"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import "@fancyapps/ui/dist/fancybox/fancybox.css";
import { getEventById } from "@/features/events/services/eventsApi";
import { isViewerOrganizer } from "@/features/shared/opportunityButtonState";
import { useAuthStore } from "@/store/authStore";
import { useSessionReady } from "@/store/useSessionReady";
import { useLanguageStore } from "@/store/languageStore";
import { Fancybox as NativeFancybox } from "@fancyapps/ui";
import {
  localizedError,
  type EventDetailsData,
} from "./eventDetailsParts";

/**
 * One event's detail page: the event itself, its sponsors, and the
 * register/unregister calls.
 */
export function useEventDetails(eventId: string) {
  const { t } = useTranslation();
  const language = useLanguageStore((state) => state.language);
  const user = useAuthStore((state) => state.user);
  const sessionReady = useSessionReady();
  const router = useRouter();

  // Bind Fancybox to the event image gallery
  useEffect(() => {
    const galleryId = `event-gallery-${eventId}`;
    NativeFancybox.bind(`[data-fancybox="${galleryId}"]`, {
      showClass: "fancybox-zoomIn",
      hideClass: "fancybox-zoomOut",
    });
    return () => {
      NativeFancybox.unbind(`[data-fancybox="${galleryId}"]`);
      NativeFancybox.close();
    };
  }, [eventId]);

  const eventQuery = useQuery({
    queryKey: ["event-details", eventId, user?.id ?? "guest", Boolean(user?.auth_token)],
    queryFn: () => getEventById({ id: eventId, passToken: Boolean(user?.auth_token) }),
    /*
     * `sessionReady` as well as the id: the token is part of the key, and on
     * the client the first render deliberately works from the signed-out
     * server snapshot (see `useSessionReady`). Without this the query would
     * fire once keyed `false` and again keyed `true`, so every signed-in
     * reader of this screen would cost two requests instead of one. The wait
     * is a single render, before paint, not a round trip.
     */
    enabled: sessionReady && Boolean(eventId),
  });
  const event = eventQuery.data?.data as EventDetailsData | undefined;

  /**
   * `/events/{id}/` sends both `is_creator` and (since 2026-09-07)
   * `relationship_tags`, so ownership goes through the one shared derivation
   * every other detail screen uses — see BE-02 in `docs/resolved/BACKEND_ISSUES_ROUND_1.md`.
   * That keeps this screen working if `is_creator` is ever dropped here the way
   * it already was on the two opportunity resources.
   */
  const isCreator = user?.id != null && isViewerOrganizer(event, user.id);

  // Declared above the loading/error early returns below — a hook after them
  // runs conditionally, which React forbids.
  const [showPrimaryActionConfirm, setShowPrimaryActionConfirm] =
    useState(false);

  useEffect(() => {
    const responseStatus = (
      eventQuery.error as { response?: { status?: number; data?: unknown } }
    )?.response?.status;
    if (responseStatus !== 404) return;

    toast.error(
      localizedError(eventQuery.error, language, t("COMMON.EVENT_NOT_FOUND"))
    );
    router.replace("/404");
  }, [eventQuery.error, language, router, t]);

  return {
    language,
    user,
    router,
    eventQuery,
    event,
    isCreator,
    showPrimaryActionConfirm,
    setShowPrimaryActionConfirm,
  };
}
