"use client";

import { useEffect, useRef } from "react";
import { useIsMutating, useQuery } from "@tanstack/react-query";
import type { ApiResponse } from "@/lib/api/types";
import { useLanguageStore } from "@/store/languageStore";
import { useSessionReady } from "@/store/useSessionReady";
import { getOpportunityById } from "../services/opportunities";
import { getLearnServeOpportunityById } from "../services/learnServe";
import { certificatesOutdatedNote, certificatesSendState, liveOpportunityStatus, type CertificatesOutdatedSource } from "../certificatesOutdated";

/**
 * A15 on the registration lists. They work from a stashed snapshot of the
 * detail, which goes stale the moment the organizer edits hours here — exactly
 * when `certificates_outdated` changes. So the live detail is read under the
 * detail page's own key (one cache, no duplicate request) and read again each
 * time this screen's mutations settle (hours, attendance, sending).
 */
export function useCertificatesOutdated(
  kind: "volunteer" | "learn-serve",
  opportunityId: string | number | null | undefined,
  /** The list's stashed status, used until the live detail has loaded. */
  stashedStatus?: string | null
) {
  const id = opportunityId == null ? "" : String(opportunityId);
  const language = useLanguageStore((s) => s.language);
  const sessionReady = useSessionReady();
  const detail = useQuery({
    queryKey: [kind === "volunteer" ? "volunteer-opportunity" : "learn-serve-opportunity", id, true],
    queryFn: (): Promise<ApiResponse<unknown>> =>
      kind === "volunteer" ? getOpportunityById(id, true) : getLearnServeOpportunityById(id),
    enabled: sessionReady && id !== "",
  });
  const mutating = useIsMutating();
  const wasMutating = useRef(false);
  const { refetch } = detail;
  useEffect(() => {
    if (wasMutating.current && mutating === 0) void refetch();
    wasMutating.current = mutating > 0;
  }, [mutating, refetch]);

  // The detail record types predate these fields; the page reads them the same way.
  const source = detail.data?.data as CertificatesOutdatedSource | undefined;
  const { needsSending, blockedReason } = certificatesSendState({ hasData: detail.data !== undefined, isError: detail.isError, source });
  return {
    needsSending,
    /** Joins the toolbars' existing `sendBlockedReason` keys. */
    blockedReason,
    /** The failed read, so the screen can explain the disabled Send and retry. */
    error: detail.isError ? detail.error : null,
    retry: () => void refetch(),
    note: certificatesOutdatedNote(source, language),
    /** Live resolved status; the stashed one until the detail has loaded. */
    opportunityStatus: liveOpportunityStatus(source, stashedStatus),
  };
}
