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 { useAgentStore } from "@/store/agentStore";
import { useEffect, useState } from "react";
import { 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'

export default function Index() {
  const [tabIndex, setTabIndex] = useState('1');
  const router = useRouter();
  const headerHeight = useAppStore((state) => state.headerHeight);
  const agentId = router.params.agentId;
  const { fetchAgent } = useAgentStore();
  const { fetchMyEntList } = useUserStore();
  const { setComponentList } = useComponentStore();
  const handleTabIndexChange = (index: string) => {
    setTabIndex(index);
  };

  const fetchAgentDetail = 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: "微官网",
    },
  ];

  useDidShow(()=> {
    agentId && fetchAgentDetail(agentId);
  })

  return (
    <PageCustom>
      <NavBarNormal>编辑智能体</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"}`}>
            <View className="pt-12">
            <AgentSetting></AgentSetting>
            </View>
          </View>
          <View className={`${tabIndex === "2" ? "block" : "hidden"}`}>
            <View className="pt-36 pb-80">
              <AgentWebsite></AgentWebsite>  
            </View>          
          </View>
        </View>
        
      </View>
    </PageCustom>
  );
}
