import { CreateLetterDto } from "@/shared/dto/External-Portal/External-PortalDto";
import { useState } from "react";
import {
  createExternalLetterRecord,
  externalParam,
  getExternalLetterRecord,
} from "../services/portalOutgoingService";
import { nonSmartOfficeFileService } from "@/record-management/services/api/nonSmartOfficeFileService";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { fetchLetterById } from "@/record-management/services/api/userRecordService";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

export interface CreateLetterResult {
  recordId: string;
  contentId: string;
  fileInfo: {
    bucket: string;
    fileName: string;
    contentType: string;
    originalname: string;
    size: number;
  };
  presigned: string;
}

export const useExternalPortal = (params?: externalParam) => {
  const [isSending, setIsSending] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

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

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

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

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

      setIsUploading(true);

      // Return the record information here
      return createRes.data;
    } 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);
    }
  };

  const {
    data: externalLettersData = [],
    isLoading: isFetchingLetters,
    isError,
    refetch,
  } = useQuery({
    queryKey: ["external-letters", params],
    queryFn: async () => {
      const res = await getExternalLetterRecord(params);
      return res.data; // adjust if you need metadata too
    },
  });

  const ExternalLetters = externalLettersData.items || [];
  const ExternalCount = externalLettersData.count || 0;

  return {
    createExternalPortalLetter,
    ExternalLetters,
    ExternalCount,
    isFetchingLetters,
    isError,
    refetchExternalLetters: refetch,
    isSending,
    isUploading,
  };
};

export const attachmentResponse = (id: string) => {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  return useQuery({
    queryKey: ["record-pdf", id],
    queryFn: () => fetchLetterById(id),
    enabled: !!id,
  });
};
