/**
 * 环境配置器组件
 * 
 * 用于创建和编辑工作流执行环境
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState, useEffect } from 'react';
import {
  X,
  Save,
  TestTube,
  CheckCircle,
  XCircle,
  RefreshCw,
  Monitor,
  Cloud,
  Globe,
  Server,
  Info
} from 'lucide-react';

// 环境类型枚举
type EnvironmentType = 'local_comfyui' | 'modal_cloud' | 'runpod_cloud' | 'custom';

// 执行环境接口
interface WorkflowExecutionEnvironment {
  id?: number;
  name: string;
  environment_type: EnvironmentType;
  description?: string;
  base_url: string;
  api_key?: string;
  connection_config_json?: any;
  supported_workflow_types: string[];
  max_concurrent_jobs: number;
  priority: number;
  is_active: boolean;
  is_available: boolean;
  max_memory_mb?: number;
  max_execution_time_seconds?: number;
  metadata_json?: any;
  tags?: string[];
}

// 创建环境请求接口
interface CreateEnvironmentRequest {
  name: string;
  environment_type: EnvironmentType;
  description?: string;
  base_url: string;
  api_key?: string;
  connection_config_json?: any;
  supported_workflow_types: string[];
  max_concurrent_jobs?: number;
  priority?: number;
  max_memory_mb?: number;
  max_execution_time_seconds?: number;
  metadata_json?: any;
  tags?: string[];
}

// 组件属性接口
interface EnvironmentConfiguratorProps {
  /** 编辑的环境（为空时表示创建新环境） */
  environment?: WorkflowExecutionEnvironment;
  /** 是否显示模态框 */
  isOpen: boolean;
  /** 保存回调 */
  onSave: (env: CreateEnvironmentRequest) => void;
  /** 关闭回调 */
  onClose: () => void;
}

/**
 * 环境配置器组件
 */
