import { Image, View } from "@tarojs/components";
import style from "./index.module.less";
import IconPlusBig from "@/components/icon/icon-plus-big";
import Taro from "@tarojs/taro";
import { uploadAndNavToGenNewAvatar } from "@/utils/avatar";
import WemetaRadio from "@/components/WemetaRadio";
import { useAgentStore } from "@/store/agentStore";
import { editAgentChatBg } from "@/service/agent";
import { isSuccess } from "@/utils";
import { fetchMyAvatars } from "@/service/storage";
import { AvatarMedia } from "@/components/AvatarMedia";

export default () => {
  const { agent, fetchAgent } = useAgentStore();

  const handleChange = async (isChecked: boolean) => {
    if (!agent?.agentId || !agent.avatarUrl) {
      return;
    }
    const response = await editAgentChatBg(agent.agentId, isChecked);
    if (isSuccess(response.status)) {
      Taro.showToast({
        title: isChecked ? "启用成功" : "取消启用",
        icon: "success",
      });
      fetchAgent(agent.agentId); // 刷新智能体信息
    }
  };
  const handleClick = async () => {
    const response = await fetchMyAvatars({ pageIndex: 1, pageSize: 2 });
    if (isSuccess(response.status)) {
      if (response.data.data.length > 0) {
        Taro.navigateTo({ url: "/pages/agent-avatars/index" });
        return;
      }
    }
    if (agent?.avatarUrl) {
      return;
    }
    uploadAndNavToGenNewAvatar();
  };

  const handleChangeAvatar = async (e: any) => {
    e.stopPropagation();
    Taro.navigateTo({ url: "/pages/agent-avatars/index" });
  };

  const renderContent = () => {
    if (!agent?.avatarUrl) {
      return (
        <View className={style.tips}>
          <View className={style.icon}>
            <IconPlusBig></IconPlusBig>
          </View>
          <View className={style.tipsText}>形象照</View>
        </View>
      );
    }

    return (
      <View className="relative overflow-hidden w-full h-full">
        <AvatarMedia source={agent.avatarUrl} className={style.card} />
        {agent?.enabledChatBg &&  <View className={style.confirmChatAvatarBgCover}>
          <View className={style.block1}></View>
          <View className={style.block2}></View>
          <View className={style.block3}></View>
        </View>}
        <View className={style.changeButton} onClick={handleChangeAvatar}>
          更换形象
        </View>
      </View>
    );
  };

  return (
    <View className={style.container}>
      <View className={style.card} onClick={handleClick}>
        {renderContent()}
      </View>
      <View
        className="w-full flex-center pt-24 gap-6"
        onClick={() => handleChange(!!!agent?.enabledChatBg)}
      >
        {/* ={agent?.enabledChatBg} */}
        <WemetaRadio checkbox checked={agent?.enabledChatBg}></WemetaRadio>
        <View className="font-medium text-14 text-black">启用聊天背景</View>
      </View>
    </View>
  );
};
