import { useState } from "react";
import { View, Text } from "@tarojs/components";
import style from "./index.module.less";
import TagCertificated from "@/components/tag-certificated";
import IconSwapBlack from "@/components/icon/icon-swap-black";
import IconChatWhite from "@/components/icon/icon-chat-white";
import IconQRCodeBlack from "@/components/icon/icon-qrcode-black";
import IconSendBlack from "@/components/icon/icon-send-black";
import IconEditBlack from "@/components/icon/icon-edit-black";
import IconMoreBlack from "@/components/icon/IconMoreBlack";

import ContactIcon from '@/components/ContactIcon'
import { useIsLogin } from "@/xiaolanbenlib/hooks/data/useAuth";
import AgentSwap from "../AgentSwap/index";
import AgentQRCode from "../AgentQRcode/index";
import SharePopup from "@/components/custom-share/SharePopup";
import Taro from "@tarojs/taro";
import PopupSheets from "@/components/popup/popup-sheets";

import { useModalStore } from "@/store/modalStore";
import { TAgentDetail } from "@/types/agent";
import { useAgentStoreActions } from "@/store/agentStore";
import LoginPopup from "@/components/LoginPopup";

interface IProps {
  agent: TAgentDetail,
  isVisitor: boolean, // 是否是访问他人智能体
}
export default ({agent, isVisitor}: IProps) => {
  const [showAgentSwap, setShowAgentSwap] = useState(false);
  const [showAgentQRcode, setShowAgentQRcode] = useState(false);
  const [showPopup, setShowPopup] = useState(false);
  const [showShare, setShowShare] = useState(false);
  const [showLogin, setShowLogin] = useState(false);
  const { deleteAgent, updateEditAgent } = useAgentStoreActions();


  const {showModal} = useModalStore((state) => state.actions);
  const isLogin = useIsLogin();
  const handleClick = ()=> {
    // 如果是未登录状态下想要去聊天， 则弹窗登录
    if(!isLogin){
      return setShowLogin(true);
    }

    // 如果是已经下线的智能体，显示提示信息
    if(agent.status === 'deleted'){
      showModal({
        content: <View className="w-200">{agent.deletedTip}</View>,
        showCancelButton: false,
        onConfirm() {
          Taro.showTabBar().catch(()=> {});
        },
        onCancel() {
          Taro.showTabBar().catch(()=> {});
        },
      })
      return
    }

    Taro.navigateTo({
      url: `/pages/chat/index?agentId=${agent.agentId}&isVisitor=${isVisitor}`,
    });
  }

  const handleEdit = ()=> {
    updateEditAgent(agent)
    Taro.navigateTo({ url: `/pages/agent/index?agentId=${agent?.agentId}` });
  }

  const confirmDelete = async () => {
    if(agent?.agentId){
      await deleteAgent(agent.agentId)
    }
  }

  const renderValue = (value: string | null | undefined, defaultValue: string)=> {
    return value?.length ? value :  <Text className="text-12 text-black-50">{defaultValue}</Text>
  }

  // 允许更多操作，非企业智能体且非访问者身份
  const enableMoreAction = !agent?.isEnt && !isVisitor
  // 是自己的智能体或者有二维码地址
  const enableQrcode = !isVisitor || !!agent?.qrCodeUrl?.length


  return (
    <View className="relative w-full">
      <View className={style.topBarContainer}>
        <View className={style.topBar}>
          <View className="px-8 mb-16">
            <View className="flex items-start mb-24">
              <View className="flex flex-col flex-1 gap-8">
                <View className="flex items-end gap-8">
                  <View className="text-24 font-medium leading-22 truncate max-w-180">{agent?.name}</View>
                  <View className="text-12 leading-20 text-black-60">{agent?.position ?? (isVisitor ? '' :'暂未填职业')}</View>
                </View>
                <View className="flex items-center gap-4">
                  <View className="text-12 leading-20 text-black-60 truncate max-w-[188px]">
                    {agent?.entName ?? (isVisitor ? '' :'暂未填写企业')}
                  </View>
                  {agent?.isEnt && <TagCertificated />}
                </View>
              </View>
              {!isVisitor && <View
                className={style.boxButton}
                onClick={() => {
                  setShowAgentSwap(true);
                }}
              >
                <IconSwapBlack />
              </View>}
            </View>
            <View className="flex items-center gap-8">
              {/* 和TA聊聊 */}
              <View className="flex-1">
                <View
                  className="button-rounded button-text-medium button-primary"
                  onClick={handleClick}
                >
                  <IconChatWhite />
                  和TA聊聊
                </View>
              </View>

              {/* 二维码 */}
              {enableQrcode && <View
                className={style.boxButton}
                onClick={() => {
                  setShowAgentQRcode(true);
                }}
              >
                <IconQRCodeBlack />
              </View>}

              {/* 智能体分享 */}
              <View
                className={style.boxButton}
                onClick={() => {
                  setShowShare(true);
                }}
              >
                <IconSendBlack />
              </View>

              {/* 编辑智能体 */}
              {!isVisitor && <View
                className={style.boxButton}
                onClick={handleEdit}
              >
                <IconEditBlack />
              </View>}

              {/* 更多操作 */}
              {enableMoreAction && <View className={style.boxButton} onClick={()=> {
                setShowPopup(true)
              }}>
                <IconMoreBlack />
              </View>}
            </View>
          </View>

          {/* 联系方式 */}
          <View className="rounded-12 bg-white p-20">
            <View className="flex flex-col gap-20 text-12 leading-20">
              <View className="flex items-center gap-12">
                <ContactIcon type="phone" actived={!!agent?.mobile}/>
                <View>{renderValue(agent?.mobile, '暂未填写手机号')}</View>
              </View>
              <View className="flex items-center gap-12">
                <ContactIcon type="mail" actived={!!agent?.email}/>
                <View>{renderValue(agent?.email, '暂未填写邮箱')}</View>
              </View>
              <View className="flex items-center gap-12">
                <ContactIcon type="location" actived={!!agent?.address}/>
                <View>{renderValue(agent?.address, '暂未填写地址')}</View>
              </View>
            </View>
          </View>

        </View>
      </View>

      {/* 切换智能体弹窗 */}
      {!isVisitor && <AgentSwap show={showAgentSwap} setShow={setShowAgentSwap}></AgentSwap>}

      {/* 二维码弹窗 */}
      <AgentQRCode isVisitor={isVisitor} agent={agent} show={showAgentQRcode} setShow={setShowAgentQRcode} />

      {/* 分享弹窗 */}
      {agent && <SharePopup
        show={showShare}
        setShow={setShowShare}
        agent={agent}
      ></SharePopup>}

      {/* 删除弹层 */}
      <PopupSheets
          setShow={setShowPopup}
          show={showPopup}
          content={[
            {item: <View className="text-12 font-normal text-gray-4">删除后所有数据将被清空，且无法恢复</View>},
            {item:'删除', type: 'warn', onClick: ()=> {
              setShowPopup(false);
              setTimeout(()=> {
                Taro.hideTabBar();
              },300)
              showModal({
                content: <>确认删除该智能体？</>,
                onConfirm() {
                  confirmDelete()
                  Taro.showTabBar().catch(()=> {});
                },
                onCancel() {
                  Taro.showTabBar().catch(()=> {});
                },
              })

            }},
          ]}
        >
        </PopupSheets>

        {/* 登录弹窗 */}
        <LoginPopup showPopup={showLogin} setShowPopup={setShowLogin}></LoginPopup>
    </View>
  );
};
