import AntechamberHeader from "@/components/AntechamberHeader";
import InvokeButton from "@/components/AntechamberButton";
import AntechamberScore from "@/components/AntechamberScore";

import { useContext, useEffect, useState } from "react";
import { RealtimeClientContext } from "@/components/Provider/RealtimeClientProvider";
import { useSearchParams } from "react-router-dom";
import {  fetchUserToken } from "@/apis/user";
import { useToast } from "@/hooks/use-toast";
import { useAbortController } from "@/hooks/useAbortController";
// import { ReportContext } from "@/components/Provider/ReportResolveProvider";
import AntechamberFile from "@/components/AntechamberFile";
import AntechamberReport from "@/components/AntechamberReport";
import AntechamberWishList from "@/components/AntechamberWishList";

export default function Antechamber() {

  const { handleConnect } = useContext(RealtimeClientContext);
  

  const [searchParams] = useSearchParams();
  const [disable,setDisable] = useState(true);

  const token = searchParams.get("token") || '';
  // const reportId = searchParams.get("reportId") || '';
  // const reportType = searchParams.get("reportType") || '';
  
  const { toast } = useToast();
  const { getSignal } = useAbortController();

  const getUserToken = async () => {
    try {
      const { result, message } = await fetchUserToken({ 
        options: { 
          signal: getSignal(),
          headers: {
            "Authorization": `Bearer ${encodeURIComponent(token)}`
          } 
        } 
      });
      if (message) {
        console.log(message);
      } else {
        const _result = result as {isExpired:boolean;msg:string};      
        setDisable(!_result.isExpired);
        if(!_result.isExpired &&_result.msg){          
          toast({
            title: _result.msg,
            description: "请重新登录",
          });
        }
      }
    } catch (error: any) {
      if (error.name !== 'AbortError') {
        console.error('获取用户令牌失败:', error);
      }
    }
  };

  // const getReport = async () => {
  //   try {
  //     const { result, message } = await fetchReport({ 
  //       params:{Type:reportType,Id:reportId}, 
  //       options: { 
  //         signal: getSignal(),
  //         headers: {
  //           "Authorization": `Bearer ${encodeURIComponent(token)}`
  //         } 
  //       } 
  //     });
  //     if (message) {
  //       console.log(message);
  //     } else {
  //       handleConnect({initMessage:result as string});
  //       setHasHandledReport(true)
  //     }
  //   } catch (error: any) {
  //     if (error.name !== 'AbortError') {
  //       console.error('获取报告失败:', error);
  //     }
  //   }
  // }
  
  useEffect(() => {
    getUserToken();
  }, [token]);

  // useEffect(() => {
  //   if(reportId && reportType && !hasHandledReport){
  //     getReport();
  //   }
  // }, [reportId, reportType,hasHandledReport]);

  const toRoom = (params:{initMessage?:string,fileUrl?:string}) => {
    if(disable){
      return;
    }
    handleConnect(params);
  };
  return (
    <div className="flex flex-col items-center h-full">
      <AntechamberHeader />
      <AntechamberScore />
      <AntechamberWishList />
      <AntechamberFile  />
      <AntechamberReport />
      <InvokeButton disable={disable} onClick={() => toRoom({})} />
    </div>
  );
}
