/**
 * ComfyUI 连接面板组件
 * 提供现代化的连接管理界面
 */

import React, { useState, useEffect } from 'react';
import { 
  WifiIcon, 
  XMarkIcon, 
  CheckCircleIcon, 
  ExclamationTriangleIcon,
  Cog6ToothIcon,
  ArrowPathIcon,
  InformationCircleIcon
} from '@heroicons/react/24/outline';
import { useComfyUIV2Store } from '../../store/comfyuiV2Store';
import type { ComfyUIV2Config } from '../../services/comfyuiV2Service';

interface ComfyUIConnectionPanelProps {
  className?: string;
}

export const ComfyUIConnectionPanel: React.FC<ComfyUIConnectionPanelProps> = ({ 
  className = '' 
}) => {
  const {
    isConnected,
    connectionStatus,
    systemInfo,
    queueStatus,
    config,
    connect,
    disconnect,
    refreshConnectionStatus,
    refreshSystemInfo,
    refreshQueueStatus,
    updateConfig,
    loadConfig,
    startRealtimeMonitor,
    subscribeRealtimeEvents,
    realtimeConnected,
  } = useComfyUIV2Store();

  const [showConfigForm, setShowConfigForm] = useState(false);
  const [configForm, setConfigForm] = useState<ComfyUIV2Config>({
    base_url: 'http://127.0.0.1:8188',
    timeout: 30000,
    retry_attempts: 3,
    enable_cache: true,
    max_concurrency: 4,
    websocket_url: 'ws://127.0.0.1:8188/ws',
  });
  const [isConnecting, setIsConnecting] = useState(false);
  const [connectionError, setConnectionError] = useState<string | null>(null);

  // 组件挂载时加载配置
  useEffect(() => {
    loadConfig();
  }, [loadConfig]);

  // 初始化配置表单
  useEffect(() => {
    if (config) {
      setConfigForm(config);
    }
  }, [config]);

  // 自动刷新状态
  useEffect(() => {
    if (isConnected) {
      const interval = setInterval(() => {
        refreshQueueStatus();
      }, 5000); // 每5秒刷新队列状态

      return () => clearInterval(interval);
    }
  }, [isConnected]); // 移除 refreshQueueStatus 依赖，因为它是稳定的 Zustand action

  const handleConnect = async () => {
    setIsConnecting(true);
    setConnectionError(null);
    
    try {
      await connect(configForm);
      
      // 连接成功后启动实时监控
      try {
        await startRealtimeMonitor();
        await subscribeRealtimeEvents();
      } catch (realtimeError) {
        console.warn('实时监控启动失败，但连接成功:', realtimeError);
      }
      
      setShowConfigForm(false);
    } catch (error) {
      setConnectionError(error instanceof Error ? error.message : '连接失败');
    } finally {
      setIsConnecting(false);
    }
  };

  const handleDisconnect = async () => {
    try {
      await disconnect();
      setConnectionError(null);
    } catch (error) {
      console.error('断开连接失败:', error);
    }
  };

  const handleConfigSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (isConnected) {
      // 如果已连接，更新配置
      try {
        await updateConfig(configForm);
        setShowConfigForm(false);
      } catch (error) {
        setConnectionError(error instanceof Error ? error.message : '更新配置失败');
      }
    } else {
      // 如果未连接，尝试连接
      await handleConnect();
    }
  };

  const getStatusColor = () => {
    if (isConnected) return 'text-green-600';
    if (connectionError) return 'text-red-600';
    return 'text-gray-500';
  };

  const getStatusIcon = () => {
    if (isConnected) return <CheckCircleIcon className="w-5 h-5 text-green-600" />;
    if (connectionError) return <ExclamationTriangleIcon className="w-5 h-5 text-red-600" />;
    return <XMarkIcon className="w-5 h-5 text-gray-500" />;
  };

  return (
    <div className={`bg-white rounded-lg shadow-sm border border-gray-200 ${className}`}>
      {/* 头部 */}
      <div className="px-6 py-4 border-b border-gray-200">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <WifiIcon className="w-6 h-6 text-blue-600" />
            <div>
              <h3 className="text-lg font-semibold text-gray-900">ComfyUI 连接</h3>
              <div className="flex items-center space-x-2 mt-1">
                {getStatusIcon()}
                <span className={`text-sm font-medium ${getStatusColor()}`}>
                  {isConnected ? '已连接' : connectionError ? '连接失败' : '未连接'}
                </span>
                {realtimeConnected && (
                  <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                    实时监控
                  </span>
                )}
              </div>
            </div>
          </div>
          
          <div className="flex items-center space-x-2">
            {isConnected && (
              <button
                onClick={refreshConnectionStatus}
                className="p-2 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100"
                title="刷新状态"
              >
                <ArrowPathIcon className="w-5 h-5" />
              </button>
            )}
            
            <button
              onClick={() => setShowConfigForm(!showConfigForm)}
              className="p-2 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100"
              title="配置"
            >
              <Cog6ToothIcon className="w-5 h-5" />
            </button>
          </div>
        </div>
      </div>

      {/* 连接状态信息 */}
      {isConnected && (connectionStatus || systemInfo || queueStatus) && (
        <div className="px-6 py-4 bg-gray-50">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {/* 连接信息 */}
            {connectionStatus && (
              <div className="bg-white p-3 rounded-lg border">
                <h4 className="text-sm font-medium text-gray-900 mb-2">连接状态</h4>
                <div className="space-y-1 text-xs text-gray-600">
                  <div>重连次数: {connectionStatus.reconnect_attempts}</div>
                  <div>总连接数: {connectionStatus.total_connections}</div>
                  {connectionStatus.last_connected_at && (
                    <div>最后连接: {new Date(connectionStatus.last_connected_at).toLocaleString()}</div>
                  )}
                </div>
              </div>
            )}

            {/* 系统信息 */}
            {systemInfo && (
              <div className="bg-white p-3 rounded-lg border">
                <h4 className="text-sm font-medium text-gray-900 mb-2">系统信息</h4>
                <div className="space-y-1 text-xs text-gray-600">
                  <div>版本: {systemInfo.version}</div>
                  <div>Python: {systemInfo.python_version}</div>
                  <div>平台: {systemInfo.platform}</div>
                </div>
              </div>
            )}

            {/* 队列状态 */}
            {queueStatus && (
              <div className="bg-white p-3 rounded-lg border">
                <h4 className="text-sm font-medium text-gray-900 mb-2">队列状态</h4>
                <div className="space-y-1 text-xs text-gray-600">
                  <div>运行中: {queueStatus.running_count}</div>
                  <div>等待中: {queueStatus.pending_count}</div>
                  <div>历史记录: {queueStatus.history_count}</div>
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* 错误信息 */}
      {connectionError && (
        <div className="px-6 py-4 bg-red-50 border-t border-red-200">
          <div className="flex items-start space-x-3">
            <ExclamationTriangleIcon className="w-5 h-5 text-red-600 mt-0.5" />
            <div>
              <h4 className="text-sm font-medium text-red-800">连接错误</h4>
              <p className="text-sm text-red-700 mt-1">{connectionError}</p>
            </div>
          </div>
        </div>
      )}

      {/* 配置表单 */}
      {showConfigForm && (
        <div className="px-6 py-4 border-t border-gray-200 bg-gray-50">
          <form onSubmit={handleConfigSubmit} className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  API 地址
                </label>
                <input
                  type="url"
                  value={configForm.base_url}
                  onChange={(e) => setConfigForm(prev => ({ ...prev, base_url: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="http://127.0.0.1:8188"
                  required
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  WebSocket 地址
                </label>
                <input
                  type="text"
                  value={configForm.websocket_url}
                  onChange={(e) => setConfigForm(prev => ({ ...prev, websocket_url: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="ws://127.0.0.1:8188/ws"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  超时时间 (毫秒)
                </label>
                <input
                  type="number"
                  value={configForm.timeout}
                  onChange={(e) => setConfigForm(prev => ({ ...prev, timeout: parseInt(e.target.value) }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  min="1000"
                  max="300000"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  重试次数
                </label>
                <input
                  type="number"
                  value={configForm.retry_attempts}
                  onChange={(e) => setConfigForm(prev => ({ ...prev, retry_attempts: parseInt(e.target.value) }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  min="0"
                  max="10"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  最大并发数
                </label>
                <input
                  type="number"
                  value={configForm.max_concurrency}
                  onChange={(e) => setConfigForm(prev => ({ ...prev, max_concurrency: parseInt(e.target.value) }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  min="1"
                  max="16"
                />
              </div>

              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="enable_cache"
                  checked={configForm.enable_cache}
                  onChange={(e) => setConfigForm(prev => ({ ...prev, enable_cache: e.target.checked }))}
                  className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                />
                <label htmlFor="enable_cache" className="ml-2 text-sm text-gray-700">
                  启用缓存
                </label>
              </div>
            </div>

            <div className="flex items-center justify-between pt-4">
              <div className="flex items-center space-x-2 text-sm text-gray-500">
                <InformationCircleIcon className="w-4 h-4" />
                <span>配置将自动保存</span>
              </div>
              
              <div className="flex items-center space-x-3">
                <button
                  type="button"
                  onClick={() => setShowConfigForm(false)}
                  className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50"
                >
                  取消
                </button>
                
                {isConnected ? (
                  <button
                    type="submit"
                    className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
                  >
                    更新配置
                  </button>
                ) : (
                  <button
                    type="submit"
                    disabled={isConnecting}
                    className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-2"
                  >
                    {isConnecting && <ArrowPathIcon className="w-4 h-4 animate-spin" />}
                    <span>{isConnecting ? '连接中...' : '连接'}</span>
                  </button>
                )}
              </div>
            </div>
          </form>
        </div>
      )}

      {/* 连接操作按钮 */}
      {!showConfigForm && (
        <div className="px-6 py-4 border-t border-gray-200">
          <div className="flex items-center justify-between">
            <div className="text-sm text-gray-500">
              {config?.base_url && (
                <span>当前地址: {config.base_url}</span>
              )}
            </div>
            
            <div className="flex items-center space-x-3">
              {isConnected ? (
                <button
                  onClick={handleDisconnect}
                  className="px-4 py-2 text-sm font-medium text-red-700 bg-red-50 border border-red-200 rounded-lg hover:bg-red-100"
                >
                  断开连接
                </button>
              ) : (
                <button
                  onClick={() => setShowConfigForm(true)}
                  className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
                >
                  配置连接
                </button>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
