"use client";

import { DETAIL_CONTAINER, DETAIL_COLUMNS, DETAIL_SURFACE } from "./opportunityDetailLayout";
import { useState } from "react";
import { Info } from "lucide-react";
import { useLanguageStore } from "@/store/languageStore";
import { certificatesOutdatedNote } from "@/features/opportunities/certificatesOutdated";
import moment from "moment";
import { useClock } from "@/hooks/useClock";
import { useTranslation } from "react-i18next";
import Button from "@/components/ui/Button";
import Loader from "@/components/ui/Loader";
import { SponsorsClient } from "@/features/home";
import {
  getOpportunityButtonState,
  isOpportunityButtonActionable,
} from "@/features/shared/opportunityButtonState";
import { useAuthStore } from "@/store/authStore";
import AttendancePanel from "./volunteer-event/AttendancePanel";
import CompletionGallery from "./volunteer-event/CompletionGallery";
import CreatorActionBar from "./volunteer-event/CreatorActionBar";
import OpportunityDescription from "./volunteer-event/OpportunityDescription";
import OpportunityFacts from "./volunteer-event/OpportunityFacts";
import OpportunityHeader, {
  ViewerActionButton,
} from "./volunteer-event/OpportunityHeader";
import OpportunitySchedule from "./volunteer-event/OpportunitySchedule";
import OrganizerCard from "./volunteer-event/OrganizerCard";
import RegistrationFlowModals, {
  type RegistrationStep,
} from "./volunteer-event/RegistrationFlowModals";
import RejectionNotice from "./volunteer-event/RejectionNotice";
import SelfScanPanel from "./volunteer-event/SelfScanPanel";
import SponsorsCard from "./volunteer-event/SponsorsCard";
import { useVolunteerOpportunity } from "./volunteer-event/useVolunteerOpportunity";
import { deriveVolunteerEventView } from "./volunteer-event/volunteerEventView";

/**
 * `/volunteer-event-detail/{id}` — one volunteering opportunity.
 *
 * This file is composition only. What the page *shows* is decided by
 * `deriveVolunteerEventView` (a pure function of the payload and the viewer);
 * each section in `./volunteer-event/` renders one part of it and owns its own
 * dialogs and mutations. The one piece of state left here is which step of the
 * registration flow is open, because the Register button that starts it
 * appears twice — once in the header, once below the details on a phone.
 */
