import { useCallback } from "react";
import { toast } from "sonner";
import EnhancedDynamicModal from "@/record-management/common/EnhancedDynamicModal";
import { useTranslation } from "react-i18next";
import { useQuery } from "@tanstack/react-query";
import { fetchLetterById } from "@/record-management/services/api/userRecordService";

interface DownloadRecordProps {
  recordId: string;
  onSuccess: () => void;
  onClose: () => void;
}

const DownloadRecord: React.FC<DownloadRecordProps> = ({
  recordId,
  onSuccess,
  onClose,
}) => {
  const {
    data: data,
    isLoading: isLoadingAttachment,
    error: errorAttachment,
    refetch: refetchAttachment,
  } = useQuery({
    queryKey: ["record-pdf", recordId],
    queryFn: () => fetchLetterById(recordId!),
    enabled: !!recordId,
    retry: false,
  });
  const { t } = useTranslation();
  const handleDownload = useCallback(async () => {
    try {
      if (!data?.presigned) {
        toast.error("PDF not available.");
        return;
      }

      const response = await fetch(data?.presigned); // make sure it's a valid URL
      const blob = await response.blob();

      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `${data?.fileInfo.originalname}.pdf`;
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);

      toast.success(t("userRecord.Download successful!"));
      onSuccess();
    } catch (error) {
      console.error(error);
      toast.error(t("userRecor.Failed to download PDF."));
    }
  }, [data, recordId, onSuccess]);

  return (
    <EnhancedDynamicModal
      title={t("userRecord.Download Record PDF")}
      open={true}
      onClose={onClose}
      actionConfig={{
        type: "download",
        onAction: handleDownload,
        confirmText: t("userRecord.Downloaded"),
        confirmVariant: "default",
      }}
    ></EnhancedDynamicModal>
  );
};

export default DownloadRecord;
