import React, { useState, useCallback, useRef, useEffect } from 'react';
import { queryRagGrounding } from '../services/ragGroundingService';
import { 
  RagGroundingQueryOptions, 
  GroundingSource,
  ConversationContext,
} from '../types/ragGrounding';

/**
 * 多轮RAG对话测试组件
 * 支持基于检索增强生成的多轮对话功能
 */

interface ChatMessage {
  id: string;
  type: 'user' | 'assistant';
  content: string;
  timestamp: Date;
  status: 'sending' | 'sent' | 'error';
  metadata?: {
    responseTime?: number;
    modelUsed?: string;
    groundingSources?: GroundingSource[];
    conversationContext?: ConversationContext;
  };
}

export const MultiTurnRagChatTest: React.FC = () => {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [sessionId, setSessionId] = useState<string | null>(null);
  const [showHistory, setShowHistory] = useState(true);
  const [maxHistoryMessages, setMaxHistoryMessages] = useState(1);
  const [systemPrompt, setSystemPrompt] = useState('你是一个专业的服装搭配顾问，基于检索到的相关信息为用户提供准确、实用的搭配建议。');
  const [showGroundingSources, setShowGroundingSources] = useState(true);
  
  const messagesEndRef = useRef<HTMLDivElement>(null);

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

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

  // 生成消息ID
  const generateMessageId = () => {
    return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
  };

  // 发送消息
  const handleSendMessage = useCallback(async () => {
    if (!input.trim() || isLoading) return;

    const userMessage: ChatMessage = {
      id: generateMessageId(),
      type: 'user',
      content: input.trim(),
      timestamp: new Date(),
      status: 'sent'
    };

    const assistantMessage: ChatMessage = {
      id: generateMessageId(),
      type: 'assistant',
      content: '',
      timestamp: new Date(),
      status: 'sending'
    };

    // 添加用户消息和占位助手消息
    setMessages(prev => [...prev, userMessage, assistantMessage]);
    setInput('');
    setIsLoading(true);
    setError(null);

    try {
      // 构建查询选项
      const options: RagGroundingQueryOptions = {
        sessionId: sessionId || undefined,
        includeHistory: showHistory,
        maxHistoryMessages: maxHistoryMessages,
        systemPrompt: systemPrompt.trim() || undefined,
        includeMetadata: showGroundingSources,
      };

      // 调用RAG Grounding服务
      const result = await queryRagGrounding(userMessage.content, options);

      if (result.success && result.data) {
        // 更新会话ID
        if (!sessionId && result.data.session_id) {
          setSessionId(result.data.session_id);
        }

        // 更新助手消息
        setMessages(prev => prev.map(msg => 
          msg.id === assistantMessage.id 
            ? { 
                ...msg, 
                content: result.data!.answer, 
                status: 'sent' as const,
                metadata: {
                  responseTime: result.data!.response_time_ms,
                  modelUsed: result.data!.model_used,
                  groundingSources: result.data!.grounding_metadata?.sources,
                  conversationContext: result.data!.conversation_context,
                }
              }
            : msg
        ));
      } else {
        // 处理错误
        setError(result.error || '查询失败');
        setMessages(prev => prev.map(msg => 
          msg.id === assistantMessage.id 
            ? { ...msg, content: '抱歉，查询过程中发生了错误', status: 'error' as const }
            : msg
        ));
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '未知错误';
      setError(errorMessage);
      setMessages(prev => prev.map(msg => 
        msg.id === assistantMessage.id 
          ? { ...msg, content: '抱歉，发生了系统错误', status: 'error' as const }
          : msg
      ));
    } finally {
      setIsLoading(false);
    }
  }, [input, isLoading, sessionId, showHistory, maxHistoryMessages, systemPrompt, showGroundingSources]);

  // 清空对话
  const handleClearChat = useCallback(() => {
    setMessages([]);
    setSessionId(null);
    setError(null);
  }, []);

  // 处理键盘事件
  const handleKeyPress = useCallback((e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  }, [handleSendMessage]);

  // 格式化响应时间
  const formatResponseTime = (ms: number) => {
    if (ms < 1000) return `${ms}ms`;
    return `${(ms / 1000).toFixed(1)}s`;
  };

  return (
    <div className="flex flex-col h-full max-w-6xl mx-auto p-4">
      {/* 标题和设置 */}
      <div className="mb-4">
        <h2 className="text-2xl font-bold mb-2">多轮RAG对话测试</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
          <div className="space-y-2">
            <div className="flex items-center gap-2">
              <label className="flex items-center gap-1">
                <input
                  type="checkbox"
                  checked={showHistory}
                  onChange={(e) => setShowHistory(e.target.checked)}
                  className="rounded"
                />
                包含历史消息
              </label>
            </div>
            <div className="flex items-center gap-2">
              <label>最大历史消息数:</label>
              <input
                type="number"
                value={maxHistoryMessages}
                onChange={(e) => setMaxHistoryMessages(parseInt(e.target.value) || 1)}
                min="1"
                max="50"
                className="w-16 px-2 py-1 border rounded"
              />
            </div>
            <div className="flex items-center gap-2">
              <label className="flex items-center gap-1">
                <input
                  type="checkbox"
                  checked={showGroundingSources}
                  onChange={(e) => setShowGroundingSources(e.target.checked)}
                  className="rounded"
                />
                显示检索来源
              </label>
            </div>
          </div>
          <div className="space-y-2">
            <div className="text-gray-600">
              会话ID: {sessionId ? sessionId.substring(0, 8) + '...' : '未创建'}
            </div>
            <button
              onClick={handleClearChat}
              className="px-3 py-1 bg-gray-500 text-white rounded hover:bg-gray-600"
            >
              清空对话
            </button>
          </div>
        </div>
        
        {/* 系统提示词设置 */}
        <div className="mt-4">
          <label className="block text-sm font-medium mb-1">系统提示词:</label>
          <textarea
            value={systemPrompt}
            onChange={(e) => setSystemPrompt(e.target.value)}
            placeholder="设置系统提示词..."
            className="w-full px-3 py-2 border rounded-lg resize-none"
            rows={2}
          />
        </div>
      </div>

      {/* 错误提示 */}
      {error && (
        <div className="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded">
          错误: {error}
        </div>
      )}

      {/* 消息列表 */}
      <div className="flex-1 overflow-y-auto border rounded-lg p-4 mb-4 bg-gray-50">
        {messages.length === 0 ? (
          <div className="text-center text-gray-500 py-8">
            开始RAG对话吧！这是一个基于检索增强生成的多轮对话测试界面。
          </div>
        ) : (
          <div className="space-y-4">
            {messages.map((message) => (
              <div
                key={message.id}
                className={`flex ${message.type === 'user' ? 'justify-end' : 'justify-start'}`}
              >
                <div
                  className={`max-w-2xl px-4 py-2 rounded-lg ${
                    message.type === 'user'
                      ? 'bg-blue-500 text-white'
                      : message.status === 'error'
                      ? 'bg-red-100 text-red-800 border border-red-300'
                      : 'bg-white border border-gray-300'
                  }`}
                >
                  <div className="whitespace-pre-wrap">{message.content}</div>
                  
                  {/* 消息元数据 */}
                  <div className="text-xs mt-2 opacity-70">
                    {message.timestamp.toLocaleTimeString()}
                    {message.metadata?.responseTime && (
                      <span className="ml-2">
                        ({formatResponseTime(message.metadata.responseTime)})
                      </span>
                    )}
                    {message.status === 'sending' && (
                      <span className="ml-2">发送中...</span>
                    )}
                  </div>

                  {/* 检索来源 */}
                  {message.metadata?.groundingSources && message.metadata.groundingSources.length > 0 && (
                    <div className="mt-2 pt-2 border-t border-gray-200">
                      <div className="text-xs font-medium mb-1">检索来源:</div>
                      <div className="space-y-1">
                        {message.metadata.groundingSources.map((source, index) => (
                          <div key={index} className="text-xs bg-gray-100 p-2 rounded">
                            <div className="font-medium">{source.title}</div>
                            {source.uri && (
                              <div className="text-blue-600 truncate">{source.uri}</div>
                            )}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* 对话上下文信息 */}
                  {message.metadata?.conversationContext && (
                    <div className="mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600">
                      上下文: {message.metadata.conversationContext.total_messages} 条消息
                      {message.metadata.conversationContext.history_included && 
                        ` (包含 ${message.metadata.conversationContext.context_length} 条历史)`
                      }
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>

      {/* 输入区域 */}
      <div className="flex gap-2">
        <textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyPress={handleKeyPress}
          placeholder="输入消息... (Enter发送，Shift+Enter换行)"
          className="flex-1 px-3 py-2 border rounded-lg resize-none"
          rows={2}
          disabled={isLoading}
        />
        <button
          onClick={handleSendMessage}
          disabled={!input.trim() || isLoading}
          className="px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:bg-gray-300 disabled:cursor-not-allowed"
        >
          {isLoading ? '查询中...' : '发送'}
        </button>
      </div>

      {/* 统计信息 */}
      <div className="mt-2 text-xs text-gray-500 text-center">
        消息数: {messages.length} | 
        历史消息: {showHistory ? '开启' : '关闭'} | 
        最大历史: {maxHistoryMessages}条 |
        检索来源: {showGroundingSources ? '显示' : '隐藏'}
      </div>
    </div>
  );
};
