import PageCustom from "@/components/page-custom/index";
import NavBarNormal from "@/components/NavBarNormal";

import { View } from "@tarojs/components";
import Logo from "@/components/logo";
import AgentActionBar from "./components/AgentActionBar";
import { useAgentStore, useAgentStoreActions } from "@/store/agentStore";
import { useEffect, useState } from "react";
import { useComponentStore } from "@/store/componentStore";
import ComponentList from "@/components/component-list";
import { useUserStore } from "@/store/userStore";
import {  DEFAULT_AVATAR_BG } from '@/config'

import Taro, { useDidShow } from "@tarojs/taro";


interface IProps {
  agentId: string;
}
export default function Index({ agentId }: IProps) {
  const agent = useAgentStore((state)=> state.agent);
  const { fetchAgent } = useAgentStoreActions();
  const { fetchMyEntList } = useUserStore();
  const [bg, setBg] = useState('')
  const [isDefaultBg, setIsDefaultBg] = useState(false)

  const { setComponentList } = useComponentStore()
  const components = useComponentStore((state) => state.components);

  const fetchData = async ()=> {
    if (agentId) {
      const _agent = await fetchAgent(agentId)
      // 要等请求结束才能判断要不要显示默认形象图
      // 设置 背景
      setBg(_agent?.avatarUrl ?? DEFAULT_AVATAR_BG)
      setIsDefaultBg(!_agent?.avatarUrl)
    }
  }

  useDidShow(()=> {
    fetchData()
  })
  useEffect(()=> {
    fetchData()
  },[agentId])

  useEffect(()=> {
    // 过滤,1,允许显示，2、有 id 的组件防止有错误数据
    const components = (agent?.components ?? []).filter(c => !!c.data?.id && c.enabled)
    setComponentList(components, agentId);
  }, [agent])

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

  // 如果是默认形象，设置占位空间，点击后跳转至编辑页
  const renderDefaultPlaceholder = ()=> {
    if(!isDefaultBg){
      return <></>
    }
    return <View className="absolute w-full h-[400px] z-0" onClick={() => {
          Taro.navigateTo({ url: `/pages/agent/index?agentId=${agent?.agentId}` });
        }}>
    </View>
  }

  return (
    <PageCustom styleBg={bg}>
      <NavBarNormal blur scrollFadeIn scrollFadeInDelta={240} leftColumn={Logo}></NavBarNormal>
      {renderDefaultPlaceholder()}
      <View className="blur-rounded-container">
        {(!!agent) ? <AgentActionBar isVisitor={false} agent={agent}></AgentActionBar> : <></>}
        <View className={`flex flex-col gap-12 w-full p-16`}>
          <ComponentList components={components}></ComponentList>
        </View>
      </View>
    </PageCustom>
  );
}
