"use client";

import { useMemo } from "react";
import { useRouter } from "next/navigation";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import {
  getLearnServeOpportunityById,
  updateLearnServeOpportunityImages,
} from "@/features/opportunities/services/learnServe";
import {
  deleteOpportunityImage,
  downloadOpportunityImage,
} from "@/features/opportunities/services/opportunities";
import {
  issueLearnServeAttendanceCode,
} from "@/features/opportunities/services/selfCheckIn";
import { isViewerOrganizer } from "@/features/shared/opportunityButtonState";
import { toNumber } from "@/lib/helpers";
import { normalizeInterests } from "@/lib/interests";
import { useAuthStore } from "@/store/authStore";
import { useSessionReady } from "@/store/useSessionReady";
import { useLanguageStore } from "@/store/languageStore";
import { type LearnServeOpportunityData } from "./learnServeDetailsTypes";
import { learnServeTotalDuration } from "./learnServeDuration";
import {
  useLearnServeErrorRedirect,
  useLearnServeGalleries,
} from "./useLearnServeDetailsEffects";

/**
 * The record, the six mutations that act on it, and everything derived from it
 * that needs memoizing.
 *
 * Separated from the page so the page is markup and wiring only. Nothing here
 * reads dialog state, which is what keeps this hook independent of the two that
 * follow it.
 */
export function useLearnServeDetailsData(id: string) {
  const { t } = useTranslation();
  const router = useRouter();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const user = useAuthStore((s) => s.user);
  const authToken = user?.auth_token;
  const sessionReady = useSessionReady();

  const opportunityQuery = useQuery({
    // Link visibility and ownership are specific to the current account.
    queryKey: ["learn-serve-opportunity", id, user?.id ?? null, Boolean(authToken)],
    queryFn: () => getLearnServeOpportunityById(id),
    /*
     * `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(id),
  });

  const opportunityData = opportunityQuery.data?.data as
    | LearnServeOpportunityData
    | undefined;
  const refetch = opportunityQuery.refetch;

  // `/learn-serve-opportunities/{id}/` stopped sending `is_creator` and reports
  // ownership through `relationship_tags: ["organizer"]` instead, so all three
  // signals are ORed — see `isViewerOrganizer`. Declared here, above the click
  // handlers, so the creator's own Edit button can't fall through into the
  // registration flow.
  const isCreator = isViewerOrganizer(opportunityData, user?.id);

  const updateImagesMutation = useMutation({
    mutationFn: updateLearnServeOpportunityImages,
  });
  const deleteImageMutation = useMutation({
    mutationFn: deleteOpportunityImage,
  });

  /**
   * BE-192: one stable printable code, available before first start and after
   * completion. Issuance never activates scanning: the server separately gates
   * it to the start of the final scheduled day's session. Older deployments
   * can still reject early printing; display their real error until upgraded.
   */
  const issueAttendanceCodeMutation = useMutation({
    mutationFn: () => issueLearnServeAttendanceCode(id),
  });
  const downloadImageMutation = useMutation({
    mutationFn: downloadOpportunityImage,
  });

  const remainingParticipants = Math.max(
    0,
    toNumber(opportunityData?.participants_needed) -
    toNumber(opportunityData?.registered_volunteers_count)
  );

  useLearnServeErrorRedirect(
    opportunityQuery.error,
    selectedLanguage,
    t,
    router.replace,
    Boolean(opportunityData)
  );
  useLearnServeGalleries(id);

  const afterCompletedImages = useMemo(
    () =>
      opportunityData?.opportunity_images?.filter(
        (image) => image.is_after_completed
      ) ?? [],
    [opportunityData]
  );

  const interestTags = useMemo(
    () =>
      normalizeInterests(
        opportunityData?.interest_display,
        opportunityData?.interests
      ),
    [opportunityData]
  );

  const totalDuration = useMemo(
    () => learnServeTotalDuration(opportunityData),
    [opportunityData]
  );

  return {
    id,
    t,
    router,
    selectedLanguage,
    user,
    authToken,
    isLoading: opportunityQuery.isLoading,
    /* A refused or failed read (404, network, CORS) — the page must not render
       an empty, bookable shell in its place. */
    isError: opportunityQuery.isError && !opportunityData,
    error: opportunityQuery.error,
    opportunityData,
    refetch,
    isCreator,
    updateImagesMutation,
    deleteImageMutation,
    issueAttendanceCodeMutation,
    downloadImageMutation,
    remainingParticipants,
    afterCompletedImages,
    interestTags,
    totalDuration,
  };
}

export type LearnServeDetailsData = ReturnType<typeof useLearnServeDetailsData>;
