/**
 * ComfyUI 设置面板组件
 */

import React, { useState, useEffect, useCallback } from 'react';
import {
  Settings,
  Server,
  CheckCircle,
  XCircle,
  AlertCircle,
  Save,
  RotateCcw,
  Folder,
  Globe,
  Clock
} from 'lucide-react';
import type { ComfyUISettings } from '../../types/outfitPhotoGeneration';
import { OutfitPhotoGenerationService } from '../../services/outfitPhotoGenerationService';
import { LoadingSpinner } from '../LoadingSpinner';

interface ComfyUISettingsPanelProps {
  onSettingsChange?: (settings: ComfyUISettings) => void;
}

export const ComfyUISettingsPanel: React.FC<ComfyUISettingsPanelProps> = ({
  onSettingsChange
}) => {
  const [settings, setSettings] = useState<ComfyUISettings>({
    server_address: 'localhost',
    server_port: 8188,
    is_local: true,
    timeout_seconds: 300,
    enabled: false,
    workflow_directory: undefined,
    output_directory: undefined
  });

  const [originalSettings, setOriginalSettings] = useState<ComfyUISettings | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [connectionStatus, setConnectionStatus] = useState<'unknown' | 'connected' | 'failed'>('unknown');
  const [error, setError] = useState<string | null>(null);
  const [hasChanges, setHasChanges] = useState(false);

  // 加载设置
  const loadSettings = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      
      const loadedSettings = await OutfitPhotoGenerationService.getComfyUISettings();
      setSettings(loadedSettings);
      setOriginalSettings(loadedSettings);
      setHasChanges(false);
    } catch (err) {
      console.error('加载 ComfyUI 设置失败:', err);
      setError(err instanceof Error ? err.message : '加载设置失败');
    } finally {
      setLoading(false);
    }
  }, []);

  // 初始加载
  useEffect(() => {
    loadSettings();
  }, [loadSettings]);

  // 检测设置变化
  useEffect(() => {
    if (originalSettings) {
      const changed = JSON.stringify(settings) !== JSON.stringify(originalSettings);
      setHasChanges(changed);
    }
  }, [settings, originalSettings]);

  // 测试连接
  const testConnection = useCallback(async () => {
    try {
      setTesting(true);
      setConnectionStatus('unknown');
      
      const connected = await OutfitPhotoGenerationService.testComfyUIConnection();
      setConnectionStatus(connected ? 'connected' : 'failed');
    } catch (err) {
      console.error('测试连接失败:', err);
      setConnectionStatus('failed');
    } finally {
      setTesting(false);
    }
  }, []);

  // 保存设置
  const saveSettings = useCallback(async () => {
    try {
      setSaving(true);
      setError(null);
      
      await OutfitPhotoGenerationService.updateComfyUISettings(settings);
      setOriginalSettings(settings);
      setHasChanges(false);
      onSettingsChange?.(settings);
      
      // 如果启用了服务，自动测试连接
      if (settings.enabled) {
        await testConnection();
      }
    } catch (err) {
      console.error('保存设置失败:', err);
      setError(err instanceof Error ? err.message : '保存设置失败');
    } finally {
      setSaving(false);
    }
  }, [settings, onSettingsChange, testConnection]);

  // 重置设置
  const resetSettings = useCallback(() => {
    if (originalSettings) {
      setSettings(originalSettings);
      setHasChanges(false);
      setError(null);
    }
  }, [originalSettings]);

  // 更新设置字段
  const updateSetting = useCallback(<K extends keyof ComfyUISettings>(
    key: K,
    value: ComfyUISettings[K]
  ) => {
    setSettings(prev => ({ ...prev, [key]: value }));
  }, []);

  if (loading) {
    return (
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div className="flex items-center justify-center py-8">
          <LoadingSpinner size="medium" />
          <span className="ml-2 text-gray-600">加载设置中...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-lg shadow-sm border border-gray-200">
      {/* 头部 */}
      <div className="p-4 border-b border-gray-200">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
            <Settings className="w-5 h-5 text-purple-500" />
            ComfyUI 设置
          </h3>
          
          <div className="flex items-center gap-2">
            {settings.enabled && (
              <button
                onClick={testConnection}
                disabled={testing}
                className="px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50 flex items-center gap-1 transition-colors"
              >
                {testing ? (
                  <>
                    <LoadingSpinner size="small" />
                    测试中...
                  </>
                ) : (
                  <>
                    <Server className="w-3 h-3" />
                    测试连接
                  </>
                )}
              </button>
            )}
            
            {connectionStatus !== 'unknown' && (
              <div className={`flex items-center gap-1 px-2 py-1 rounded text-xs font-medium ${
                connectionStatus === 'connected'
                  ? 'text-green-700 bg-green-100'
                  : 'text-red-700 bg-red-100'
              }`}>
                {connectionStatus === 'connected' ? (
                  <>
                    <CheckCircle className="w-3 h-3" />
                    已连接
                  </>
                ) : (
                  <>
                    <XCircle className="w-3 h-3" />
                    连接失败
                  </>
                )}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 错误提示 */}
      {error && (
        <div className="p-4 bg-red-50 border-b border-red-200 flex items-center gap-2 text-red-700">
          <AlertCircle className="w-4 h-4 flex-shrink-0" />
          <span className="text-sm">{error}</span>
        </div>
      )}

      {/* 设置表单 */}
      <div className="p-6 space-y-6">
        {/* 基础设置 */}
        <div>
          <h4 className="text-sm font-medium text-gray-700 mb-4 flex items-center gap-2">
            <Server className="w-4 h-4" />
            服务器设置
          </h4>
          
          <div className="space-y-4">
            {/* 启用开关 */}
            <div className="flex items-center justify-between">
              <div>
                <label className="text-sm font-medium text-gray-700">启用 ComfyUI</label>
                <p className="text-xs text-gray-500">开启穿搭照片生成功能</p>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={settings.enabled}
                  onChange={(e) => updateSetting('enabled', e.target.checked)}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-purple-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
              </label>
            </div>

            {settings.enabled && (
              <>
                {/* 服务器地址 */}
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                  <div className="sm:col-span-2">
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      服务器地址
                    </label>
                    <input
                      type="text"
                      value={settings.server_address}
                      onChange={(e) => updateSetting('server_address', e.target.value)}
                      placeholder="localhost 或 IP 地址"
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                    />
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      端口
                    </label>
                    <input
                      type="number"
                      value={settings.server_port}
                      onChange={(e) => updateSetting('server_port', parseInt(e.target.value) || 8188)}
                      min="1"
                      max="65535"
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                    />
                  </div>
                </div>

                {/* 本地/远程 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    服务器类型
                  </label>
                  <div className="flex gap-4">
                    <label className="flex items-center">
                      <input
                        type="radio"
                        checked={settings.is_local}
                        onChange={() => updateSetting('is_local', true)}
                        className="w-4 h-4 text-purple-600 bg-gray-100 border-gray-300 focus:ring-purple-500"
                      />
                      <span className="ml-2 text-sm text-gray-700 flex items-center gap-1">
                        <Globe className="w-3 h-3" />
                        本地服务器 (HTTP)
                      </span>
                    </label>
                    <label className="flex items-center">
                      <input
                        type="radio"
                        checked={!settings.is_local}
                        onChange={() => updateSetting('is_local', false)}
                        className="w-4 h-4 text-purple-600 bg-gray-100 border-gray-300 focus:ring-purple-500"
                      />
                      <span className="ml-2 text-sm text-gray-700 flex items-center gap-1">
                        <Server className="w-3 h-3" />
                        远程服务器 (HTTPS)
                      </span>
                    </label>
                  </div>
                </div>

                {/* 超时设置 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 flex items-center gap-1">
                    <Clock className="w-3 h-3" />
                    超时时间（秒）
                  </label>
                  <input
                    type="number"
                    value={settings.timeout_seconds}
                    onChange={(e) => updateSetting('timeout_seconds', parseInt(e.target.value) || 300)}
                    min="30"
                    max="3600"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    生成任务的最大等待时间，建议 300-600 秒
                  </p>
                </div>
              </>
            )}
          </div>
        </div>

        {/* 目录设置 */}
        {settings.enabled && (
          <div>
            <h4 className="text-sm font-medium text-gray-700 mb-4 flex items-center gap-2">
              <Folder className="w-4 h-4" />
              目录设置
            </h4>
            
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  工作流目录（可选）
                </label>
                <input
                  type="text"
                  value={settings.workflow_directory || ''}
                  onChange={(e) => updateSetting('workflow_directory', e.target.value || undefined)}
                  placeholder="ComfyUI 工作流文件存放目录"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                />
                <p className="text-xs text-gray-500 mt-1">
                  留空则使用默认目录
                </p>
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  输出目录（可选）
                </label>
                <input
                  type="text"
                  value={settings.output_directory || ''}
                  onChange={(e) => updateSetting('output_directory', e.target.value || undefined)}
                  placeholder="生成图片的输出目录"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                />
                <p className="text-xs text-gray-500 mt-1">
                  留空则使用 ComfyUI 默认输出目录
                </p>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 底部操作栏 */}
      {hasChanges && (
        <div className="p-4 border-t border-gray-200 bg-gray-50 flex items-center justify-between">
          <p className="text-sm text-gray-600">设置已修改，请保存更改</p>
          
          <div className="flex items-center gap-2">
            <button
              onClick={resetSettings}
              disabled={saving}
              className="px-3 py-1 text-sm text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded transition-colors disabled:opacity-50"
            >
              <RotateCcw className="w-3 h-3 mr-1 inline" />
              重置
            </button>
            
            <button
              onClick={saveSettings}
              disabled={saving}
              className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 flex items-center gap-1 transition-colors"
            >
              {saving ? (
                <>
                  <LoadingSpinner size="small" />
                  保存中...
                </>
              ) : (
                <>
                  <Save className="w-3 h-3" />
                  保存设置
                </>
              )}
            </button>
          </div>
        </div>
      )}
    </div>
  );
};
