"use client";

import { useState } from "react";
import moment from "moment";
import { useRouter } from "next/navigation";
import { useClock } from "@/hooks/useClock";
import { hasOpportunityEnded, isOpportunityCancelled } from "@/features/shared/clientReviewPolicy";
import { eventExternalRegistrationLink, eventSchedule, externalHref } from "../eventLifecycle";
import type { EventRecord } from "../eventRecord";
import { getEventById } from "../services/eventsApi";

export type EventCardActionSource = Pick<EventRecord, "id"> & Partial<Pick<EventRecord, "start_date" | "end_date" | "start_time" | "end_time" | "event_status" | "participation_type_display" | "paid_registration">>;

/** Cards omit registration_link; resolve it on demand from the public detail endpoint. */
export function useEventCardAction(event: EventCardActionSource, detailHref: string) {
  const router = useRouter();
  const clock = useClock(1000);
  const [loading, setLoading] = useState(false);
  const requiresRegistration = event.paid_registration ?? event.participation_type_display?.value_en === "Paid Event";
  const schedule = eventSchedule(event);
  const available = Boolean(clock) && requiresRegistration && !hasOpportunityEnded(schedule, moment(clock)) && !isOpportunityCancelled(schedule);

  const onClick = async () => {
    if (loading) return;
    if (!available) { router.push(detailHref); return; }
    setLoading(true);
    try {
      const response = await getEventById({ id: String(event.id) });
      const current = eventSchedule(response.data);
      const href = externalHref(eventExternalRegistrationLink(response.data));
      if (href && !hasOpportunityEnded(current) && !isOpportunityCancelled(current)) {
        window.location.assign(href);
        return;
      }
      router.push(detailHref);
    } catch {
      router.push(detailHref);
    } finally {
      setLoading(false);
    }
  };
  return { loading, onClick, label: requiresRegistration ? "COMMON.REGISTER" : "COMMON.DETAILS" };
}
