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

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 AntechamberFile from "@/components/AntechamberFile";
import AntechamberReport from "@/components/AntechamberReport";
import AntechamberWishList from "@/components/AntechamberWishList";
import { ReportContext } from "@/components/Provider/ReportResolveProvider";
// import ReceiveTime from "/icons/receive-time.png";
import { ReceiveDialog } from "@/components/ReceiveDialog";

export default function Antechamber() {
  const { handleConnect } = useContext(RealtimeClientContext);
  const { hasHandledReport } = useContext(ReportContext);

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

  const token = searchParams.get("token") || "";

  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);
      }
    }
  };

  useEffect(() => {
    getUserToken();
  }, [token]);

  const toRoom = (params: { initMessage?: string; fileUrl?: string }) => {
    if (!hasHandledReport && (disable || isLoading)) {
      return;
    }
    setIsLoading(true);
    handleConnect(params).then(() => {
      setIsLoading(false);
    });
  };

  const [isReceiveDialogOpen, setIsReceiveDialogOpen] = useState(false);

  return (
    <div className="flex flex-col items-center h-full overflow-y-auto relative">
      <AntechamberHeader />
      <AntechamberWishList handleLoading={setIsLoading} />
      <AntechamberFile handleLoading={setIsLoading} />
      <AntechamberReport handleLoading={setIsLoading} />
      <InvokeButton disable={disable} onClick={() => toRoom({})} />
      {/* <img
        src={ReceiveTime}
        alt="receive-item"
        className="w-[100px] h-[100px] absolute right-[12px] bottom-[80px]"
        onClick={() => setIsReceiveDialogOpen(true)}
      /> */}
      {isLoading ? (
        <div className="absolute w-full h-full bg-red">
          <div className="w-[108px] h-[108px] absolute top-[50%] left-[50%] translate-x-[-50%] translate-y-[-50%] bg-black/60 rounded-[20px] flex flex-col items-center justify-center">
            <img
              src="/icons/loading.gif"
              alt="loading"
              className="w-[68px] h-[68px]"
            />
            <span className="text-[14px] text-[#fff]">加载中</span>
          </div>
        </div>
      ) : (
        <></>
      )}
      <ReceiveDialog
        isOpen={isReceiveDialogOpen}
        onOpenChange={setIsReceiveDialogOpen}
      />
    </div>
  );
}