export default function VolunteerEvent({
  opportunityId,
  organizationId,
}: {
  opportunityId: string;
  organizationId?: string;
}) {
  const { t } = useTranslation();
  const language = useLanguageStore((state) => state.language);
  const clock = useClock(1000);
  const user = useAuthStore((s) => s.user);
  const [registrationStep, setRegistrationStep] =
    useState<RegistrationStep | null>(null);

  const { data, isLoading, isError, isRefetching, refetch } = useVolunteerOpportunity(opportunityId);

  // A failed request (not the 404, which the hook redirects) gets a retry
  // rather than a loader that never ends.
  if (isError && !data) {
    return (
      <div role="alert" className="mx-auto flex w-[90%] max-w-md flex-col items-center gap-4 py-20 text-center">
        <h2 className="text-2xl font-bold text-primary-5">{t("COMMON.SOMETHING_WENT_WRONG")}</h2>
        <Button type="button" variant="primary" size="medium" disabled={isRefetching} onClick={() => { void refetch(); }}>
          {t("COMMON.TRY_AGAIN")}
        </Button>
      </div>
    );
  }
  // No data otherwise is a load in flight, or a 404 on its way to `/404`.
  if (isLoading || !data) return <Loader />;

  const view = deriveVolunteerEventView(data, {
    id: user?.id,
    signedIn: Boolean(user),
    hasAuthToken: Boolean(user?.auth_token),
    isVerified: user?.is_verified === true,
    userType: user?.user_type,
  }, moment(clock));

  /**
   * Where the registration flow starts for this viewer. Only viewers reach it —
   * the creator's Edit / Repost is its own control in the icon row.
   */
  const handleRegisterClick = () => {
    // Started / Ended / Full / Closed never open a flow. The button is
    // disabled for them already; this also guards any other caller.
    if (!isOpportunityButtonActionable(getOpportunityButtonState(data))) return;

    if (!user?.auth_token) {
      setRegistrationStep("login");
      return;
    }
    setRegistrationStep(
      data.is_registered
        ? "unregister"
        : data.total_roles > 0
          ? "roles"
          : "confirm",
    );
  };

  return (
    <div className="w-full bg-[#F7F7FB]">
      <RegistrationFlowModals
        step={registrationStep}
        onStepChange={setRegistrationStep}
        opportunityId={opportunityId}
        organizationId={organizationId}
        opportunityDetails={{
          title_ar: data.title_ar,
          title_en: data.title_en,
          start_date: data.start_date,
          daily_hours: data.volunteer_hours_per_day,
          // A volunteering opportunity keeps its WhatsApp in `link`.
          whatsapp_link: data.link,
        }}
        refetch={refetch}
      />

      <div className={DETAIL_CONTAINER}>
        <div className={DETAIL_COLUMNS}>
          {/* Organizer column */}
          <div>
            <div>
              <OrganizerCard data={data} isCreator={view.isCreator}>
                <SponsorsCard sponsors={data.opportunity_sponsor_images} />
                <SelfScanPanel
                  data={data}
                  isCreator={view.isCreator}
                  onRecorded={refetch}
                />
                <AttendancePanel data={data} view={view} />
              </OrganizerCard>
            </div>
          </div>

          {/*
            Details column, with the creator's action rail as its sibling — the
            same two-part shape as the development page (`LearnServeDetails`).
            The rail used to sit inside the header, which squeezed the title and
            reflowed as actions appeared; beside the column it runs the full
            height of the content and keeps a fixed order.

            It renders nothing for a viewer, so `gap-5` costs them nothing.
          */}
          <div className={`opportunity-detail-main grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-start gap-x-3 ${DETAIL_SURFACE}`}>
            {view.isCreator && certificatesOutdatedNote(view.certificatesOutdated, language) && (
              <div role="status" className="col-span-2 mb-5 flex min-w-0 items-start gap-2 rounded-xl border border-primary-5/15 bg-primary-5/5 px-4 py-3 text-sm leading-relaxed text-primary-5">
                <Info className="mt-0.5 h-5 w-5 shrink-0" aria-hidden="true" />
                <p className="min-w-0 break-words">{certificatesOutdatedNote(view.certificatesOutdated, language)}</p>
              </div>
            )}
            <div className="min-w-0">
              <div className="w-full">
                <OpportunityHeader
                  data={data}
                  view={view}
                  onRegisterClick={handleRegisterClick}
                />

                {view.isRejected && (
                  <RejectionNotice reason={data.rejected_reason} />
                )}

                <OpportunitySchedule data={data} />

                <div className="mb-5 border-b border-[#EEEDF4] pb-3">
                  <OpportunityFacts data={data} />
                  {/* The phone copy of the header's Register button. */}
                  <div className="hidden xss:block">
                    <ViewerActionButton
                      view={view}
                      onClick={handleRegisterClick}
                      className="whitespace-nowrap mb-5 w-full !h-11 mt-4 disabled:opacity-50 disabled:cursor-not-allowed"
                    />
                  </div>
                </div>

                <OpportunityDescription data={data} />
              </div>
            </div>

            <CreatorActionBar
              opportunityId={String(data.id)}
              view={view}
              onChanged={refetch}
            />
            <div className="col-span-2 min-w-0">
                <CompletionGallery
                  data={data}
                  isCreator={view.isCreator}
                  onChanged={refetch}
                />
            </div>
          </div>
        </div>
      </div>

      <div className="border-t bg-white pt-6 md:pt-8">
        <SponsorsClient />
      </div>
    </div>
  );
}
