import {
  OutgoingRecordQueryParams,
  toBeDispatchedRecords,
} from "@/record-management/services/api/recordOfficerService";
import { MeDto } from "@/shared/dto/user/meDto";
import { useQuery } from "@tanstack/react-query";
import { useUserDetail } from "./useUserDetail";
import { useAuthUser } from "@/shared/hooks/useAuthUser";

interface RecordContent {
  nonSmartReceivers: any;
  id: string;
  subject: string;
}

export interface PendingRecord {
  letterName: any;
  preferredLanguage: string;
  amharicSubmittedDate: string;
  amharicApprovedDate: string;
  approvedDate: string;
  initiator: any;
  from: string;
  status: string;
  id: string;
  createdAt: string;
  updatedAt: string;
  statusKey: string;
  content: RecordContent[];
  referenceNumber: string | null;
  submittedDate: string | null;
  recordTypeKey: string;
  receivingUnits: string[];
  ID: string;
  count: number;
  counts: number;
  isUrgent: boolean;
  isSecured: boolean;
}

export const usePendingRecords = (params?: OutgoingRecordQueryParams) => {
  const { userDetails } = useAuthUser();
  const { permissionKeys } = useUserDetail(userDetails as MeDto);
  const RO = permissionKeys.includes("can:dispatchRecords");

  const { data, isLoading, isError, refetch } = useQuery<{
    items: PendingRecord[];
    count: number;
  }>({
    queryKey: ["pendingRecords", params],
    queryFn: () => toBeDispatchedRecords(RO ? params : {}),
    staleTime: 60 * 1000,
    enabled: Boolean(RO),
  });

  const records = data?.items || [];
  const pendingRecordsCount = data?.count || 0;
  return {
    pendingRecordsResponse: data,
    records,
    pendingRecordsCount,
    isLoading,
    isError,
    refetch,
  };
};
