import React, { useEffect, useRef } from 'react';
import { Avatar, Typography, Space, Tag } from 'antd';
import { UserOutlined, RobotOutlined, LoadingOutlined } from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import './MessageList.css';

const { Text } = Typography;

interface Message {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  model?: string;
  tokens?: number;
  createdAt: string;
  isStreaming?: boolean;
}

interface MessageListProps {
  messages: Message[];
  loading?: boolean;
  streamingContent?: string;
}

const MessageList: React.FC<MessageListProps> = ({ 
  messages, 
  loading = false,
  streamingContent = ''
}) => {
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages, streamingContent]);

  // 处理引用标记的点击事件（事件委托）
  useEffect(() => {
    const handleCitationClick = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      // 检查target是否有classList属性（防止非Element节点）
      if (target.classList && target.classList.contains('citation-badge')) {
        const citationNum = target.getAttribute('data-citation-num');
        if (citationNum) {
          const targetElement = document.getElementById(`citation-detail-${citationNum}`);
          if (targetElement) {
            targetElement.scrollIntoView({
              behavior: 'smooth',
              block: 'center',
            });
            // 高亮闪烁效果
            targetElement.style.backgroundColor = '#fffbe6';
            setTimeout(() => {
              targetElement.style.backgroundColor = '';
            }, 2000);
          }
        }
      }
    };

    // 添加鼠标悬停效果
    const handleCitationMouseEnter = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      // 检查target是否有classList属性（防止非Element节点）
      if (target.classList && target.classList.contains('citation-badge')) {
        target.style.backgroundColor = '#bae7ff';
        target.style.borderColor = '#40a9ff';
      }
    };

    const handleCitationMouseLeave = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      // 检查target是否有classList属性（防止非Element节点）
      if (target.classList && target.classList.contains('citation-badge')) {
        target.style.backgroundColor = '#e6f7ff';
        target.style.borderColor = '#91d5ff';
      }
    };

    document.addEventListener('click', handleCitationClick);
    document.addEventListener('mouseenter', handleCitationMouseEnter, true);
    document.addEventListener('mouseleave', handleCitationMouseLeave, true);

    return () => {
      document.removeEventListener('click', handleCitationClick);
      document.removeEventListener('mouseenter', handleCitationMouseEnter, true);
      document.removeEventListener('mouseleave', handleCitationMouseLeave, true);
    };
  }, []);

  // 将文本中的引用标记转换为HTML
  const convertCitationsToHTML = (text: string): string => {
    // 匹配 [来源数字] 模式
    const citationRegex = /\[来源(\d+)\]/g;
    
    return text.replace(citationRegex, (match, num) => {
      // 生成唯一的ID用于跳转
      const citationId = `citation-ref-${num}-${Math.random().toString(36).substr(2, 9)}`;
      
      // 返回HTML字符串（单行，避免换行导致的解析问题）
      return `<span class="citation-badge" id="${citationId}" data-citation-num="${num}" style="color:#1890ff;font-weight:600;background-color:#e6f7ff;padding:2px 6px;border-radius:4px;margin:0 2px;font-size:0.9em;border:1px solid #91d5ff;cursor:pointer;transition:all 0.2s;display:inline-block;" title="点击跳转到 [来源${num}] 的详情">${match}</span>`;
    });
  };

  // Markdown代码块渲染
  const MarkdownComponents = {
    code({ node, inline, className, children, ...props }: any) {
      const match = /language-(\w+)/.exec(className || '');
      return !inline && match ? (
        <SyntaxHighlighter
          style={oneLight}
          language={match[1]}
          PreTag="div"
          customStyle={{
            backgroundColor: '#fafafa',
            border: '1px solid #e8e8e8',
            borderRadius: '6px',
            fontSize: '13px',
            margin: '12px 0',
          }}
          {...props}
        >
          {String(children).replace(/\n$/, '')}
        </SyntaxHighlighter>
      ) : (
        <code className={className} {...props}>
          {children}
        </code>
      );
    },
  };

  const renderMessage = (message: Message) => {
    const isUser = message.role === 'user';
    
    return (
      <div
        key={message.id}
        className={`message-item ${isUser ? 'message-user' : 'message-assistant'}`}
      >
        <div className="message-avatar">
          <Avatar
            size={40}
            icon={isUser ? <UserOutlined /> : <RobotOutlined />}
            style={{
              backgroundColor: isUser ? '#1890ff' : '#52c41a',
            }}
          />
        </div>
        
        <div className="message-content">
          <div className="message-header">
            <Text strong>{isUser ? '我' : 'AI助手'}</Text>
            {message.model && (
              <Tag color="blue" style={{ marginLeft: 8 }}>
                {message.model}
              </Tag>
            )}
            <Text type="secondary" style={{ marginLeft: 8, fontSize: 12 }}>
              {new Date(message.createdAt).toLocaleTimeString('zh-CN')}
            </Text>
          </div>
          
          <div className="message-body">
            {isUser ? (
              <div className="user-message-text">{message.content}</div>
            ) : (
              <div className="assistant-message-text">
                <ReactMarkdown
                  remarkPlugins={[remarkGfm]}
                  rehypePlugins={[rehypeRaw]}
                  components={MarkdownComponents}
                >
                  {convertCitationsToHTML(message.content)}
                </ReactMarkdown>
              </div>
            )}
          </div>
          
          {message.tokens && (
            <div className="message-footer">
              <Text type="secondary" style={{ fontSize: 12 }}>
                消耗Token: {message.tokens}
              </Text>
            </div>
          )}
        </div>
      </div>
    );
  };

  return (
    <div className="message-list">
      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        {messages.map(renderMessage)}
        
        {/* 流式输出中的消息 */}
        {loading && streamingContent && (
          <div className="message-item message-assistant">
            <div className="message-avatar">
              <Avatar
                size={40}
                icon={<RobotOutlined />}
                style={{ backgroundColor: '#52c41a' }}
              />
            </div>
            
            <div className="message-content">
              <div className="message-header">
                <Text strong>AI助手</Text>
                <Tag color="processing" style={{ marginLeft: 8 }}>
                  <LoadingOutlined /> 生成中...
                </Tag>
              </div>
              
              <div className="message-body">
                <div className="assistant-message-text streaming">
                  <ReactMarkdown
                    remarkPlugins={[remarkGfm]}
                    rehypePlugins={[rehypeRaw]}
                    components={MarkdownComponents}
                  >
                    {convertCitationsToHTML(streamingContent)}
                  </ReactMarkdown>
                  <span className="cursor-blink">▊</span>
                </div>
              </div>
            </div>
          </div>
        )}
        
        {/* 仅显示loading，无流式内容 */}
        {loading && !streamingContent && (
          <div className="message-item message-assistant">
            <div className="message-avatar">
              <Avatar
                size={40}
                icon={<LoadingOutlined spin />}
                style={{ backgroundColor: '#52c41a' }}
              />
            </div>
            <div className="message-content">
              <Text type="secondary">AI正在思考中...</Text>
            </div>
          </div>
        )}
      </Space>
      
      {/* 自动滚动锚点 */}
      <div ref={messagesEndRef} />
    </div>
  );
};

export default MessageList;

