"use client";

import { DETAIL_CONTAINER, DETAIL_COLUMNS } from "@/features/opportunities/components/opportunityDetailLayout";
import moment from "moment";
import { useClock } from "@/hooks/useClock";
import { eventSchedule, eventStateLabel, eventExternalRegistrationLink, externalHref } from "../eventLifecycle";
import EventDeletionAction from "./EventDeletionAction";
import type { LocalizedChoice } from "@/features/shared/apiPrimitives";
import { useTranslation } from "react-i18next";
import "@fancyapps/ui/dist/fancybox/fancybox.css";
import { Button } from "@/components/ui/Button";
import Loader from "@/components/ui/Loader";
import { SponsorsClient } from "@/features/home";
import { NAV_STATE_KEYS, setNavState } from "@/lib/navigationState";
import { sanitizeRichText } from "@/lib/sanitizeRichText";
import { socialLinks } from "./eventDetailsParts";
import { getReadErrorMessage } from "@/lib/api/errors";
import { useEventDetails } from "./useEventDetails";
import EventDetailsMain from "./EventDetailsMain";
import EventDetailsAside from "./EventDetailsAside";
import EventActionConfirmModal from "./EventActionConfirmModal";
import EventDetailsActionButton from "./EventDetailsActionButton";
import { hasOpportunityEnded } from "@/features/shared/clientReviewPolicy";
import { canEditOrDelete, isCreatorRepostState } from "@/features/shared/opportunityButtonState";
import { profilePath } from "@/lib/profilePath";
import RejectionNotice from "@/features/opportunities/components/volunteer-event/RejectionNotice";

export default function EventDetails({ eventId }: { eventId: string }) {
  const { t } = useTranslation();
  const {
    language,
    user,
    router,
    eventQuery,
    event,
    isCreator,
    showPrimaryActionConfirm,
    setShowPrimaryActionConfirm,
  } = useEventDetails(eventId);

  const clock = useClock(1000);
  const now = moment(clock);
  if (eventQuery.isLoading) return <Loader />;
  if (eventQuery.isError || !event) {
    return (
      <div role="alert" className="mx-auto max-w-3xl py-24 text-center">
        <p className="mb-6 text-lg text-red-600">
          {/* A network error or a 500 is not «not found»: only a 404 (or a read with no record) says so. */}
          {eventQuery.isError
            ? getReadErrorMessage(eventQuery.error, language, { notFound: t("COMMON.EVENT_NOT_FOUND"), failed: t("COMMON.DETAILS_LOAD_FAILED") })
            : t("COMMON.EVENT_NOT_FOUND")}
        </p>
        <Button size="medium" onClick={() => eventQuery.refetch()}>
          {t("COMMON.RETRY")}
        </Button>
      </div>
    );
  }

  /* One rule for this, in `lib/profilePath.ts` — nine copies of it had drifted. */
  const organizerPath = profilePath(event.created_by?.id);
  // The description is always shown in full — the View More toggle was removed.
  // Rendered as HTML, so it is sanitized first: the backend stores the editor's
  // markup verbatim and any organization account can author it.
  const description = sanitizeRichText(
    event.primary_language === "ar"
      ? event.description_ar
      : event.description_en,
  );
  /* `WebsiteChoiceDisplay | null`: the detail payload's `*_display` keys come
     from `websiteChoicePayload()`, which drops its null entries — so each
     field can be *absent* as well as null, and the whole object is null when
     the relation is unset. The `|| ""` already covered all three. */
  const displayValue = (value?: LocalizedChoice | null) =>
    value?.[language === "ar" ? "value_ar" : "value_en"] || "";
  const schedule = eventSchedule(event);
  const statusKey = clock ? eventStateLabel(event, now) ?? "COMMON.UPCOMING" : null;
  const isActive = Boolean(clock) && !hasOpportunityEnded(schedule, now) && event.event_status !== "cancelled";

  // Whether the creator's icon means Edit or Repost — derived once, since the
  // button, its icon, its dialog copy and the nav payload all read it.
  const isRepostState = isCreatorRepostState(schedule, now);

  const goToEventForm = () => {
    setNavState(NAV_STATE_KEYS.eventForm, {
      id: String(event.id),
      isRepublish: isRepostState,
    });
    router.push("/event-form");
  };

  const actionButton = (mobile = false) => (
    <div className="flex flex-col items-center gap-2">
    <EventDetailsActionButton
      mobile={mobile}
      isCreator={isCreator}
      isBanned={user?.is_banned}
      isRepostState={isRepostState}
      isActive={isActive}
      isCancelled={event.event_status === "cancelled"}
      canEdit={Boolean(clock) && canEditOrDelete(schedule, now)}
      /* Normalized: a legacy link stored without a scheme opened as a path on Fursa. */
      registrationLink={externalHref(eventExternalRegistrationLink(event))}
      /* Edit goes straight to the form; only Repost asks, because only
         Repost creates a second event. Same rule as both opportunity
         screens. */
      onManage={
        isRepostState ? () => setShowPrimaryActionConfirm(true) : goToEventForm
      }
    />
    {isCreator && !user?.is_banned && <EventDeletionAction event={event} onChanged={() => { void eventQuery.refetch(); }} />}
    </div>
  );

  return (
    <div className="w-full bg-[#F7F7FB]">
      <div className={DETAIL_CONTAINER}>
        {/* Owner-only field (BE-106): the organizer learns why the event is not public. */}
        {isCreator && event.approval_status === "rejected" && <RejectionNotice reason={event.rejected_reason} />}
        <div className={DETAIL_COLUMNS}>
          <EventDetailsAside
            event={event}
            language={language}
            organizerPath={organizerPath}
            socialLinks={socialLinks}
          />

          <EventDetailsMain
            event={event}
            isCreator={isCreator}
            statusLabel={statusKey && statusKey !== "COMMON.UPCOMING" ? t(statusKey) : undefined}
            language={language}
            description={description}
            displayValue={displayValue}
            actionButton={actionButton}
            router={router}
          />
        </div>
      </div>

      <div className="border-t bg-white pt-10 2xl:pt-[70px]">
        <SponsorsClient />
      </div>

      {/* The creator's icon confirms before it navigates, matching the two
          opportunity detail screens. Repost reads as "edit" at a glance but
          creates a second event, so the copy says the original survives. */}
      <EventActionConfirmModal
        showPrimaryActionConfirm={showPrimaryActionConfirm}
        setShowPrimaryActionConfirm={setShowPrimaryActionConfirm}
        isRepostState={isRepostState}
        goToEventForm={goToEventForm}
      />
    </div>
  );
}