export const EnvironmentConfigurator: React.FC<EnvironmentConfiguratorProps> = ({
  environment,
  isOpen,
  onSave,
  onClose
}) => {
  const [formData, setFormData] = useState<CreateEnvironmentRequest>({
    name: '',
    environment_type: 'local_comfyui',
    description: '',
    base_url: '',
    api_key: '',
    supported_workflow_types: [],
    max_concurrent_jobs: 1,
    priority: 0,
    max_memory_mb: undefined,
    max_execution_time_seconds: undefined,
    tags: []
  });

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isTestingConnection, setIsTestingConnection] = useState(false);
  const [connectionTestResult, setConnectionTestResult] = useState<{
    success: boolean;
    message: string;
  } | null>(null);

  // 可用的工作流类型
  const availableWorkflowTypes = [
    'outfit_generation',
    'background_replacement',
    'portrait_enhancement',
    'image_upscaling',
    'style_transfer'
  ];

  // 环境类型配置
  const environmentTypeConfigs = {
    local_comfyui: {
      icon: Monitor,
      label: '本地ComfyUI',
      description: '连接到本地运行的ComfyUI实例',
      defaultUrl: 'http://localhost:8188',
      requiresApiKey: false
    },
    modal_cloud: {
      icon: Cloud,
      label: 'Modal云端',
      description: '使用Modal云端服务执行工作流',
      defaultUrl: 'https://your-modal-endpoint.modal.run',
      requiresApiKey: true
    },
    runpod_cloud: {
      icon: Globe,
      label: 'RunPod云端',
      description: '使用RunPod云端GPU服务',
      defaultUrl: 'https://api.runpod.ai',
      requiresApiKey: true
    },
    custom: {
      icon: Server,
      label: '自定义',
      description: '自定义API服务',
      defaultUrl: '',
      requiresApiKey: false
    }
  };

  // 初始化表单数据
  useEffect(() => {
    if (environment) {
      console.log('EnvironmentConfigurator 接收到环境数据:', environment);
      console.log('环境类型:', environment.environment_type, '类型:', typeof environment.environment_type);
      setFormData({
        name: environment.name,
        environment_type: environment.environment_type,
        description: environment.description || '',
        base_url: environment.base_url,
        api_key: environment.api_key || '',
        supported_workflow_types: environment.supported_workflow_types,
        max_concurrent_jobs: environment.max_concurrent_jobs,
        priority: environment.priority,
        max_memory_mb: environment.max_memory_mb,
        max_execution_time_seconds: environment.max_execution_time_seconds,
        tags: environment.tags || []
      });
      console.log('设置的表单数据 environment_type:', environment.environment_type);
    } else {
      // 重置为默认值
      setFormData({
        name: '',
        environment_type: 'local_comfyui',
        description: '',
        base_url: environmentTypeConfigs.local_comfyui.defaultUrl,
        api_key: '',
        supported_workflow_types: [],
        max_concurrent_jobs: 1,
        priority: 0,
        max_memory_mb: undefined,
        max_execution_time_seconds: undefined,
        tags: []
      });
    }
    setErrors({});
    setConnectionTestResult(null);
  }, [environment, isOpen]);

  // 更新表单字段
  const updateField = (field: keyof CreateEnvironmentRequest, value: any) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // 清除该字段的错误
    if (errors[field]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  // 处理环境类型变化
  const handleEnvironmentTypeChange = (type: EnvironmentType) => {
    const config = environmentTypeConfigs[type] || environmentTypeConfigs.local_comfyui;
    updateField('environment_type', type);
    updateField('base_url', config?.defaultUrl || '');
    if (!config?.requiresApiKey) {
      updateField('api_key', '');
    }
  };

  // 验证表单
  const validateForm = () => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = '环境名称不能为空';
    }

    if (!formData.base_url.trim()) {
      newErrors.base_url = 'URL不能为空';
    } else {
      try {
        new URL(formData.base_url);
      } catch {
        newErrors.base_url = 'URL格式不正确';
      }
    }

    const config = environmentTypeConfigs[formData.environment_type] || environmentTypeConfigs.local_comfyui;
    if (config?.requiresApiKey && !formData.api_key?.trim()) {
      newErrors.api_key = 'API密钥不能为空';
    }

    if ((formData.max_concurrent_jobs || 0) < 1) {
      newErrors.max_concurrent_jobs = '最大并发数必须大于0';
    }

    if (formData.supported_workflow_types.length === 0) {
      newErrors.supported_workflow_types = '至少选择一种支持的工作流类型';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 测试连接
  const testConnection = async () => {
    if (!validateForm()) return;

    setIsTestingConnection(true);
    setConnectionTestResult(null);

    try {
      // TODO: 实现实际的连接测试
      await new Promise(resolve => setTimeout(resolve, 2000)); // 模拟测试
      
      setConnectionTestResult({
        success: true,
        message: '连接测试成功！环境可以正常使用。'
      });
    } catch (error) {
      setConnectionTestResult({
        success: false,
        message: '连接测试失败：' + (error as Error).message
      });
    } finally {
      setIsTestingConnection(false);
    }
  };

  // 处理保存
  const handleSave = () => {
    if (!validateForm()) return;

    onSave(formData);
  };

  // 处理工作流类型选择
  const handleWorkflowTypeToggle = (type: string) => {
    const currentTypes = formData.supported_workflow_types;
    const newTypes = currentTypes.includes(type)
      ? currentTypes.filter(t => t !== type)
      : [...currentTypes, type];
    
    updateField('supported_workflow_types', newTypes);
  };

  if (!isOpen) return null;

  const currentConfig = environmentTypeConfigs[formData.environment_type] || environmentTypeConfigs.local_comfyui;
  const IconComponent = currentConfig?.icon || Monitor;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] flex flex-col">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div className="flex items-center space-x-3">
            <IconComponent className="w-6 h-6 text-blue-600" />
            <h2 className="text-lg font-semibold text-gray-900">
              {environment ? '编辑执行环境' : '添加执行环境'}
            </h2>
          </div>
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* 内容 */}
        <div className="flex-1 overflow-y-auto p-6 space-y-6">
          {/* 基本信息 */}
          <div className="space-y-4">
            <h3 className="text-sm font-medium text-gray-900">基本信息</h3>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                环境名称 <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => updateField('name', e.target.value)}
                className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                  errors.name ? 'border-red-300' : 'border-gray-300'
                }`}
                placeholder="例如：本地ComfyUI环境"
              />
              {errors.name && (
                <p className="mt-1 text-sm text-red-600">{errors.name}</p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                环境类型 <span className="text-red-500">*</span>
              </label>
              <div className="grid grid-cols-2 gap-3">
                {Object.entries(environmentTypeConfigs).map(([type, config]) => {
                  const Icon = config.icon;
                  return (
                    <button
                      key={type}
                      type="button"
                      onClick={() => handleEnvironmentTypeChange(type as EnvironmentType)}
                      className={`p-3 border-2 rounded-lg text-left transition-all ${
                        formData.environment_type === type
                          ? 'border-blue-500 bg-blue-50'
                          : 'border-gray-200 hover:border-gray-300'
                      }`}
                    >
                      <div className="flex items-center space-x-2 mb-1">
                        <Icon className="w-4 h-4" />
                        <span className="font-medium text-sm">{config.label}</span>
                      </div>
                      <p className="text-xs text-gray-600">{config.description}</p>
                    </button>
                  );
                })}
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                描述
              </label>
              <textarea
                value={formData.description}
                onChange={(e) => updateField('description', e.target.value)}
                rows={2}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="环境的详细描述..."
              />
            </div>
          </div>

          {/* 连接配置 */}
          <div className="space-y-4">
            <h3 className="text-sm font-medium text-gray-900">连接配置</h3>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                服务URL <span className="text-red-500">*</span>
              </label>
              <input
                type="url"
                value={formData.base_url}
                onChange={(e) => updateField('base_url', e.target.value)}
                className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                  errors.base_url ? 'border-red-300' : 'border-gray-300'
                }`}
                placeholder={currentConfig.defaultUrl}
              />
              {errors.base_url && (
                <p className="mt-1 text-sm text-red-600">{errors.base_url}</p>
              )}
            </div>

            {currentConfig.requiresApiKey && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  API密钥 <span className="text-red-500">*</span>
                </label>
                <input
                  type="password"
                  value={formData.api_key}
                  onChange={(e) => updateField('api_key', e.target.value)}
                  className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                    errors.api_key ? 'border-red-300' : 'border-gray-300'
                  }`}
                  placeholder="输入API密钥"
                />
                {errors.api_key && (
                  <p className="mt-1 text-sm text-red-600">{errors.api_key}</p>
                )}
              </div>
            )}

            {/* 连接测试 */}
            <div className="bg-gray-50 rounded-lg p-4">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-medium text-gray-700">连接测试</span>
                <button
                  onClick={testConnection}
                  disabled={isTestingConnection}
                  className="px-3 py-1 bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition-colors flex items-center space-x-1 disabled:opacity-50"
                >
                  {isTestingConnection ? (
                    <RefreshCw className="w-3 h-3 animate-spin" />
                  ) : (
                    <TestTube className="w-3 h-3" />
                  )}
                  <span>{isTestingConnection ? '测试中...' : '测试连接'}</span>
                </button>
              </div>
              
              {connectionTestResult && (
                <div className={`flex items-start space-x-2 text-sm ${
                  connectionTestResult.success ? 'text-green-700' : 'text-red-700'
                }`}>
                  {connectionTestResult.success ? (
                    <CheckCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
                  ) : (
                    <XCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
                  )}
                  <span>{connectionTestResult.message}</span>
                </div>
              )}
            </div>
          </div>

          {/* 能力配置 */}
          <div className="space-y-4">
            <h3 className="text-sm font-medium text-gray-900">能力配置</h3>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                支持的工作流类型 <span className="text-red-500">*</span>
              </label>
              <div className="grid grid-cols-2 gap-2">
                {availableWorkflowTypes.map((type) => (
                  <label key={type} className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      checked={formData.supported_workflow_types.includes(type)}
                      onChange={() => handleWorkflowTypeToggle(type)}
                      className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                    />
                    <span className="text-sm text-gray-700">{type}</span>
                  </label>
                ))}
              </div>
              {errors.supported_workflow_types && (
                <p className="mt-1 text-sm text-red-600">{errors.supported_workflow_types}</p>
              )}
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  最大并发数 <span className="text-red-500">*</span>
                </label>
                <input
                  type="number"
                  min="1"
                  max="100"
                  value={formData.max_concurrent_jobs}
                  onChange={(e) => updateField('max_concurrent_jobs', parseInt(e.target.value) || 1)}
                  className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                    errors.max_concurrent_jobs ? 'border-red-300' : 'border-gray-300'
                  }`}
                />
                {errors.max_concurrent_jobs && (
                  <p className="mt-1 text-sm text-red-600">{errors.max_concurrent_jobs}</p>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  优先级
                </label>
                <input
                  type="number"
                  min="0"
                  max="100"
                  value={formData.priority}
                  onChange={(e) => updateField('priority', parseInt(e.target.value) || 0)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
                <p className="mt-1 text-xs text-gray-500">数字越大优先级越高</p>
              </div>
            </div>
          </div>

          {/* 资源限制 */}
          <div className="space-y-4">
            <h3 className="text-sm font-medium text-gray-900">资源限制（可选）</h3>
            
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  最大内存 (MB)
                </label>
                <input
                  type="number"
                  min="0"
                  value={formData.max_memory_mb || ''}
                  onChange={(e) => updateField('max_memory_mb', e.target.value ? parseInt(e.target.value) : undefined)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="不限制"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  最大执行时间 (秒)
                </label>
                <input
                  type="number"
                  min="0"
                  value={formData.max_execution_time_seconds || ''}
                  onChange={(e) => updateField('max_execution_time_seconds', e.target.value ? parseInt(e.target.value) : undefined)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="不限制"
                />
              </div>
            </div>
          </div>
        </div>

        {/* 底部操作栏 */}
        <div className="flex items-center justify-between p-6 border-t border-gray-200">
          <div className="flex items-center space-x-2 text-sm text-gray-500">
            <Info className="w-4 h-4" />
            <span>保存后将自动进行健康检查</span>
          </div>
          
          <div className="flex items-center space-x-3">
            <button
              onClick={onClose}
              className="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
            >
              取消
            </button>
            <button
              onClick={handleSave}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
            >
              <Save className="w-4 h-4" />
              <span>{environment ? '更新' : '创建'}</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};
