import { ExtendedMessage, isCoinInsufficientAtom } from "@/atoms/im";
import { parseTextWithBrackets } from "@/utils/textParser";
import ChatBubble from "./ChatBubble";
import { useChatConfig } from "../../context/chatConfig";
import Image from "next/image";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { useNimMsgContext } from "@/context/NimChat/useNimChat";
import { ChatPriceType, useUpdateWalletBalance } from "@/hooks/useWallet";
import { useSetAtom } from "jotai";

const ChatUserTextContainer = ({
  message,
}: {
  message: ExtendedMessage;
}) => {
  // 解析文本中的括号内容
  const textParts = parseTextWithBrackets(message.text || '');
  const { aiInfo } = useChatConfig();  
  const { sendMessageActive } = useNimMsgContext();
  const { chatBubble } = aiInfo || {};
  const { checkSufficientByType } = useUpdateWalletBalance();
  const setIsCoinInsufficient = useSetAtom(isCoinInsufficientAtom);

  const handleResendMessage = () => {
    if (!checkSufficientByType(ChatPriceType.TEXT)) {
      setIsCoinInsufficient(true);
      return;
    }
    sendMessageActive({
      msg: message,
      conversationId: message.conversationId,
    });
  }

  return (
    <div className="flex justify-end items-center pb-8">
      <div className="text-xs mt-1 text-right mr-2">
        {/* {message.sendingState === 1 && (
          <span className="text-green-400">✓ 已发送</span>
        )} */}
        {/* {message.sendingState === 2 && (
          <span className="text-red-400">❌ 发送失败</span>
        )} */}
        {message.sendingState === 2 && (
          <Image src="/icons/status-error.svg" alt="Sending-failed" width={16} height={16} className="cursor-pointer" onClick={handleResendMessage} />
          // <Tooltip>
          //   <TooltipTrigger asChild>
          //     <Image src="/icons/status-error.svg" alt="Sending-failed" width={16} height={16} className="cursor-pointer" onClick={handleResendMessage} />
          //   </TooltipTrigger>
          //   <TooltipContent>
          //     <p>Error</p>
          //   </TooltipContent>
          // </Tooltip>
        )}
      </div>
      <ChatBubble isDefault={chatBubble?.isDefault} img={chatBubble?.webImgUrl}>
        <div className={cn("txt-body-l", (message.text || '').length > 3 ? "text-left" : "text-center")}>
          {textParts.map((part, index) => (
            <span
              key={index}
              className={part.isInBrackets ? 'text-txt-primary-specialmap-press' : ''}
              style={{
                wordBreak: "break-word"
              }}
            >
              {part.text}
            </span>
          ))}
        </div>
      </ChatBubble>
    </div>
  );
}
 
export default ChatUserTextContainer;