import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { apiClient, loadApplicantDraftBundle } from "@ump/shared";
import { getMockApplicationById, type ApplicationItem } from "@/data/mockApplications";
import { resolveApplicationDraftCaseId } from "@/lib/resolveApplicationDraftCaseId";
import { syncApplicantSubmissionFromApplicationItem } from "@/lib/applicantSubmissionRecord";
import { axiosSuccessStatusOnly, getNestedData, normalizeApplicationItem } from "@/lib/applicationReviewApi";

export type UseApplicationReviewDetailOptions = {
  enabled?: boolean;
  /**
   * When false (staff reviewing others), do not write `initiative:last-submission-v1` — avoids corrupting the reviewer’s local applicant shortcut.
   */
  syncLocalSubmission?: boolean;
};

export function useApplicationReviewDetail(
  applicationId: string,
  { enabled = true, syncLocalSubmission = true }: UseApplicationReviewDetailOptions = {},
) {
  const detailQuery = useQuery({
    queryKey: ["application-detail", applicationId],
    enabled: Boolean(applicationId) && enabled,
    queryFn: async (): Promise<ApplicationItem | null> => {
      try {
        const raw = await apiClient.get(
          `/api/applications/${encodeURIComponent(applicationId)}`,
          axiosSuccessStatusOnly,
        );
        const data = getNestedData<ApplicationItem | null>(raw);
        if (data && typeof data === "object" && "id" in data) {
          const next = normalizeApplicationItem(data as ApplicationItem & { draft_case_id?: string });
          if (syncLocalSubmission) {
            syncApplicantSubmissionFromApplicationItem(next);
          }
          return next;
        }
      } catch (e: unknown) {
        const st =
          e && typeof e === "object" && "status" in e ? Number((e as { status: unknown }).status) || 0 : 0;
        if (st >= 400 && st < 500) return null;
      }
      const mock = getMockApplicationById(applicationId) ?? null;
      if (mock) {
        const next = normalizeApplicationItem(mock);
        if (syncLocalSubmission) {
          syncApplicantSubmissionFromApplicationItem(next);
        }
        return next;
      }
      return null;
    },
  });

  const detail = detailQuery.data;

  const draftCaseIdForDetail = useMemo(
    () => (detail ? resolveApplicationDraftCaseId(detail) : ""),
    [detail],
  );

  const draftBundleQuery = useQuery({
    queryKey: ["application-draft-for-documents", applicationId, draftCaseIdForDetail],
    enabled: Boolean(applicationId) && Boolean(detail) && Boolean(draftCaseIdForDetail) && enabled,
    queryFn: () => loadApplicantDraftBundle(draftCaseIdForDetail),
    staleTime: 30_000,
    retry: 1,
  });

  return { detailQuery, draftBundleQuery, detail, draftCaseIdForDetail };
}
