import { useGetIMUserInfo } from '@/hooks/useIm';
import { useChatConfig } from '../context/chatConfig';
import { cn } from "@/lib/utils";
import { ExtendedMessage } from '@/atoms/im';
import ChatOtherTextContainer from './ChatMessageItems/ChatOtherTextContainer';
import { useMemo } from 'react';
import { useNimChat } from '@/context/NimChat/useNimChat';
import { useAtomValue } from 'jotai';
import { selectedConversationIdAtom, deletedConversationsAtom } from '@/atoms/im';

interface ChatPrologueMessageProps {
  className?: string;
}

const ChatPrologueMessage = ({ className }: ChatPrologueMessageProps) => {
  const { aiId } = useChatConfig();
  const { data: aiUserInfo } = useGetIMUserInfo({ aiId: aiId || 0 });
  const { nim } = useNimChat();
  const selectedConversationId = useAtomValue(selectedConversationIdAtom);
  const deletedConversations = useAtomValue(deletedConversationsAtom);

  // 创建模拟的开场白消息对象
  const mockPrologueMessage = useMemo((): ExtendedMessage | null => {
    if (!aiUserInfo?.dialoguePrologue || !nim || !selectedConversationId || aiUserInfo.isDelChatted === false) {
      return null;
    }

    try {
      // 获取 AI 用户 ID（会话目标 ID）
      const aiUserId = nim.V2NIMConversationIdUtil.parseConversationTargetId(selectedConversationId);
      const currentUser = nim.V2NIMLoginService.getLoginUser();
      
      // 创建模拟的开场白消息
      const prologueMessage = nim.V2NIMMessageCreator.createTextMessage(aiUserInfo.dialoguePrologue);
      
      // 设置消息属性
      prologueMessage.senderId = aiUserId; // 设置发送者为 AI
      prologueMessage.receiverId = currentUser || ''; // 设置接收者为当前用户
      prologueMessage.conversationId = selectedConversationId;
      prologueMessage.messageType = 0; // TEXT 消息类型
      prologueMessage.createTime = Date.now();
      prologueMessage.sendingState = 0; // 已发送状态
      prologueMessage.messageClientId = `prologue_${aiId}`;
      prologueMessage.messageServerId = `prologue_${aiId}`;
      prologueMessage.serverExtension = '{}'; // 空的服务端扩展
      
      return prologueMessage as ExtendedMessage;
    } catch (error) {
      console.error('创建开场白消息失败:', error);
      return null;
    }
  }, [aiUserInfo?.dialoguePrologue, nim, selectedConversationId, aiId, deletedConversations]);

  // 如果没有开场白内容或无法创建消息对象，不显示组件
  if (!mockPrologueMessage) {
    return null;
  }

  return (
    <div className={cn("mb-4 relative", className)}>
      {/* 使用 ChatOtherTextContainer 渲染开场白 */}
      <ChatOtherTextContainer message={mockPrologueMessage} />
    </div>
  );
};

export default ChatPrologueMessage;
