import { useState } from "react";
import { View } from "@tarojs/components";
import Taro, { useRouter } from "@tarojs/taro";
import PageCustom from "@/components/page-custom/index";
import NavBarNormal from "@/components/NavBarNormal/index";
import ButtonCardAdd from "@/components/button-card-add";
import ContactCard from "@/components/AgentCard/index";
import style from './index.module.less'
import Popup from "@/components/popup/popup";
import WemetaTabs from "@/components/wemeta-tabs/index";
import BottomBar from "@/components/BottomBar";
import { TContactItem } from "@/types/contact";
import AgentScrollList from './components/MyContactsScrollList'
import MyAgentsScrollList from './components/MyAgentsScrollList'
import MyEntAgentsScrollList from './components/MyEntAgentsScrollList'
import { TAgent } from "@/types/agent";

import IconMoreBlack from "@/components/icon/IconMoreBlack";
import PopupSheets from "@/components/popup/popup-sheets";
import { EComponentType } from "@/consts/enum";
import { useComponentStore } from "@/store/componentStore";
import { useAgentStore } from "@/store/agentStore";

export default function Index() {
  const { saveComponent } = useComponentStore();
  let currentComponent = useComponentStore((state) => state.currentComponent);
  const loading = useComponentStore((state) => state.loading);
  const prevData = currentComponent?.data.values ?? []
  const [picked, setPicked] = useState<(TContactItem|TAgent)[]>(prevData);
  const [agents, setAgents] = useState<(TContactItem|TAgent)[]>(prevData);
  const [current, setCurrent] = useState<(TContactItem|TAgent)|null>(null);
  const agent = useAgentStore((state)=>  state.agent)

  // 是否显示选择器
  const [show, setShow] = useState(false);

  const [showPopupSheets, setShowPopupSheets] = useState(false);




  const handleSubmit = async () => {
    if(!currentComponent?.data?.id){
      return
    }
    if (loading) {
      return;
    }
    // 过虑掉 email, mobile, qrCodeUrl
    const newPicked = picked.map(item=> {
      return {
        ...item,
        email: undefined,
        mobile: undefined,
        qrCodeUrl: undefined,
      }
    })
    const c = {
      data: {
        values: newPicked,
        layout: currentComponent.data.layout ?? 'mini',
        id: currentComponent.data.id,
        index: currentComponent.data.index,
      },
      enabled: currentComponent?.enabled ?? true,
      type: EComponentType.bluebook,
    };

    await saveComponent(c);
    Taro.navigateBack();
  };

  const handleClickMore = (item: TAgent|TContactItem) => {
    setCurrent(item)
    setShowPopupSheets(true)
  };

  const handleClick = () => {
    setShow(true)
  }
  const handlePicked = () => {
    setShow(false)
    setPicked(agents)
  }

  const visitorCurrent = ()=> {
    if(!current){
      return;
    }

    setShowPopupSheets(false)
    Taro.navigateTo({
      url: "/pages/profile/index?agentId=" + current?.agentId,
    });
    setCurrent(null)
  }

  const removePicked = ()=> {
    if(!current){
      return;
    }

    setShowPopupSheets(false)
    const restAgent = picked.filter(item => item.agentId !== current.agentId);
    setPicked(restAgent)
    setAgents(restAgent)
    setCurrent(null)
  }




  const renderContactList = () => {
    if (!picked.length) {
      return (
        <></>
      );
    }
    return (
      <View className="flex flex-col gap-8 w-full">
        {picked.map((item) => {
          return (
            <ContactCard
              className="p-16"
              key={item.agentId}
              data={item}
              renderRight={() => {
                return (
                  <View className="flex self-center" onClick={() => handleClickMore(item)}>
                    <IconMoreBlack />
                  </View>
                );
              }}
            ></ContactCard>
          );
        })}
      </View>
    );
  };


  const colleagues = {
    key: "3",
    label: "企业同事",
    children: (
      <View className={style.tabContainer}>
        <MyEntAgentsScrollList selected={agents} setSelected={setAgents}></MyEntAgentsScrollList>
      </View>
    ),
  }

  const tabsBaseList = [
    {
      key: "1",
      label: "我创建的",
      children: (
        <View className={style.tabContainer}>
          <MyAgentsScrollList selected={agents} setSelected={setAgents}></MyAgentsScrollList>
        </View>
      ),
    },
    {
      key: "2",
      label: "我的联系⼈",
      children: (
        <View className={style.tabContainer}>
          <AgentScrollList selected={agents} setSelected={setAgents}></AgentScrollList>
        </View>
      ),
    },
  ]

  const tabList = agent?.isEnt ? [...tabsBaseList, colleagues] : tabsBaseList;





  return (
    <PageCustom>
      <NavBarNormal>智能体</NavBarNormal>
      <View>
      </View>
      <View className="w-full">
        <View className='flex flex-col items-center w-full'>
          <ButtonCardAdd
            text={`添加展示的智能体`}
            onClick={handleClick}
          ></ButtonCardAdd>

          <View className="pt-16 pb-162 px-16 w-full">
            {renderContactList()}
          </View>
        </View>
      </View>
      <BottomBar>
        <View className="button-rounded button-primary flex-1" onClick={handleSubmit}>保存</View>
      </BottomBar>
      <Popup setShow={setShow} show={show} title="智能体">
        <WemetaTabs current="1" list={tabList}></WemetaTabs>
        <BottomBar>
          <View
            className="button-rounded button-primary flex-1"
            onClick={handlePicked}
          >
            引用
          </View>
        </BottomBar>
      </Popup>

      <PopupSheets
          setShow={setShowPopupSheets}
          show={showPopupSheets}
          content={[
            {item: '访问TA的主页', type: 'primary', onClick: visitorCurrent},
            {item:'删除', type: 'warn', onClick: removePicked},
          ]}
        >
      </PopupSheets>
    </PageCustom>
  );
}
