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/IconSpeaker";
import RenderMedia from "@/components/RenderContent/RenderMedia";
import RenderLinks from "@/components/RenderContent/RenderLinks";
import MarkdownParser from './MarkdownParser'
import { TAgentDetail } from "@/types/agent";

import Taro from "@tarojs/taro";
import ThinkAnimation from "../think-animation/index";
import { dislikeMessage, likeMessage } from "@/service/chat";
import { EContentType, TMessage } from "@/types/bot";
import { getLoginId, isSuccess } from "@/utils";
import { useState } from "react";
import { AvatarMedia } from "../AvatarMedia";
import { useTextChat } from "@/store/textChatStore";
import { useTextToSpeech } from './textToSpeech'
import { handleCopy } from '@/utils/messageUtils'
interface Props {
  agent?: TAgentDetail | null;
  text: string;
  textReasoning: string;
  message: TMessage;
  showUser?: boolean
  mutate: (func:any, params:any)=>void
}
export default ({ agent, text, message, mutate, showUser=false}: Props) => {
  const [isDislike, setIsDislike] = useState(message.isDislike);
  const [isLike, setIsLike] = useState(message.isLike);
  const [isSpeaking, setIsSpeaking] = useState(false);
  const loginId = getLoginId();
  const { setMessageRespeaking, setMessageStopHandle, messageStopHandle, isReacting, updateMessageReaction } = useTextChat()
  const { startSpeech, stopSpeech, onPlayerStatusChanged } = useTextToSpeech()

  // 更新单个消息的函数
  const updateMessage = (messageId: number, updatedFields: {isLike: boolean, isDislike: boolean}) => {
    // 使用 mutate 更新 SWR 缓存
    // 历史消息
    mutate((pages:any) => {
      return pages.map(page => {
        const updatedMessages = page.data.map((msg:TMessage) => 
          msg.msgId === messageId ? { ...msg, ...updatedFields } : msg
        );
        return { ...page, data: updatedMessages };
      });
    }, false); // 不重新验证，因为我们手动更新了
    // 更新在 store 中新的 messages 数据
    updateMessageReaction(messageId, updatedFields)
  };


  onPlayerStatusChanged((status)=> {
    const isSpeaking = status === 'playing';
    setMessageRespeaking(isSpeaking)
    setIsSpeaking(isSpeaking)
  })
  
  const handlePlayAudio = async (e:any, text: string) => {
    e.stopPropagation();
    if(isReacting){
      return;
    }

    if(messageStopHandle){
      messageStopHandle()
    }
    if(isSpeaking){
      stopSpeech()
      setIsSpeaking(false)
      return;
    }
    if(!agent?.agentId){
      return;
    }

    startSpeech({
      agentId: agent.agentId,
      msgUk: message.msgUk,
      text: text,
      loginId: loginId,
    })

    setMessageStopHandle(stopSpeech)
    
    setIsSpeaking(true)
    setMessageRespeaking(true)
  }
  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",
      });
      if(message.msgId){
        updateMessage(message.msgId, {isLike: isLike ?? false, isDislike})
      }
      setIsDislike(isDislike);
      if (isDislike && isLike) {
        message.isLike = false; // 取消 like
        if(message.msgId){
          updateMessage(message.msgId, {isLike: false, isDislike})
        }
        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",
      });
      if(message.msgId){
        updateMessage(message.msgId, {isLike, isDislike: isDislike ?? false})
      }
      // message.isLike = isLike; // 更新本地状态
      // 触发 mutate 更新列表
      setIsLike(isLike);
      if (isDislike && isLike) {
        if(message.msgId){
          updateMessage(message.msgId, {isLike, isDislike: false})
        }
        message.isDislike = false; // 取消 dislike
        setIsDislike(false); // 取消 dislike
      }
    }
  };

  // 渲染消息主体
  const renderMessageBody = () => {
    const body = message.body;
    // console.log('render:', 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 (
        <>
          {!!pics.length && <View className="pb-10">
            <RenderMedia urls={pics}></RenderMedia>
          </View>}
          {!!links.length && <View className="pb-10">
            <RenderLinks urls={links}></RenderLinks>
          </View>}
        </>
      );
    }
    return <></>;
  };

  return (
    <View className="max-w-[280px]">
      {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}`}>

          {
            text.length === 0 ? <ThinkAnimation></ThinkAnimation> : <>
              {/* <Text user-select>{text}</Text> */}
              {/* <MarkdownParser content='您可能想询问的是：**“汽车的核心理念”** 是什么。'></MarkdownParser> */}
              <MarkdownParser content={text}></MarkdownParser>
              {renderMessageBody()}
            </>
          }
          
        </View>
        <View className="flex gap-12">
          <View onClick={(e) => handleCopy(e, text)}>
            <IconCopy />
          </View>
          <View className={isReacting ? 'opacity-60' : ''} onClick={(e) => handlePlayAudio(e, text)}>
            <IconSpeaker color={isSpeaking} />
          </View>
          {/* <IconSpeaker></IconSpeaker> */}
          <View onClick={() => handleDislike()}>
            {isDislike ? <IconDislikeBlue /> : <IconDislike />}
          </View>
          <View onClick={() => handleLike()}>
            {isLike ? <IconLikeBlue /> : <IconLike />}
          </View>
        </View>
      </View>
    </View>
  );
};
