import { useState } from "react";
import { SendLetterDto } from "@/record-management/dto/IncomingRecords/IncomingLetterDto";
import {
  createIncoming,
  updateIncoming,
} from "@/record-management/services/api/nonSmartOfficeService";
import { nonSmartOfficeFileService } from "@/record-management/services/api/nonSmartOfficeFileService";
import { useTranslation } from "react-i18next";
import { CreateLetterResult } from "@/external-portal/hooks/useCreateExternalLetterRecord";
import { EditLetterFormValues } from "../recordOfficer/incomingRecords/AddIncoming/Form-Schema";
import { useQueries, useQuery } from "@tanstack/react-query";
import { data } from "jquery";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

export const useIncomings = () => {
  const [isSending, setIsSending] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  const sendLetterAndUploadFile = async (
    values: SendLetterDto,
    file: File,
  ): Promise<CreateLetterResult> => {
    let recordId: string | null = null;
    try {
      setIsSending(true);

      const createRes = await createIncoming(values);
      recordId = createRes.recordId;
      const { presigned: uploadUrl } = createRes;

      if (!recordId || !uploadUrl) {
        return Promise.reject(
          new Error("Failed to create record or get upload URL"),
        );
      }

      await nonSmartOfficeFileService.uploadFile(file, uploadUrl);
      await nonSmartOfficeFileService.updateStatus(recordId, true);

      setIsUploading(true);

      return createRes; // ✅ Now sendletterResponse.data works
    } catch (error) {
      // If upload failed, mark status as false
      if (recordId) {
        try {
          await nonSmartOfficeFileService.updateStatus(recordId, false);
        } catch (statusError) {
          await handleError(statusError);
        }
      }
      return Promise.reject(error);
    } finally {
      setIsSending(false);
      setIsUploading(false);
    }
  };

  return {
    sendLetterAndUploadFile,
    isSending,
    isUploading,
  };
};

export const useUpdateIncoming = () => {
  const [isUpdating, setIsUpdating] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  const updateIncomingRecord = async (
    payload: any,
    id: string,
    file?: File,
  ): Promise<any> => {
    try {
      setIsUpdating(true);
      // 1. Update metadata
      const updatedRes = await updateIncoming(payload, id);

      const { presigned: uploadUrl } = updatedRes;

      // 2. If a new file is provided, upload it
      if (file && uploadUrl) {
        try {
          await nonSmartOfficeFileService.uploadFile(file, uploadUrl);
          await nonSmartOfficeFileService.updateStatus(id, true);
        } catch (uploadError) {
          // If upload failed, mark status as false
          try {
            await nonSmartOfficeFileService.updateStatus(id, false);
          } catch (statusError) {
            await handleError(statusError);
          }
          throw uploadError;
        }
      }

      return updatedRes;
    } catch (error) {
      return Promise.reject(error);
    } finally {
      setIsUpdating(false);
      setIsUploading(false);
    }
  };

  return {
    updateIncomingRecord,
    isUpdating,
    isUploading,
  };
};

export const useGetUploadingUrl = (file: File[]) => {
  const {
    data: uploadFileUrl,
    isLoading,
    error,
  } = useQuery({
    queryKey: ["uploadUrl"],
    queryFn: () => nonSmartOfficeFileService.getFileUploadUrl(file),
  });
  return {
    uploadFileUrl,
    isLoading,
    error,
  };
};
