import NavBarNormal from "@/components/NavBarNormal/index";
import { View } from "@tarojs/components";
import PageCustom from "@/components/page-custom/index";

import TabBarButtons from "@/components/wemeta-tabs/TabBarButtons";
import AgentSetting from "./components/AgentSetting/";
import AgentWebsite from "./components/AgentWebsite/";
import { useModalStore } from "@/store/modalStore";
import { useAgentStore, useAgentStoreActions } from "@/store/agentStore";
import { useEffect, useState } from "react";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import { useComponentStore } from "@/store/componentStore";
import { useUserStore } from "@/store/userStore";
import { useAppStore } from "@/store/appStore";
import style from './index.module.less'
import {restrictedPage} from '@/utils'

export default function Index() {
  restrictedPage()
  const { showModal } = useModalStore((state) => state.actions);
  const router = useRouter();
  const headerHeight = useAppStore((state) => state.headerHeight);
  const agentId = router.params.agentId;
  const agent = useAgentStore((state) => state.agent);
  const { clearMyAgent, fetchAgent, saveAgent } = useAgentStoreActions();
  const { fetchMyEntList } = useUserStore();
  const { setComponentList } = useComponentStore();
  const [tabIndex, setTabIndex] = useState('1');

  const handleTabIndexChange = (index: string) => {
    setTabIndex(index);
  };

  const fetchData = async (agentId: string) => {
    const result = await fetchAgent(agentId);
    if (result) {
      const components = result.components ?? []
      // 过滤掉没有 id 的组件防止有错误数据
      setComponentList(components.filter(c => !!c.data?.id), agentId);
    }
    fetchMyEntList()
  };

  const tabList = [
    {
      key: "1",
      label: "智能体",
    },
    {
      key: "2",
      label: "微官网",
    },
  ];

  const agentTemp = useAgentStore(state=> state.agentTemp);
  const { fetchAgents } = useAgentStoreActions();

  useEffect(()=> {
    fetchAgents()
  }, [])

  const handleSave  = async () =>{
    await saveAgent()
  }

  const handleNavBack = async () => {
    if(!agentTemp){
      return true
    }
    // 创建的智能体没有名字时拦截弹窗
    if(!agentTemp.name){
      const r = await new Promise((resolve)=> {
        showModal({
          content: <View className="text-black font-pingfangSCMedium font-medium text-14 leading-22">确定放弃创建智能体？</View>,
          confirmText: "我再想想",
          onConfirm() {
            Taro.showTabBar().catch(()=> {});
            resolve(true)
          },
          onCancel() {
            Taro.showTabBar().catch(()=> {});
            resolve(false)
          },
        })
      })

      return r
    }
  }

  useDidShow(()=> {
    if(agentId){
      fetchData(agentId);
    }else{
      clearMyAgent();
    }

  })

  return (
    <PageCustom>
      <NavBarNormal  onNavBack={handleNavBack}>编辑智能体</NavBarNormal>
      <View className="px-16 w-full flex flex-col gap-20">
        <View className={style.tabContainer}
        style={{
          paddingTop: headerHeight,
        }}
        >
          <View className="flex flex-center px-16 pb-12">
            <TabBarButtons
              current={tabIndex}
              list={tabList}
              onTabIndexChange={handleTabIndexChange}
            ></TabBarButtons>
          </View>
        </View>
        <View className="pt-52">
          <View className={`${tabIndex === "1" ? "block" : "hidden"}`}>
            <AgentSetting save={handleSave}></AgentSetting>
          </View>
          <View className={`${tabIndex === "2" ? "block" : "hidden"}`}>
            <View className="pt-36 pb-80">
              <AgentWebsite></AgentWebsite>
            </View>
          </View>
        </View>

      </View>
    </PageCustom>
  );
}
