"use client";

import type { LocalizedChoice } from "@/features/shared/apiPrimitives";
import { eventTimeRange } from "../eventClock";
import { useTranslation } from "react-i18next";
import "@fancyapps/ui/dist/fancybox/fancybox.css";
import AddToCalendar from "@/components/shared/AddToCalendar";
import { DETAIL_SURFACE, DETAIL_TITLE } from "@/features/opportunities/components/opportunityDetailLayout";
import { formatSingleDate } from "@/lib/helpers";
import LocationLink from "@/components/ui/LocationLink";
import LearnServeCoverGallery from "@/features/opportunities/components/LearnServeCoverGallery";
import {
  asset,
  DetailRow,
  } from "./eventDetailsParts";
import type { EventDetailsData } from "./eventDetailsParts";
import AssetIcon from "@/components/ui/AssetIcon";
import { eventCardLocation, eventGalleryImages } from "../eventCardFields";
import { CARD_TAG_CLASS } from "@/features/opportunities/cardStatusBadges";

/**
 * The event detail page's main column: title, description, the detail rows
 * and the primary action.
 *
 * Takes explicit props rather than the page's state bag: an `any` bag
 * typechecks even for a name that does not exist on it.
 */
export default function EventDetailsMain({
  event,
  isCreator,
  statusLabel,
  language,
  description,
  displayValue,
  actionButton,
  router,
}: {
  event: EventDetailsData;
  isCreator: boolean;
  statusLabel?: string;
  language: string;
  /** Sanitized on the page, because `sanitizeRichText` is server-side. */
  description: string;
  displayValue: (value?: LocalizedChoice | null) => string;
  actionButton: (mobile?: boolean) => React.ReactNode;
  router: { push: (href: string) => void };
}) {
  const { t } = useTranslation();
  /* A new event has a location link only (PDF p.22 removed the text
     location), so the link needs words of its own — it used to render as an
     empty, invisible anchor. The calendar entry takes the link as its place. */
  const placeLabel = eventCardLocation(event, language);
  const calendarPlace = placeLabel || event.location_url || null;

  return (
  <main className={`opportunity-detail-main min-w-0 ${DETAIL_SURFACE}`}>
    <div className="flex items-start justify-between gap-5">
      <div className="min-w-0 flex-1">
        {statusLabel && <span role="status" className={`mb-3 inline-block rounded-full px-3 py-1 text-sm ${CARD_TAG_CLASS.state}`}>{statusLabel}</span>}
        <h2 className={DETAIL_TITLE}>
          {(event.primary_language === "ar" ? event.title_ar : event.title_en) ?? ""}
        </h2>
      </div>
      <div className={`flex shrink-0 flex-col gap-3 pt-1 ${isCreator ? "" : "xss:hidden"}`}>
        {actionButton()}
      </div>
    </div>

    <DetailRow icon={asset("homepage/learn_type.svg")} label={t("COMMON.TYPE")}>
      {displayValue(event.event_type_display)}
    </DetailRow>

    <div className="grid grid-cols-1 md:grid-cols-2">
      <DetailRow icon={asset("homepage/dateicn.svg")} label={t("COMMON.START.DATE")}>
        {formatSingleDate(event.start_date, language, t)}
      </DetailRow>
      <DetailRow icon={asset("homepage/dateicn.svg")} label={t("COMMON.END.DATE")}>
        {formatSingleDate(event.end_date, language, t)}
      </DetailRow>
      {eventTimeRange(event.start_time, event.end_time, t) && <DetailRow icon={asset("homepage/timeicn.svg")}>
        {eventTimeRange(event.start_time, event.end_time, t)}
      </DetailRow>}
    </div>

    {/* Sits with the dates it copies — Google Calendar, or an .ics
        for Apple Calendar / Outlook. */}
    <div className="flex">
      <AddToCalendar
        payload={{
          title_en: event.title_en,
          title_ar: event.title_ar,
          location_en: calendarPlace,
          location_ar: calendarPlace,
          start_date: event.start_date,
          end_date: event.end_date,
          start_time: event.start_time,
          end_time: event.end_time,
        }}
      />
    </div>

    <div className="mb-5 border-b border-[#EEEDF4] pb-3">
      <div className="flex xss:flex-col">
        <div className="w-1/2 pt-5 xss:w-full">
          <DetailRow icon={asset("homepage/locations.svg")}>
            <LocationLink
              address={placeLabel || t("COMMON.OPEN_IN_MAPS")}
              locationUrl={event.location_url}
              latitude={event.latitude}
              longitude={event.longitude}
              className="line-clamp-1 hover:underline"
            />
          </DetailRow>
          {event.from_age ? (
            <DetailRow icon={asset("voluneteerevent/age.svg")} label={t("COMMON.AGE")}>
              {event.from_age}
              {event.to_age ? ` - ${event.to_age}` : " +"}
            </DetailRow>
          ) : null}
          {event.gender_display?.value_en ? (
            <DetailRow icon={asset("voluneteerevent/gender.svg")} label={t("COMMON.GENDER")}>
              {displayValue(event.gender_display)}
            </DetailRow>
          ) : null}
        </div>
        {!isCreator && <div className="hidden xss:flex xss:flex-col xss:gap-3">
          {actionButton(true)}
        </div>}
      </div>
    </div>

    <section className="mb-6">
      <div className="mb-3 flex items-center justify-between">
        <h2 className="flex items-center gap-2 text-sm font-bold text-primary-5 md:text-base">
          {/* 22x22, the SVG's own box. Unsized, this heading's text shifted
              sideways as the arrow loaded. */}
          <AssetIcon
            src={asset("voluneteerevent/rightarrows.svg")}
            size={22}
            className={language === "ar" ? "rotate-180" : ""}
          />
          {t("COMMON.DESCRIPTION")}
        </h2>
      </div>
      <div
        className="text-sm font-normal text-secondary-102 md:text-base"
        dangerouslySetInnerHTML={{ __html: description }}
      />
    </section>

    {event.interest_display?.length ? (
      <div className="mb-6 mt-6 flex flex-wrap items-center gap-6 xss:gap-2">
        <AssetIcon src={asset("voluneteerevent/label.svg")} size={30} />
        {/* No annotation: the element type comes from `EventDetailRecord`,
            which is `EventInterestDisplay` — only the two labels, both
            nullable, and **no `id`**. Annotating it `ChoiceDisplay` claimed an
            `id` and a `slug` the key does not carry. */}
        {event.interest_display.map((interest, index) => {
          const value = displayValue(interest);
          const colors = ["#70B4C2", "#FC9555", "#D9EF61", "#5271FF"];
          return (
            <button
              /* `value`, not `interest.id`: `websiteInterestDisplay()` emits
                 only the two labels, so `id` was `undefined` on every chip and
                 React fell back to the index with a key warning. The label is
                 what distinguishes these. */
              key={value || index}
              type="button"
              style={{ backgroundColor: colors[index % colors.length] }}
              className={`rounded-[20px] px-8 py-[13px] text-sm ${
                index % colors.length === 3 ? "text-white" : "text-primary-5"
              }`}
              onClick={() =>
                router.push(`/events-and-activities?tags=${encodeURIComponent(value)}`)
              }
            >
              {value}
            </button>
          );
        })}
      </div>
    ) : null}

    <LearnServeCoverGallery
      id={`event-${event.id}`}
      galleryId={`event-gallery-${event.id}`}
      coverImages={eventGalleryImages(event).map((image) => ({
        id: image.id,
        image: image.image ?? undefined,
      }))}
      coverGalleryTitle={(language === "ar" ? event.title_ar : event.title_en) ?? ""}
    />

  </main>
  );
}
