import React, { useState, useEffect } from 'react';
import { 
  MessageCircle,
  Settings,
  Info,
} from 'lucide-react';
import { ChatInterface } from '../../components/ChatInterface';
import { testRagGroundingConnection, getRagGroundingConfig } from '../../services/ragGroundingService';
import { RagGroundingConfigInfo } from '../../types/ragGrounding';

/**
 * AI 聊天工具页面
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
const ChatTool: React.FC = () => {
  const [connectionStatus, setConnectionStatus] = useState<'checking' | 'connected' | 'error'>('checking');
  const [configInfo, setConfigInfo] = useState<RagGroundingConfigInfo | null>(null);
  const [showSettings, setShowSettings] = useState(false);

  // 检查连接状态
  useEffect(() => {
    const checkConnection = async () => {
      try {
        setConnectionStatus('checking');
        
        // 测试连接
        await testRagGroundingConnection();
        
        // 获取配置信息
        const config = await getRagGroundingConfig();
        setConfigInfo(config);
        
        setConnectionStatus('connected');
      } catch (error) {
        console.error('连接检查失败:', error);
        setConnectionStatus('error');
      }
    };

    checkConnection();
  }, []);

  // 重新连接
  const handleReconnect = async () => {
    setConnectionStatus('checking');
    try {
      await testRagGroundingConnection();
      setConnectionStatus('connected');
    } catch (error) {
      setConnectionStatus('error');
    }
  };

  return (
    <div className="h-full flex flex-col animate-fade-in">
      {/* 页面头部 */}
      <div className="page-header flex items-center justify-between p-6 border-b border-gray-200 bg-white">
        <div className=" flex items-center gap-4">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
              <MessageCircle className="w-6 h-6 text-white" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-gray-900">AI 智能聊天</h1>
              <p className="text-gray-600">基于 RAG 检索增强生成的智能对话助手</p>
            </div>
          </div>
        </div>

        <div className="flex items-center gap-3">
          {/* 连接状态指示器 */}
          <div className="flex items-center gap-2">
            <div className={`w-2 h-2 rounded-full ${
              connectionStatus === 'connected' ? 'bg-green-500' : 
              connectionStatus === 'checking' ? 'bg-yellow-500 animate-pulse' : 
              'bg-red-500'
            }`}></div>
            <span className="text-sm text-gray-600">
              {connectionStatus === 'connected' ? '已连接' : 
               connectionStatus === 'checking' ? '连接中...' : 
               '连接失败'}
            </span>
          </div>

          <button
            onClick={() => setShowSettings(!showSettings)}
            className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-all duration-200"
            title="设置"
          >
            <Settings className="w-5 h-5" />
          </button>
        </div>
      </div>

      {/* 连接错误提示 */}
      {connectionStatus === 'error' && (
        <div className="mx-6 mt-4 p-4 bg-red-50 border border-red-200 rounded-lg flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-red-100 rounded-full flex items-center justify-center">
              <Info className="w-4 h-4 text-red-500" />
            </div>
            <div>
              <h3 className="font-medium text-red-800">连接失败</h3>
              <p className="text-sm text-red-600">无法连接到 RAG Grounding 服务，请检查网络连接或服务配置。</p>
            </div>
          </div>
          <button
            onClick={handleReconnect}
            className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors duration-200"
          >
            重新连接
          </button>
        </div>
      )}

      {/* 设置面板 */}
      {showSettings && configInfo && (
        <div className="mx-6 mt-4 p-4 bg-blue-50 border border-blue-200 rounded-lg">
          <h3 className="font-medium text-blue-800 mb-3">服务配置信息</h3>
          <div className="grid grid-cols-2 gap-4 text-sm">
            <div>
              <span className="text-blue-600 font-medium">模型:</span>
              <span className="ml-2 text-blue-800">{configInfo.model_name}</span>
            </div>
            <div>
              <span className="text-blue-600 font-medium">温度:</span>
              <span className="ml-2 text-blue-800">{configInfo.temperature}</span>
            </div>
            <div>
              <span className="text-blue-600 font-medium">最大令牌:</span>
              <span className="ml-2 text-blue-800">{configInfo.max_tokens}</span>
            </div>
            <div>
              <span className="text-blue-600 font-medium">超时时间:</span>
              <span className="ml-2 text-blue-800">{configInfo.timeout}s</span>
            </div>
          </div>
        </div>
      )}

      {/* 聊天界面 */}
      <div className="flex-1 pt-6">
        {connectionStatus === 'connected' ? (
          <ChatInterface
            sessionId={`chat-tool-${Date.now()}`}
            maxMessages={3}
            showSources={true}
            enableImageCards={true}
            className="h-full"
            placeholder="请输入您的问题，我会基于知识库为您提供准确的答案..."
          />
        ) : (
          <div className="h-full flex items-center justify-center">
            <div className="text-center">
              <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4 mx-auto">
                <MessageCircle className="w-8 h-8 text-gray-400" />
              </div>
              <h3 className="text-lg font-medium text-gray-700 mb-2">等待连接</h3>
              <p className="text-gray-500">
                {connectionStatus === 'checking' ? '正在连接到服务...' : '请检查服务连接状态'}
              </p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default ChatTool;
