import React, { useState, useRef, useEffect } from 'react';
import { message, Select, Button } from 'antd';
import ReactECharts from 'echarts-for-react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import useAuthStore from '../store/authStore';
import './ChatAssistant.css';

const ChatAssistant = ({ models }) => {
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [selectedModel, setSelectedModel] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const messagesEndRef = useRef(null);
  const { token } = useAuthStore();

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

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

  // 发送消息
  const handleSendMessage = async () => {
    if (!inputValue.trim()) {
      message.warning('请输入查询内容');
      return;
    }

    if (!selectedModel && models.length > 0) {
      // 自动选择默认模型或第一个模型
      const defaultModel = models.find(m => m.is_default) || models[0];
      setSelectedModel(defaultModel.id);
    }

    const userMessage = {
      role: 'user',
      content: inputValue,
      timestamp: new Date().toISOString()
    };

    setMessages(prev => [...prev, userMessage]);
    setInputValue('');
    setIsLoading(true);

    // 创建一个空的助手消息
    const assistantMessageId = Date.now();
    const assistantMessage = {
      id: assistantMessageId,
      role: 'assistant',
      content: '',
      timestamp: new Date().toISOString(),
      toolCalls: [],
      charts: [],  // 添加图表数组
      isStreaming: true
    };

    setMessages(prev => [...prev, assistantMessage]);

    try {
      const apiHost = import.meta.env.VITE_API_HOST || 'http://localhost:8000';
      const response = await fetch(
        `${apiHost}/api/chat-assistant/chat`,
        {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            message: userMessage.content,
            model_id: selectedModel
          })
        }
      );

      if (!response.ok) {
        throw new Error('请求失败');
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n\n');
        buffer = lines.pop() || '';

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const data = JSON.parse(line.substring(6));

              if (data.type === 'error') {
                message.error(data.content);
                setMessages(prev => prev.map(msg =>
                  msg.id === assistantMessageId
                    ? { ...msg, content: `错误: ${data.content}`, isStreaming: false }
                    : msg
                ));
              } else if (data.type === 'tool_call') {
                // 工具调用通知
                setMessages(prev => prev.map(msg =>
                  msg.id === assistantMessageId
                    ? {
                      ...msg,
                      toolCalls: [
                        ...msg.toolCalls,
                        {
                          tool: data.tool,
                          explanation: data.explanation,
                          sql: data.sql,
                          status: 'calling'
                        }
                      ]
                    }
                    : msg
                ));
              } else if (data.type === 'tool_result') {
                // 工具调用结果
                setMessages(prev => prev.map(msg =>
                  msg.id === assistantMessageId
                    ? {
                      ...msg,
                      toolCalls: msg.toolCalls.map((call, idx) =>
                        idx === msg.toolCalls.length - 1
                          ? {
                            ...call,
                            status: data.success ? 'success' : 'error',
                            count: data.count,
                            error: data.error
                          }
                          : call
                      )
                    }
                    : msg
                ));
              } else if (data.type === 'chart_call') {
                // 图表生成通知
                setMessages(prev => prev.map(msg =>
                  msg.id === assistantMessageId
                    ? {
                      ...msg,
                      charts: [
                        ...msg.charts,
                        {
                          chart_type: data.chart_type,
                          title: data.title,
                          explanation: data.explanation,
                          status: 'generating'
                        }
                      ]
                    }
                    : msg
                ));
              } else if (data.type === 'chart_result') {
                // 图表生成结果
                setMessages(prev => prev.map(msg =>
                  msg.id === assistantMessageId
                    ? {
                      ...msg,
                      charts: msg.charts.map((chart, idx) =>
                        idx === msg.charts.length - 1
                          ? {
                            ...chart,
                            status: data.success ? 'success' : 'error',
                            config: data.config,
                            error: data.error
                          }
                          : chart
                      )
                    }
                    : msg
                ));
              } else if (data.type === 'content') {
                // 流式内容
                setMessages(prev => prev.map(msg =>
                  msg.id === assistantMessageId
                    ? { ...msg, content: msg.content + data.content }
                    : msg
                ));
              } else if (data.type === 'done') {
                // 完成
                setMessages(prev => prev.map(msg =>
                  msg.id === assistantMessageId
                    ? { ...msg, isStreaming: false }
                    : msg
                ));
              }
            } catch (e) {
              console.error('解析数据失败:', e);
            }
          }
        }
      }
    } catch (e) {
      console.error('发送失败:', e);
      message.error(e.message || '发送失败');
      setMessages(prev => prev.map(msg =>
        msg.id === assistantMessageId
          ? { ...msg, content: '发送失败，请重试', isStreaming: false }
          : msg
      ));
    } finally {
      setIsLoading(false);
    }
  };

  // 清空对话
  const handleClearChat = () => {
    setMessages([]);
  };

  return (
    <div className="chat-assistant-container">
      <div className="chat-assistant-header">
        <div>
          <h2 className="chat-assistant-title">智能对话助手</h2>
          <p className="chat-assistant-subtitle">通过自然语言查询聊天消息数据</p>
        </div>
        <div className="chat-assistant-controls">
          <Select
            placeholder="选择AI模型"
            value={selectedModel}
            onChange={setSelectedModel}
            style={{ width: 200, marginRight: '12px' }}
          >
            {models.map(m => (
              <Select.Option key={m.id} value={m.id}>
                {m.name}
                {m.is_default && <span style={{ marginLeft: '8px', color: '#f59e0b' }}>⭐</span>}
              </Select.Option>
            ))}
          </Select>
          <Button onClick={handleClearChat} disabled={messages.length === 0}>
            清空对话
          </Button>
        </div>
      </div>

      <div className="chat-assistant-messages">
        {messages.length === 0 ? (
          <div className="chat-assistant-empty">
            <svg width="64" height="64" viewBox="0 0 24 24" fill="none">
              <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="#d1d5db" strokeWidth="2"/>
            </svg>
            <h3>开始对话</h3>
            <p>您可以询问关于聊天消息的任何问题，例如：</p>
            <ul>
              <li>"查询今天发送的所有消息"</li>
              <li>"统计每个用户的消息数量"</li>
              <li>"查找包含'天气'关键词的消息"</li>
              <li>"显示最近的10条敏感消息"</li>
            </ul>
          </div>
        ) : (
          messages.map((msg, idx) => (
            <div key={idx} className={`chat-message ${msg.role}`}>
              <div className="chat-message-avatar">
                {msg.role === 'user' ? (
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                    <path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2" stroke="currentColor" strokeWidth="2"/>
                    <circle cx="12" cy="7" r="4" stroke="currentColor" strokeWidth="2"/>
                  </svg>
                ) : (
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                    <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="currentColor" strokeWidth="2"/>
                  </svg>
                )}
              </div>
              <div className="chat-message-content">
                <div className="chat-message-header">
                  <span className="chat-message-role">
                    {msg.role === 'user' ? '您' : 'AI 助手'}
                  </span>
                  <span className="chat-message-time">
                    {new Date(msg.timestamp).toLocaleTimeString('zh-CN', {
                      hour: '2-digit',
                      minute: '2-digit'
                    })}
                  </span>
                </div>

                {/* 工具调用显示 */}
                {msg.toolCalls && msg.toolCalls.length > 0 && (
                  <div className="chat-tool-calls">
                    {msg.toolCalls.map((call, callIdx) => (
                      <div key={callIdx} className={`chat-tool-call ${call.status}`}>
                        <div className="chat-tool-call-header">
                          <span className="chat-tool-call-icon">
                            {call.status === 'calling' && '🔄'}
                            {call.status === 'success' && '✅'}
                            {call.status === 'error' && '❌'}
                          </span>
                          <span className="chat-tool-call-title">{call.tool}</span>
                        </div>
                        <div className="chat-tool-call-body">
                          <div className="chat-tool-call-explanation">{call.explanation}</div>
                          {call.sql && (
                            <pre className="chat-tool-call-sql">{call.sql}</pre>
                          )}
                          {call.status === 'success' && (
                            <div className="chat-tool-call-result">
                              查询成功，返回 {call.count} 条记录
                            </div>
                          )}
                          {call.status === 'error' && (
                            <div className="chat-tool-call-error">
                              {call.error}
                            </div>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                )}

                {/* 图表显示 */}
                {msg.charts && msg.charts.length > 0 && (
                  <div className="chat-charts">
                    {msg.charts.map((chart, chartIdx) => (
                      <div key={chartIdx} className={`chat-chart ${chart.status}`}>
                        <div className="chat-chart-header">
                          <span className="chat-chart-icon">
                            {chart.status === 'generating' && '📊'}
                            {chart.status === 'success' && '📈'}
                            {chart.status === 'error' && '❌'}
                          </span>
                          <span className="chat-chart-title">{chart.title}</span>
                        </div>
                        {chart.explanation && (
                          <div className="chat-chart-explanation">{chart.explanation}</div>
                        )}
                        {chart.status === 'success' && chart.config && (
                          <div className="chat-chart-container">
                            <ReactECharts
                              option={chart.config}
                              style={{ height: '400px', width: '100%' }}
                              opts={{ renderer: 'svg' }}
                            />
                          </div>
                        )}
                        {chart.status === 'error' && (
                          <div className="chat-chart-error">
                            {chart.error || '图表生成失败'}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                )}

                {/* 消息内容 */}
                <div className="chat-message-text">
                  {msg.role === 'assistant' ? (
                    <>
                      <ReactMarkdown
                        remarkPlugins={[remarkGfm]}
                        components={{
                          // 代码块
                          code({ node, inline, className, children, ...props }) {
                            return inline ? (
                              <code className="md-inline-code" {...props}>{children}</code>
                            ) : (
                              <pre className="md-code-block">
                                <code {...props}>{children}</code>
                              </pre>
                            );
                          },
                          // 表格
                          table({ children }) {
                            return <table className="md-table">{children}</table>;
                          },
                          // 链接在新标签打开
                          a({ href, children }) {
                            return <a href={href} target="_blank" rel="noreferrer">{children}</a>;
                          }
                        }}
                      >
                        {msg.content}
                      </ReactMarkdown>
                      {msg.isStreaming && <span className="chat-cursor">▊</span>}
                    </>
                  ) : (
                    <>
                      {msg.content}
                      {msg.isStreaming && <span className="chat-cursor">▊</span>}
                    </>
                  )}
                </div>
              </div>
            </div>
          ))
        )}
        <div ref={messagesEndRef} />
      </div>

      <div className="chat-assistant-input">
        <div className="chat-input-wrapper">
          <textarea
            className="chat-input"
            placeholder="输入您的问题，例如：查询今天的所有消息..."
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                handleSendMessage();
              }
            }}
            rows={3}
            disabled={isLoading}
          />
          <Button
            type="primary"
            size="large"
            onClick={handleSendMessage}
            loading={isLoading}
            disabled={!inputValue.trim()}
            className="chat-send-button"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" stroke="currentColor" strokeWidth="2"/>
            </svg>
            发送
          </Button>
        </div>
        <div className="chat-input-hint">
          按 Enter 发送，Shift + Enter 换行
        </div>
      </div>
    </div>
  );
};

export default ChatAssistant;
