import React, { useState, useCallback, useRef, useEffect } from 'react';
import { ConversationService, MultiTurnConversationHelper } from '../services/conversationService';
import { 
  ChatMessage, 
  MultiTurnConversationOptions, 
  ConversationUtils,
  MessageContentUtils 
} from '../types/conversation';

/**
 * 多轮对话测试组件
 * 遵循前端开发规范的组件设计，提供多轮对话功能的测试界面
 */
export const MultiTurnChatTest: 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(10);
  
  const messagesEndRef = useRef<HTMLDivElement>(null);

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

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

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

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

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

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

    try {
      // 构建多轮对话请求
      const request = MultiTurnConversationHelper.createTextConversationRequest(
        userMessage.content,
        sessionId || undefined,
        {
          includeHistory: showHistory,
          maxHistoryMessages: maxHistoryMessages,
          systemPrompt: "你是一个友好的AI助手，请用中文回答用户的问题。"
        }
      );

      // 调用多轮对话服务
      const response = await ConversationService.processMultiTurnConversationSafe(request);

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

        // 更新助手消息
        setMessages(prev => prev.map(msg => 
          msg.id === assistantMessage.id 
            ? { 
                ...msg, 
                content: response.data!.assistant_message, 
                status: 'sent' as const,
                metadata: {
                  responseTime: response.data!.response_time_ms,
                  modelUsed: response.data!.model_used
                }
              }
            : msg
        ));
      } else {
        // 处理错误
        setError(response.error || '发送消息失败');
        setMessages(prev => prev.map(msg => 
          msg.id === assistantMessage.id 
            ? { ...msg, content: '抱歉，发生了错误', status: 'error' as const }
            : msg
        ));
      }
    } catch (err) {
      const errorMessage = MultiTurnConversationHelper.extractErrorMessage(err);
      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]);

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

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

  return (
    <div className="flex flex-col h-full max-w-4xl mx-auto p-4">
      {/* 标题和设置 */}
      <div className="mb-4">
        <h2 className="text-2xl font-bold mb-2">多轮对话测试</h2>
        <div className="flex flex-wrap gap-4 items-center text-sm">
          <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) || 10)}
              min="1"
              max="50"
              className="w-16 px-2 py-1 border rounded"
            />
          </div>
          <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>

      {/* 错误提示 */}
      {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">
            开始对话吧！这是一个多轮对话测试界面。
          </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-xs lg:max-w-md 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-1 opacity-70">
                    {ConversationUtils.formatTimestamp(message.timestamp)}
                    {message.metadata?.responseTime && (
                      <span className="ml-2">
                        ({MultiTurnConversationHelper.formatResponseTime(message.metadata.responseTime)})
                      </span>
                    )}
                    {message.status === 'sending' && (
                      <span className="ml-2">发送中...</span>
                    )}
                  </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}条
      </div>
    </div>
  );
};
