import { ExtendedMessage, MessageLikeStatus, getUserLikeStatus } from "@/atoms/im";
import { useTypingEffect } from "@/hooks/useTypingEffect";
import { useEffect, useCallback, useRef } from "react";
import { useSetAtom } from "jotai";
import { msgListAtom } from "@/atoms/im";
import { parseTextWithBrackets } from "@/utils/textParser";
import { IconButton } from "@/components/ui/button";
import { useNimMsgContext, useNimChat } from "@/context/NimChat/useNimChat";
import { useState, useMemo } from "react";
import { cn } from "@/lib/utils";
import { useMessageLike } from "@/hooks/useMessageLike";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { toast } from "sonner";
import { useDoFeedback } from "@/hooks/useIm";
import { useChatConfig } from "../../context/chatConfig";
import { WaveAnimation } from "@/components/ui/wave-animation";
import ChatAudioTag from "./ChatAudioTag";

const ChatOtherTextContainer = ({
  message,
}: {
  message: ExtendedMessage;
}) => {
  const setMsgList = useSetAtom(msgListAtom);
  const { nim } = useNimChat();
  const { aiId } = useChatConfig();
  const { mutateAsync: doFeedback, isPending: isFeedbackPending } = useDoFeedback();
  const { addMsg, audioPlayer } = useNimMsgContext();
  const { createTime } = message;

  const is7DaysMessage = createTime && Date.now() - createTime < 7 * 24 * 60 * 60 * 1000;
  
  // 防抖相关状态
  const [optimisticOptType, setOptimisticOptType] = useState<number | null>(null);
  const debounceTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  
  // 获取当前登录用户ID
  const currentUserId = nim.V2NIMLoginService.getLoginUser();
  
  // 从serverExtension获取当前用户的点赞状态
  const serverExtension = JSON.parse(message.serverExtension || '{}')
  const { optType } = serverExtension;
  
  // 使用乐观更新的状态，优先显示本地状态
  const currentOptType = optimisticOptType !== null ? optimisticOptType : optType;
  const isLike = currentOptType === 1;
  const isDislike = currentOptType === 2;

  // 使用打字机效果，只对新消息启用
  const { displayedText, isTyping } = useTypingEffect({
    text: message.text || '',
    speed: 30,
    enabled: message.isNewMessage || false
  });

  // 解析文本中的括号内容
  const textParts = parseTextWithBrackets(displayedText);
  
  // 防抖请求函数
  const debouncedFeedback = useCallback(async (newOptType: number) => {
    try {
      // 更新本地消息状态
      addMsg(message.conversationId, [{
        ...message,
        serverExtension: JSON.stringify({
          ...serverExtension,
          optType: newOptType
        })
      }], false);
      
      // 发送反馈请求
      await doFeedback({
        aiId,
        messageId: message.messageServerId,
        content: message.text || '',
        optType: newOptType as 0 | 1 | 2
      });
      
      if (message.messageServerId.includes("prologue")) {
        return;
      }
      // 请求成功，清除乐观状态
      setOptimisticOptType(null);
    } catch (error) {
      // 请求失败，恢复原状态
      setOptimisticOptType(null);
      toast.error("Operation failed, please try again");
    }
  }, [aiId, message, serverExtension, addMsg, doFeedback]);

  // 处理点赞
  const handleLike = useCallback(() => {
    const newOptType = isLike ? 0 : 1;
    
    // 立即更新乐观状态
    setOptimisticOptType(newOptType);
    
    // 清除之前的防抖定时器
    if (debounceTimeoutRef.current) {
      clearTimeout(debounceTimeoutRef.current);
    }
    
    // 设置新的防抖定时器
    debounceTimeoutRef.current = setTimeout(() => {
      debouncedFeedback(newOptType);
    }, 2000); // 300ms防抖延迟
  }, [isLike, debouncedFeedback]);
  
  // 处理踩
  const handleDislike = useCallback(() => {
    const newOptType = isDislike ? 0 : 2;
    
    // 立即更新乐观状态
    setOptimisticOptType(newOptType);
    
    // 清除之前的防抖定时器
    if (debounceTimeoutRef.current) {
      clearTimeout(debounceTimeoutRef.current);
    }
    
    // 设置新的防抖定时器
    debounceTimeoutRef.current = setTimeout(() => {
      debouncedFeedback(newOptType);
    }, 2000); // 300ms防抖延迟
  }, [isDislike, debouncedFeedback]);

  // 清理定时器
  useEffect(() => {
    return () => {
      if (debounceTimeoutRef.current) {
        clearTimeout(debounceTimeoutRef.current);
      }
    };
  }, []);

  // 当打字效果完成后，清除 isNewMessage 标识
  useEffect(() => {
    if (message.isNewMessage && !isTyping && displayedText === message.text) {
      setMsgList(prev => {
        const newMsgList = prev.clone();
        const messages = newMsgList.get(message.conversationId) || [];
        const updatedMessages = messages.map(msg => 
          msg.messageClientId === message.messageClientId
            ? { ...msg, isNewMessage: false }
            : msg
        );
        newMsgList.set(message.conversationId, updatedMessages, false);
        return newMsgList;
      });
    }
  }, [isTyping, displayedText, message.text, message.isNewMessage, message.messageClientId, message.conversationId, setMsgList]);

  const handleCopy = () => {
    navigator.clipboard.writeText(message.text || '');
    toast.success('Copied to clipboard');
  }

  return (
    <div className="group">
      <div className="flex justify-start">
        <div className="backdrop-blur-[32px] bg-surface-element-dark-hover flex items-start justify-start pt-6 pb-4 px-4 relative max-w-[496px] rounded-lg">
          {/* 消息内容 */}
          <div className={cn("txt-body-l")}>
            {textParts.map((part, index) => (
              <span
                key={index}
                className={part.isInBrackets ? 'text-txt-secondary-normal' : ''}
                style={{
                  wordBreak: "break-word"
                }}
              >
                {part.text}
              </span>
            ))}
            {isTyping && <span className="animate-pulse">|</span>}
          </div>
          <ChatAudioTag message={message} />
        </div>
      </div>
      <div className="h-8 flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity duration-300">
        <Tooltip>
          <TooltipTrigger asChild>
            <IconButton variant="tertiary" size="xs" onClick={handleCopy} tabIndex={-1}>
              <i className="iconfont icon-copy" />
            </IconButton>
          </TooltipTrigger>
          <TooltipContent side="bottom">
            <p>Copy</p>
          </TooltipContent>
        </Tooltip>
        {is7DaysMessage && <Tooltip>
          <TooltipTrigger asChild>
            <IconButton
              variant="tertiary" 
              size="xs"
              onClick={handleLike}
              className={cn(
                "transition-colors",
              )}
              tabIndex={-1}
            >
              <i className={cn(
                "iconfont",
                isLike ? "icon-post_recommend_fill" : "icon-icon_post_recommend"
              )} />
            </IconButton>
          </TooltipTrigger>
          <TooltipContent side="bottom">
            <p>Good</p>
          </TooltipContent>
        </Tooltip>}
       
        {is7DaysMessage && <Tooltip>
          <TooltipTrigger asChild>
            <IconButton 
              variant="tertiary" 
              size="xs"
              onClick={handleDislike}
              className={cn(
                "transition-colors",
              )}
              tabIndex={-1}
            >
              <i className={cn(
                "iconfont",
                isDislike ? "icon-post_Notrecommend_fill" : "icon-icon_post_Notrecommend"
              )} />
            </IconButton>
          </TooltipTrigger>
          <TooltipContent side="bottom">
            <p>Bad</p>
          </TooltipContent>
        </Tooltip>}    
        
      </div>
    </div>
  );
}
 
export default ChatOtherTextContainer;