import { fetchFile } from "@/apis/user";
import { useToast } from "@/hooks/use-toast";
import { useAbortController } from "@/hooks/useAbortController";
import { useContext, useEffect } from "react";
import { useSearchParams } from "react-router-dom";
import { ReportContext } from "../Provider/ReportResolveProvider";
import { FileInfo, RealtimeClientContext } from "../Provider/RealtimeClientProvider";

type Props = {
  handleLoading:(val:boolean) => void
}

export default function AntechamberFile({handleLoading}:Props) {
  const [searchParams] = useSearchParams();
  const fileId = searchParams.get("fileId") || "";
  const locationCode = searchParams.get("locationCode") || "";
  const token = searchParams.get("token") || "";
  const { toast } = useToast();
  const { getSignal } = useAbortController();
  const { setHasHandledReport,hasHandledReport } = useContext(ReportContext);
  const { handleConnect } = useContext(RealtimeClientContext);

  const useFileFetch = async () => {    
    handleLoading(true)
    const result = await fetchFile({
      params: { id: fileId, location: locationCode },
      options: {
        signal: getSignal(),
        headers: { Authorization: `Bearer ${token}` },
      },
    });
    
    if (result.message) {
      toast({
        title: result.message,
      });
    }
    let resp = result.result as FileInfo;
    
    handleConnect({
      fileInfo: {type: resp.type,url: resp.url,tableName: resp.tableName,provinceName: resp.provinceName,subjectClaim: resp.subjectClaim},
    }).then(() => {
      setHasHandledReport(true);
    });
  };


  useEffect(() => {
    
    if (fileId && locationCode && !hasHandledReport) {
      useFileFetch();
    }
  }, [fileId, locationCode,hasHandledReport]);


  return <></>;
}
