import { View, Image, Text } from "@tarojs/components";
import style from "./index.module.less";
import IconCopy from "@/components/icon/IconCopy";
import IconDislike from "@/components/icon/IconDislike";
import IconDislikeBlue from "@/components/icon/IconDislikeBlue";
import IconLike from "@/components/icon/IconLike";
import IconLikeBlue from "@/components/icon/IconLikeBlue";
import IconSpeaker from "@/components/icon/icon-speaker";
import { TAgentDetail } from "@/types/agent";

import Taro from "@tarojs/taro";
import ThinkAnimation from "../think-animation/index";
import { dislikeMessage, likeMessage } from "@/service/bot";
import { EContentType, TMessage } from "@/types/bot";
import { getLoginId, isSuccess } from "@/utils";
import { useState } from "react";
import { AvatarMedia } from "../AvatarMedia";
interface Props {
  agent?: TAgentDetail | null;
  text: string;
  textReasoning: string;
  message: TMessage;
  showUser?: boolean
}
export default ({ agent, text, message, showUser=false, textReasoning = "" }: Props) => {
  const [isDislike, setIsDislike] = useState(message.isDislike);
  const [isLike, setIsLike] = useState(message.isLike);
  // console.log('helloworld: ', message)
  const handleCopy = (e: any, textStr: string) => {
    e.stopPropagation();
    // 手动复制并 toast 提示
    if (textStr) {
      Taro.setClipboardData({
        data: textStr,
        success() {
          Taro.showToast({
            title: "复制成功",
            icon: "none",
          });
        },
        fail(res) {
          console.log(res);
          Taro.showToast({
            title: "复制失败",
            icon: "none",
          });
        },
      });
    }
  };
  const loginId = getLoginId();
  const handleDislike = async () => {
    if (!agent?.agentId) {
      return;
    }
    const isDislike = !message.isDislike;
    const response = await dislikeMessage({
      agentId: agent?.agentId,
      dislikeReason: "",
      isDislike: isDislike,
      loginId,
      msgUk: message.msgUk,
    });
    if (isSuccess(response.status)) {
      Taro.showToast({
        title: isDislike ? "已差评" : "已取消差评",
        icon: "none",
      });
      message.isDislike = isDislike; // 更新本地状态
      setIsDislike(isDislike);
      if (isDislike && isLike) {
        message.isLike = false; // 取消 like
        setIsLike(false); // 取消 like
      }
    }
  };
  const handleLike = async () => {
    if (!agent?.agentId) {
      return;
    }
    const isLike = !message.isLike;
    const response = await likeMessage({
      agentId: agent?.agentId,
      isLike: isLike,
      loginId,
      msgUk: message.msgUk,
    });

    if (isSuccess(response.status)) {
      Taro.showToast({
        title: isLike ? "已喜欢" : "已取消喜欢",
        icon: "none",
      });
      message.isLike = isLike; // 更新本地状态
      // 触发 mutate 更新列表
      setIsLike(isLike);
      if (isDislike && isLike) {
        message.isDislike = false; // 取消 dislike
        setIsDislike(false); // 取消 dislike
      }
    }
  };

  // 渲染消息主体
  const renderMessageBody = () => {
    const body = message.body;
    // console.log(body?.contentType, body)
    // 渲染 QA 回答
    if (body?.contentType === EContentType.AiseekQA) {
      const payload = body?.content?.answer?.payload ?? {};
      const links = payload.links ?? [];
      const pics = payload.pics ?? [];
      // console.log(body)
      return (
        <View>
          <View className="pb-12">
            {pics.map((pic: string) => {
              return (
                <View>
                  <Image src={pic} mode="widthFix" className="w-full"></Image>
                </View>
              );
            })}
          </View>
          <View className="pb-12">
            {links.map((link: string) => {
              return (
                <View onClick={(e) => handleCopy(e, link)}>
                  <Text className="text-primary">复制链接</Text> <Text user-select>{link}</Text>
                </View>
              );
            })}
          </View>
        </View>
      );
    }
    return <></>;
  };

  return (
    <View>
      {showUser && (
        <View className="flex gap-8 mb-10">
          <View className={style.avatarContainer}>
            <AvatarMedia source={agent?.avatarLogo || ''} className={style.avatar} mode="aspectFill"></AvatarMedia>
          </View>
          <View className="font-medium text-16 leading-24 truncate">{agent?.name}</View>
        </View>
      )}

      <View className={`${style.message} ${style.messageRobot} gap-10`}>
        <View className={`${style.messageContent}`}>
          {/* {textReasoning && <View className={style.deepThinkContainer}>
            <View className="font-bold">深度思考：</View>
            <Text>
              {textReasoning}
            </Text>
          </View>} */}

          {text.length === 0 && <ThinkAnimation></ThinkAnimation>}
          <Text user-select>{text}</Text>
          {renderMessageBody()}
        </View>
        <View className="flex gap-12">
          <View onClick={(e) => handleCopy(e, text)}>
            <IconCopy />
          </View>
          {/* <IconSpeaker></IconSpeaker> */}
          <View onClick={() => handleDislike()}>
            {isDislike ? <IconDislikeBlue /> : <IconDislike />}
          </View>
          <View onClick={() => handleLike()}>
            {isLike ? <IconLikeBlue /> : <IconLike />}
          </View>
        </View>
      </View>
    </View>
  );
};
