"use client";

import React from "react";
import moment from "moment";
import { useClock } from "@/hooks/useClock";
import { canEditOrDelete, isViewerOrganizer } from "@/features/shared/opportunityButtonState";
import { eventSchedule } from "../eventLifecycle";
import "react-multi-carousel/lib/styles.css";
import { useTranslation } from "react-i18next";
import Link from "next/link";
import Image from "next/image";
import { eventTimeRange } from "../eventClock";
import { formatDateRange } from "@/lib/helpers";
import {
  type EventData,
} from "./eventListCardTypes";
import {
  eventTitleText,
  type EventTitlePair,
} from "@/features/events/eventRecord";
import IconButton from "@/components/ui/IconButton";
import EventPaidBadge from "./EventPaidBadge";
import { eventCardImage } from "../eventCardFields";

/**
 * An event row's image panel: cover photo, date strip and the organiser's
 * edit/delete controls.
 */
export default function EventListTileMedia({
  item,
  user,
  selectedLanguage,
  onRequestDelete,
  is_homepage,
}: {
  item: EventData;
  user: { id?: number | string } | null | undefined;
  selectedLanguage: string;
  onRequestDelete: (info: {
    isOpen: boolean;
    eventId?: string;
    eventTitle?: EventTitlePair;
  }) => void;
  is_homepage: boolean;
}) {
  const { t } = useTranslation();
  const clock = useClock(1000);
  const canDelete = Boolean(clock) && canEditOrDelete(eventSchedule(item), moment(clock));

  return (
<div className="relative">
  <Link href={`/event-details/${item.id}`} key={item.id}>
    {/* Square (1:1), matching the upload form and the other cards. */}
    <div className="relative w-full aspect-square">
      <Image
        src={eventCardImage(item) || "/assets/homepage/treeplanting.png"}
        alt={eventTitleText(item, selectedLanguage)}
        fill
        className="border border-[#484848] border-b-0 rounded-t-[20px] object-cover"
        unoptimized
      />
    </div>

    <EventPaidBadge
      participationTypeEn={item?.participation_type_display?.value_en}
      paidRegistration={item?.paid_registration}
    />
    <div className="card-schedule-strip grid grid-cols-2 text-sm text-gray-600 bg-[#000000B2]/70 absolute w-full bottom-0 h-[39px] items-center z-10">
      <span className="flex miniscreen3:text-[12px] smallscreen:text-[10px] laptopitms:text-xs text-white justify-center gap-2 items-center 2xl:text-base laptopmain:text-sm md:text-sm miniscreen1:text-[13px] xs:text-xs">
        <Image
          className="w-4 h-4"
          src="/assets/homepage/dateicn.svg"
          alt=""
          width={16}
          height={16}
          unoptimized
        />
        {formatDateRange(item.start_date, item.end_date, selectedLanguage, t)}
      </span>
      <div className="h-[60%] w-[1px] bg-white absolute left-1/2 top-[8px]"></div>
      <span className="text-white miniscreen3:text-[12px] smallscreen:text-[10px] laptopitms:text-xs flex justify-center gap-2 items-center 2xl:text-base laptopmain:text-sm md:text-sm miniscreen1:text-[13px] xs:text-xs">
        <Image
          src="/assets/homepage/timeicn.svg"
          className="w-4 h-4"
          alt=""
          width={16}
          height={16}
          unoptimized
        />
        {eventTimeRange(item.start_time, item.end_time, t)}
      </span>
    </div>
  </Link>
    {user?.id != null && isViewerOrganizer(item, user.id) && (
        <div className="absolute -left-3 -top-3 z-10">
          {/*
            A real button. This is a *destructive* control that used to be an
            `<Image onClick>`: unreachable by keyboard, and announced as a
            graphic rather than as something that deletes the event. The icon now
            carries `alt=""` because the accessible name belongs to the button —
            otherwise a screen reader reads both.

            It is a **sibling** of the tile's `<Link>`, not a child of it. A
            `<button>` inside an `<a>` is invalid content and leaves the two
            controls fighting over the same click and the same Tab stop; the
            earlier version nested them and relied on `stopPropagation` to undo
            the navigation. Hoisted out, the positioning context is unchanged —
            `absolute` still resolves to the same wrapping `div.relative` — so
            the control sits exactly where it did, and no longer needs to
            cancel an event it can no longer receive.
          */}
          <IconButton
            label={t(canDelete ? "COMMON.DELETE_EVENT" : "COMMON.EDIT_WINDOW_CLOSED")}
                disabled={!canDelete}
            className="cursor-pointer disabled:cursor-not-allowed disabled:opacity-40"
            onClick={() =>
              onRequestDelete({
                isOpen: true,
                /* The deletion endpoint takes the id in the URL path,
                   so the modal's contract is a string. */
                eventId: String(item.id),
                eventTitle: {
                  title_en: item.title_en,
                  title_ar: item.title_ar,
                },
              })
            }
          >
            <Image
              src={
                is_homepage
                  ? "/assets/voluneteerevent/card_delete_icon_orange.svg"
                  : "/assets/voluneteerevent/card_delete_icon.svg"
              }
              alt=""
              width={27}
              height={27}
              unoptimized
            />
          </IconButton>
        </div>
      )}
</div>
  );
}
