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, useAgentStoreActions } from "@/store/agentStore";
import { useEffect, useState, useRef } 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'
import { useConfirms } from './hooks/useConfirms'

export default function Index() {
  restrictedPage()

  const router = useRouter();
  const agentId = router.params.agentId;

  const headerHeight = useAppStore((state) => state.headerHeight);
  const agentEdit = useAgentStore((state) => state.agentEdit);
  const { fetchAgent, saveAgent, createAgent, updateEditAgent } = useAgentStoreActions();
  const { fetchMyEntList } = useUserStore();
  const { setComponentList } = useComponentStore();
  const { confirmNavBack, confirmCreateAgent, confirmEditWebsite, confirmPersonalityAndGreeting, confirmSaveAvatar } = useConfirms();
  const { fetchAgents } = useAgentStoreActions();

  const [tabIndex, setTabIndex] = useState<'agent'|'website'>('agent');

  // 润色方法引用
  const agentSettingRef = useRef<{ polishAllTexts: () => Promise<void> }>(null);

  const handleTabIndexChange = async (index: 'agent' | 'website') => {
    // 如果要编辑微官网组件且是新建智能体，则提醒用户是否先创建智能体，只有创建智能体后才能编辑微官网
    if(index === 'website' && !agentEdit?.agentId){
      const isConfirm = await confirmCreateAgent()
      if(isConfirm){
        await createAgent()
        setTabIndex(index)
      }
      return
    }
    setTabIndex(index);
  };

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

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


  const handleSave  = async () => {
    if(!agentId && !agentEdit?.agentId){
      if(!agentEdit?.avatarUrl){
        const result  = await confirmSaveAvatar()
        if(result){
          return;
        }
      }
      if(!agentEdit?.personality || !agentEdit?.greeting){
        const result  = await confirmPersonalityAndGreeting(agentEdit?.personality, agentEdit?.greeting)
        if(result){
          if (agentSettingRef.current) {
            if(agentEdit?.name && agentEdit?.name.length >= 2){
              await agentSettingRef.current.polishAllTexts();
            }
          }
          console.log(agentEdit,2222)
        }else{
          return;
        }
      }
      const res = await createAgent()
      if(res){
        const goEditWebsite = await confirmEditWebsite()
        if(goEditWebsite){
          setTabIndex('website')
        }else{
          Taro.navigateBack()
        }
      }
      return
    }
    const res = await saveAgent()
    if(res){
      Taro.showToast({title: '保存成功',icon: 'success'})
    }
  }

  const handleNavBack = async (): Promise<boolean | void> => {

    // 创建 智能体没有名字时拦截弹窗
    if(!agentEdit?.agentId && !agentEdit?.name){
      const result = await confirmNavBack()
      return !result
    }
    return true
  }

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

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

  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 === "agent" ? "block" : "hidden"}`}>
            <AgentSetting ref={agentSettingRef} save={handleSave}></AgentSetting>
          </View>
          <View className={`${tabIndex === "website" ? "block" : "hidden"}`}>
            <View className="pt-36 pb-80">
              <AgentWebsite></AgentWebsite>
            </View>
          </View>
        </View>

      </View>
    </PageCustom>
  );
}
