"use client";
import React, { createContext, useState, useContext, ReactNode,useEffect } from "react";
import { GetChatLastUsedForLocalStorage } from "@/utils/chat";

const GlobalContext = createContext<any>(null);

interface GlobalProviderProps {
  children: ReactNode;
}

export const GlobalProvider: React.FC<GlobalProviderProps> = ({ children }) => {
  const [menuIndex, setMenuIndex] = useState<number>(0);
  const [loginShow, setLoginShow] = useState<boolean>(false);

  const [listType, setListType] = useState<number>(0); //0会话历史 1助手列表
  const [agentId, setAgentId] = useState<number>(0); //助手ID
  const [conversationId, setConversationId] = useState<string>(""); //会话ID

  const changeMenuIndex = (index: number) => {
    setMenuIndex(index);
  };
  const changeLoginShow = (show: boolean) => {
    setLoginShow(show);
  };
  const changeListType = (listType: number) => {
    setListType(listType);
  };
  const changeAgentId = (agentId: number) => {
    setAgentId(agentId);
  };
  const changeConversationId = (conversationId: string) => {
    setConversationId(conversationId);
  };

  useEffect(() => {
    var lastUsed = GetChatLastUsedForLocalStorage();
    setListType(lastUsed.listType);
    setAgentId(lastUsed.agentId);
    setConversationId(lastUsed.conversationId);
  }, []);

  return (
    <GlobalContext.Provider
      value={{
        menuIndex,
        changeMenuIndex,
        loginShow,
        changeLoginShow,
        listType,
        changeListType,
        agentId,
        changeAgentId,
        conversationId,
        changeConversationId,
      }}
    >
      {children}
    </GlobalContext.Provider>
  );
};

export const useGlobalContext = () => {
  return useContext(GlobalContext);
};
