"use client";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

import {
  getProgressReport,
  getSentProgressReports,
  submitMyProgressReport,
  updateMyProgressReport,
  upsertMyProgressReportIssue,
  upsertMyProgressReportRgcDecision,
} from "../service/progress-report-service";
import type { MinistryProgressReportPatchStatus } from "../service/progress-report-service";
import type { UpsertMyProgressReportIssueInput } from "../service/progress-report-service";
import type { UpsertMyProgressReportRgcDecisionInput } from "../service/progress-report-service";
import type { ProgressReportRow } from "../progress-report-data";

// Namespaced separately from the CDC-GPSF feature's query keys so the two
// caches never collide if both are ever mounted in the same client session.
export const progressReportQueryKeys = {
  all: ["ministry-progress-reports"] as const,
  list: () => [...progressReportQueryKeys.all, "list"] as const,
  detail: (progressReportId: number) =>
    [...progressReportQueryKeys.all, "detail", progressReportId] as const,
};

const EMPTY_ROWS: ProgressReportRow[] = [];

export function useProgressReports() {
  const query = useQuery({
    queryKey: progressReportQueryKeys.list(),
    queryFn: getSentProgressReports,
  });

  return {
    rows: query.data ?? EMPTY_ROWS,
    isLoading: query.isLoading,
    error:
      query.error instanceof Error
        ? query.error.message
        : query.error
          ? "Unable to load progress reports."
          : null,
  };
}

export function useProgressReport(id: string) {
  const progressReportId = Number(id);
  const isValidId =
    Number.isInteger(progressReportId) && progressReportId > 0;

  const query = useQuery({
    queryKey: progressReportQueryKeys.detail(progressReportId),
    queryFn: () => getProgressReport(progressReportId),
    enabled: isValidId,
  });

  return {
    assignment: query.data ?? null,
    isValidId,
    isLoading: isValidId && query.isLoading,
    error:
      query.error instanceof Error
        ? query.error.message
        : query.error
          ? "Unable to load the progress report."
          : null,
  };
}

export function useUpdateMyProgressReport(progressReportId: number) {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (input: {
      file?: File;
      status?: MinistryProgressReportPatchStatus;
    }) =>
      updateMyProgressReport({
        progressReportId,
        status: input.status,
        file: input.file,
      }),
    onSuccess: async () => {
      await queryClient.invalidateQueries({
        queryKey: progressReportQueryKeys.all,
      });
    },
  });
}

export function useSubmitMyProgressReport(progressReportId: number) {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: () => submitMyProgressReport(progressReportId),
    onSuccess: async () => {
      await queryClient.invalidateQueries({
        queryKey: progressReportQueryKeys.all,
      });
    },
  });
}

export function useUpsertMyProgressReportIssue(progressReportId: number) {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (
      input: Omit<UpsertMyProgressReportIssueInput, "progressReportId">,
    ) =>
      upsertMyProgressReportIssue({
        progressReportId,
        ...input,
      }),
    onSuccess: async () => {
      await queryClient.invalidateQueries({
        queryKey: progressReportQueryKeys.detail(progressReportId),
      });
    },
  });
}

export function useUpsertMyProgressReportRgcDecision(
  progressReportId: number,
) {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (
      input: Omit<
        UpsertMyProgressReportRgcDecisionInput,
        "progressReportId"
      >,
    ) =>
      upsertMyProgressReportRgcDecision({
        progressReportId,
        ...input,
      }),
    onSuccess: async () => {
      await queryClient.invalidateQueries({
        queryKey: progressReportQueryKeys.detail(progressReportId),
      });
    },
  });
}
