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";

export default function Index() {
  const [tabIndex, setTabIndex] = useState('1');
  const router = useRouter();
  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);
  })

  // useEffect(() => {
  //   agentId && fetchAgentDetail(agentId);
  // }, [agentId]);

  return (
    <PageCustom>
      <NavBarNormal scrollFadeIn backText="创建"></NavBarNormal>
      <View className="px-16 w-full flex flex-col gap-20">
        <View className="w-full">
          <TabBarButtons
            current={tabIndex}
            list={tabList}
            onTabIndexChange={handleTabIndexChange}
          ></TabBarButtons>
        </View>
        <View className={`${tabIndex === "1" ? "block" : "hidden"}`}>
          <AgentSetting></AgentSetting>
        </View>
        <View className={`${tabIndex === "2" ? "block" : "hidden"}`}>
          <AgentWebsite></AgentWebsite>
        </View>
      </View>
    </PageCustom>
  );
}
