/**
 * ComfyUI V2 工作流模板创建器组件
 * 专门用于创建符合ComfyUI SDK规范的WorkflowTemplateData格式的模板
 */

import React, { useState, useEffect } from 'react';
import {
  X,
  Save,
  Upload,
  FileText,
  Settings,
  Info,
  AlertCircle,
  Plus,
  Trash2,
  ChevronDown,
  ChevronRight,
  Type,
  Hash,
  ToggleLeft,
  Image,
  Music,
  Video,
  List,
  Braces,
  Link,
} from 'lucide-react';

// 定义符合ComfyUI SDK的模板数据结构
interface TemplateMetadata {
  id: string;
  name: string;
  description?: string;
  version?: string;
  author?: string;
  tags?: string[];
  category?: string;
}

interface ParameterSchema {
  param_type: 'string' | 'number' | 'boolean' | 'array' | 'object' | 'image' | 'audio' | 'video' | 'integer' | 'float';
  required?: boolean;
  default?: any;
  description?: string;
  enum?: any[];
  min?: number;
  max?: number;
  step?: number;
  pattern?: string;
  items?: ParameterSchema;
  properties?: Record<string, ParameterSchema>;
  // 媒体文件相关属性
  accept?: string; // 文件类型限制
  maxSize?: number; // 最大文件大小（字节）
  width?: number; // 图片/视频宽度
  height?: number; // 图片/视频高度
  duration?: number; // 音频/视频时长限制
  // 工作流节点关联
  node_mapping?: NodeMapping;
}

// 工作流节点信息
interface WorkflowNode {
  id: string;
  class_type: string;
  title?: string;
  inputs: Record<string, any>;
}

// 节点映射配置
interface NodeMapping {
  node_id: string;
  input_field: string;
}

interface WorkflowTemplateData {
  metadata: TemplateMetadata;
  workflow: any; // ComfyUI workflow JSON
  parameters: Record<string, ParameterSchema>;
}

interface CreateTemplateRequest {
  name: string;
  category?: string;
  description?: string;
  template_data: WorkflowTemplateData;
  parameter_schema: Record<string, ParameterSchema>;
  tags: string[];
  author?: string;
}

interface WorkflowTemplateCreatorProps {
  /** 是否显示模态框 */
  isOpen: boolean;
  /** 关闭回调 */
  onClose: () => void;
  /** 保存回调 */
  onSave: (templateData: CreateTemplateRequest) => Promise<void>;
  /** 编辑的模板（为空时表示创建新模板） */
  editingTemplate?: any;
}

/**
 * ComfyUI V2 工作流模板创建器组件
 */
export const WorkflowTemplateCreator: React.FC<WorkflowTemplateCreatorProps> = ({
  isOpen,
  onClose,
  onSave,
  editingTemplate
}) => {
  const [activeTab, setActiveTab] = useState<'basic' | 'workflow' | 'parameters'>('basic');
  const [templateData, setTemplateData] = useState<WorkflowTemplateData>({
    metadata: {
      id: '',
      name: '',
      description: '',
      version: '1.0.0',
      author: '',
      tags: [],
      category: '',
    },
    workflow: {},
    parameters: {},
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isSaving, setIsSaving] = useState(false);
  const [workflowJsonText, setWorkflowJsonText] = useState('{}');
  const [newParameterName, setNewParameterName] = useState('');
  const [expandedParameters, setExpandedParameters] = useState<Set<string>>(new Set());
  const [availableNodes, setAvailableNodes] = useState<WorkflowNode[]>([]);
  const [showNodeSelector, setShowNodeSelector] = useState<string | null>(null);

  // 解析工作流JSON，提取可用节点
  useEffect(() => {
    if (workflowJsonText && workflowJsonText !== '{}') {
      try {
        const workflow = JSON.parse(workflowJsonText);
        const nodes: WorkflowNode[] = [];

        Object.entries(workflow).forEach(([nodeId, nodeData]: [string, any]) => {
          if (nodeData && typeof nodeData === 'object') {
            const node: WorkflowNode = {
              id: String(nodeId),
              class_type: String(nodeData.class_type || 'Unknown'),
              title: nodeData._meta?.title ? String(nodeData._meta.title) : undefined,
              inputs: (nodeData.inputs && typeof nodeData.inputs === 'object') ? nodeData.inputs : {}
            };
            nodes.push(node);
          }
        });

        setAvailableNodes(nodes);
      } catch (error) {
        console.error('解析工作流JSON时出错:', error);
        setAvailableNodes([]);
      }
    } else {
      setAvailableNodes([]);
    }
  }, [workflowJsonText]);

  // 重置表单数据
  useEffect(() => {
    if (isOpen) {
      if (editingTemplate) {
        setTemplateData({
          metadata: {
            id: editingTemplate.id || '',
            name: editingTemplate.name || '',
            description: editingTemplate.description || '',
            version: editingTemplate.version || '1.0.0',
            author: editingTemplate.author || '',
            tags: editingTemplate.tags || [],
            category: editingTemplate.category || '',
          },
          workflow: editingTemplate.workflow_data || {},
          parameters: editingTemplate.parameters || {},
        });
        setWorkflowJsonText(JSON.stringify(editingTemplate.workflow_data || {}, null, 2));
      } else {
        // 重置为默认值
        setTemplateData({
          metadata: {
            id: '',
            name: '',
            description: '',
            version: '1.0.0',
            author: '',
            tags: [],
            category: '',
          },
          workflow: {},
          parameters: {},
        });
        setWorkflowJsonText('{}');
      }
      setErrors({});
      setActiveTab('basic');
    }
  }, [editingTemplate, isOpen]);

  // 更新模板元数据字段
  const updateMetadata = (field: keyof TemplateMetadata, value: any) => {
    setTemplateData(prev => ({
      ...prev,
      metadata: { ...prev.metadata, [field]: value }
    }));
    // 清除该字段的错误
    if (errors[field]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  // 更新参数
  const updateParameter = (paramName: string, schema: ParameterSchema) => {
    setTemplateData(prev => ({
      ...prev,
      parameters: { ...prev.parameters, [paramName]: schema }
    }));
  };

  // 删除参数
  const removeParameter = (paramName: string) => {
    setTemplateData(prev => {
      const newParameters = { ...prev.parameters };
      delete newParameters[paramName];
      return { ...prev, parameters: newParameters };
    });
  };

  // 添加新参数
  const addParameter = () => {
    if (!newParameterName.trim()) return;

    const newSchema: ParameterSchema = {
      param_type: 'string',
      required: false,
      description: '',
      default: '',
    };

    updateParameter(newParameterName.trim(), newSchema);
    setNewParameterName('');
  };

  // 切换参数展开/折叠状态
  const toggleParameterExpanded = (paramName: string) => {
    setExpandedParameters(prev => {
      const newSet = new Set(prev);
      if (newSet.has(paramName)) {
        newSet.delete(paramName);
      } else {
        newSet.add(paramName);
      }
      return newSet;
    });
  };

  // 根据参数类型获取默认配置
  const getDefaultConfigForType = (type: string): Partial<ParameterSchema> => {
    switch (type) {
      case 'integer':
        return {
          default: 10,
          min: 0,
          max: 100,
          step: 1,
        };
      case 'float':
        return {
          default: 0.3,
          min: 0.0,
          max: 1.0,
          step: 0.01,
        };
      case 'image':
        return {
          default: '',
          accept: '.jpg,.jpeg,.png,.webp,.bmp,.tiff',
          maxSize: 10 * 1024 * 1024, // 10MB
          description: '支持的图片格式：JPG, PNG, WebP, BMP, TIFF',
        };
      case 'audio':
        return {
          default: '',
          accept: '.mp3,.wav,.flac,.aac,.ogg',
          maxSize: 50 * 1024 * 1024, // 50MB
          description: '支持的音频格式：MP3, WAV, FLAC, AAC, OGG',
        };
      case 'video':
        return {
          default: '',
          accept: '.mp4,.avi,.mov,.mkv,.webm',
          maxSize: 500 * 1024 * 1024, // 500MB
          description: '支持的视频格式：MP4, AVI, MOV, MKV, WebM',
        };
      case 'boolean':
        return {
          default: false,
        };
      case 'number':
        return {
          default: 0,
          min: 0,
          max: 100,
        };
      default:
        return {
          default: '',
        };
    }
  };

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

    if (!templateData.metadata.name.trim()) {
      newErrors.name = '模板名称不能为空';
    }

    if (!templateData.metadata.id.trim()) {
      newErrors.id = '模板ID不能为空';
    }

    if (!workflowJsonText.trim() || workflowJsonText.trim() === '{}') {
      newErrors.workflow = '工作流数据不能为空';
    } else {
      try {
        const parsed = JSON.parse(workflowJsonText);
        if (typeof parsed !== 'object' || parsed === null) {
          newErrors.workflow = '工作流数据必须是有效的JSON对象';
        }
      } catch (error) {
        newErrors.workflow = 'JSON格式错误，请检查语法';
      }
    }

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

  // 获取参数类型的显示信息
  const getParameterTypeInfo = (type: string) => {
    const typeMap = {
      string: { label: '字符串', icon: Type, color: 'text-blue-600', bgColor: 'bg-blue-50' },
      integer: { label: '整数', icon: Hash, color: 'text-green-600', bgColor: 'bg-green-50' },
      float: { label: '浮点数', icon: Hash, color: 'text-green-600', bgColor: 'bg-green-50' },
      number: { label: '数字', icon: Hash, color: 'text-green-600', bgColor: 'bg-green-50' },
      boolean: { label: '布尔值', icon: ToggleLeft, color: 'text-purple-600', bgColor: 'bg-purple-50' },
      image: { label: '图片', icon: Image, color: 'text-pink-600', bgColor: 'bg-pink-50' },
      audio: { label: '音频', icon: Music, color: 'text-orange-600', bgColor: 'bg-orange-50' },
      video: { label: '视频', icon: Video, color: 'text-red-600', bgColor: 'bg-red-50' },
      array: { label: '数组', icon: List, color: 'text-indigo-600', bgColor: 'bg-indigo-50' },
      object: { label: '对象', icon: Braces, color: 'text-gray-600', bgColor: 'bg-gray-50' },
    };
    return typeMap[type as keyof typeof typeMap] || typeMap.string;
  };

  // 格式化参数值显示
  const formatParameterValue = (schema: ParameterSchema) => {
    if (schema.default === undefined || schema.default === null || schema.default === '') {
      return '未设置';
    }

    if (schema.param_type === 'boolean') {
      return schema.default ? 'True' : 'False';
    }

    if (schema.param_type === 'integer' || schema.param_type === 'float' || schema.param_type === 'number') {
      let value = String(schema.default);
      if (schema.min !== undefined || schema.max !== undefined) {
        const range = [];
        if (schema.min !== undefined) range.push(`最小: ${schema.min}`);
        if (schema.max !== undefined) range.push(`最大: ${schema.max}`);
        if (range.length > 0) value += ` (${range.join(', ')})`;
      }
      return value;
    }

    if (schema.param_type === 'image' || schema.param_type === 'audio' || schema.param_type === 'video') {
      return schema.default || '未设置文件';
    }

    return String(schema.default);
  };

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

    setIsSaving(true);
    try {
      const workflowData = JSON.parse(workflowJsonText);
      
      // 构建符合ComfyUI SDK规范的模板数据
      const finalTemplateData: WorkflowTemplateData = {
        ...templateData,
        workflow: workflowData,
      };

      const requestData: CreateTemplateRequest = {
        name: templateData.metadata.name,
        category: templateData.metadata.category,
        description: templateData.metadata.description,
        template_data: finalTemplateData,
        parameter_schema: templateData.parameters,
        tags: templateData.metadata.tags || [],
        author: templateData.metadata.author,
      };

      await onSave(requestData);
    } catch (error) {
      console.error('保存模板失败:', error);
      setErrors({ general: `保存失败: ${error}` });
    } finally {
      setIsSaving(false);
    }
  };

  // 导入ComfyUI工作流
  const handleImportWorkflow = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json';
    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          try {
            const workflow = JSON.parse(e.target?.result as string);
            setWorkflowJsonText(JSON.stringify(workflow, null, 2));
            setTemplateData(prev => ({ ...prev, workflow }));
            // 清除工作流相关错误
            if (errors.workflow) {
              setErrors(prev => {
                const newErrors = { ...prev };
                delete newErrors.workflow;
                return newErrors;
              });
            }
          } catch (error) {
            console.error('解析ComfyUI工作流失败:', error);
            setErrors({ workflow: '文件格式错误，请选择有效的JSON文件' });
          }
        };
        reader.readAsText(file);
      }
    };
    input.click();
  };

  // 处理工作流JSON文本变化
  const handleWorkflowJsonChange = (value: string) => {
    setWorkflowJsonText(value);
    try {
      if (value.trim()) {
        const workflow = JSON.parse(value);
        setTemplateData(prev => ({ ...prev, workflow }));
        // 清除工作流相关错误
        if (errors.workflow) {
          setErrors(prev => {
            const newErrors = { ...prev };
            delete newErrors.workflow;
            return newErrors;
          });
        }
      }
    } catch (error) {
      // JSON解析错误会在验证时处理，这里不需要立即设置错误
    }
  };

  // 处理标签输入
  const handleTagsChange = (tagsString: string) => {
    const tags = tagsString
      .split(',')
      .map(tag => tag.trim())
      .filter(tag => tag.length > 0);
    updateMetadata('tags', tags);
  };

  // 生成模板ID
  const generateTemplateId = (name: string) => {
    return name
      .toLowerCase()
      .replace(/[^a-z0-9\s]/g, '')
      .replace(/\s+/g, '-')
      .trim();
  };

  // 处理名称变化，自动生成ID
  const handleNameChange = (name: string) => {
    updateMetadata('name', name);
    if (!editingTemplate) {
      updateMetadata('id', generateTemplateId(name));
    }
  };

  // 更新参数的节点映射
  const updateParameterNodeMapping = (paramName: string, nodeMapping: NodeMapping | undefined) => {
    const currentSchema = templateData.parameters[paramName];
    if (currentSchema) {
      updateParameter(paramName, {
        ...currentSchema,
        node_mapping: nodeMapping
      });

      // 如果设置了节点映射，自动更新工作流JSON中对应的字段值
      if (nodeMapping) {
        updateWorkflowNodeValue(nodeMapping.node_id, nodeMapping.input_field, `{{${paramName}}}`);
      }
    }
  };

  // 更新工作流中指定节点的输入字段值
  const updateWorkflowNodeValue = (nodeId: string, inputField: string, value: string) => {
    try {
      const workflow = JSON.parse(workflowJsonText);
      if (workflow[nodeId] && workflow[nodeId].inputs) {
        workflow[nodeId].inputs[inputField] = value;
        const updatedJsonText = JSON.stringify(workflow, null, 2);
        setWorkflowJsonText(updatedJsonText);
        setTemplateData(prev => ({ ...prev, workflow }));
      }
    } catch (error) {
      console.error('更新工作流节点值失败:', error);
    }
  };



  if (!isOpen) return null;

  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-4xl w-full max-h-[95vh] 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">
            <Settings className="w-6 h-6 text-blue-600" />
            <h2 className="text-lg font-semibold text-gray-900">
              {editingTemplate ? '编辑工作流模板' : '创建工作流模板'}
            </h2>
          </div>
          
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* 错误提示 */}
        {errors.general && (
          <div className="mx-6 mt-4 p-3 bg-red-50 border border-red-200 rounded-lg flex items-center space-x-2">
            <AlertCircle className="w-5 h-5 text-red-600" />
            <span className="text-red-700">{errors.general}</span>
          </div>
        )}

        {/* 标签页导航 */}
        <div className="flex border-b border-gray-200 px-6">
          {[
            { id: 'basic', label: '基本信息', icon: FileText },
            { id: 'workflow', label: '工作流配置', icon: Settings },
            { id: 'parameters', label: '参数配置', icon: Info },
          ].map(tab => {
            const Icon = tab.icon;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as any)}
                className={`flex items-center space-x-2 px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
                  activeTab === tab.id
                    ? 'border-blue-500 text-blue-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700'
                }`}
              >
                <Icon className="w-4 h-4" />
                <span>{tab.label}</span>
              </button>
            );
          })}
        </div>

        {/* 内容区域 */}
        <div className="flex-1 overflow-y-auto p-6">
          {/* 基本信息标签页 */}
          {activeTab === 'basic' && (
            <div className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    模板名称 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={templateData.metadata.name}
                    onChange={(e) => handleNameChange(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="例如：AI模型面部和头发细节修复"
                  />
                  {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">
                    模板ID <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={templateData.metadata.id}
                    onChange={(e) => updateMetadata('id', e.target.value)}
                    className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                      errors.id ? 'border-red-300' : 'border-gray-300'
                    }`}
                    placeholder="例如：ai-model-face-hair-fix"
                  />
                  {errors.id && (
                    <p className="mt-1 text-sm text-red-600">{errors.id}</p>
                  )}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  描述
                </label>
                <textarea
                  value={templateData.metadata.description || ''}
                  onChange={(e) => updateMetadata('description', e.target.value)}
                  rows={3}
                  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 className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    分类
                  </label>
                  <input
                    type="text"
                    value={templateData.metadata.category || ''}
                    onChange={(e) => updateMetadata('category', 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-transparent"
                    placeholder="例如：enhancement"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    版本
                  </label>
                  <input
                    type="text"
                    value={templateData.metadata.version || ''}
                    onChange={(e) => updateMetadata('version', 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-transparent"
                    placeholder="例如：1.0.0"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    作者
                  </label>
                  <input
                    type="text"
                    value={templateData.metadata.author || ''}
                    onChange={(e) => updateMetadata('author', 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-transparent"
                    placeholder="例如：ComfyUI SDK"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  标签
                </label>
                <input
                  type="text"
                  value={templateData.metadata.tags?.join(', ') || ''}
                  onChange={(e) => handleTagsChange(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-transparent"
                  placeholder="用逗号分隔，例如：face-enhancement, hair-enhancement, portrait"
                />
                <p className="mt-1 text-sm text-gray-500">用逗号分隔多个标签</p>
              </div>
            </div>
          )}

          {/* 工作流配置标签页 */}
          {activeTab === 'workflow' && (
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-medium text-gray-900">ComfyUI工作流配置</h3>
                <button
                  onClick={handleImportWorkflow}
                  className="px-3 py-1 bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition-colors flex items-center space-x-1"
                >
                  <Upload className="w-4 h-4" />
                  <span>导入JSON</span>
                </button>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  工作流JSON <span className="text-red-500">*</span>
                </label>
                <textarea
                  value={workflowJsonText}
                  onChange={(e) => handleWorkflowJsonChange(e.target.value)}
                  rows={20}
                  className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent font-mono text-sm ${
                    errors.workflow ? 'border-red-300' : 'border-gray-300'
                  }`}
                  placeholder="粘贴ComfyUI导出的工作流JSON..."
                />
                {errors.workflow && (
                  <p className="mt-1 text-sm text-red-600">{errors.workflow}</p>
                )}
                <p className="mt-1 text-sm text-gray-500">
                  从ComfyUI界面导出工作流JSON并粘贴到这里
                </p>
              </div>
            </div>
          )}

          {/* 参数配置标签页 */}
          {activeTab === 'parameters' && (
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-medium text-gray-900">模板参数配置</h3>
                <div className="flex items-center space-x-2">
                  <input
                    type="text"
                    value={newParameterName}
                    onChange={(e) => setNewParameterName(e.target.value)}
                    placeholder="参数名称"
                    className="px-3 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    onKeyDown={(e) => e.key === 'Enter' && addParameter()}
                  />
                  <button
                    onClick={addParameter}
                    disabled={!newParameterName.trim()}
                    className="px-3 py-1 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-1"
                  >
                    <Plus className="w-4 h-4" />
                    <span>添加参数</span>
                  </button>
                </div>
              </div>

              <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
                <div className="flex items-center space-x-2 mb-2">
                  <Info className="w-4 h-4 text-blue-600" />
                  <span className="text-sm font-medium text-gray-700">参数配置说明</span>
                </div>
                <div className="space-y-2 text-sm text-gray-600">
                  <p>
                    参数用于在工作流中定义可配置的变量。在工作流JSON中使用 <code className="bg-gray-200 px-1 rounded">{"{{参数名}}"}</code> 语法引用参数。
                    例如：<code className="bg-gray-200 px-1 rounded">{"{{input_image}}"}</code>
                  </p>
                  <p>
                    <strong>节点关联功能：</strong>可以将参数直接关联到工作流节点的输入字段，系统会自动将参数值替换到对应的节点输入中。
                    关联后，工作流中对应的字段值会被替换为 <code className="bg-gray-200 px-1 rounded">{"{{参数名}}"}</code> 格式。
                  </p>
                </div>
              </div>

              {Object.keys(templateData.parameters).length === 0 ? (
                <div className="text-center py-8 text-gray-500">
                  <Settings className="w-12 h-12 mx-auto mb-3 text-gray-400" />
                  <p>暂无参数配置</p>
                  <p className="text-sm">添加参数来让模板更加灵活可配置</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {Object.entries(templateData.parameters).map(([paramName, schema]) => {
                    const typeInfo = getParameterTypeInfo(schema.param_type);
                    const isExpanded = expandedParameters.has(paramName);
                    const Icon = typeInfo.icon;

                    return (
                      <div key={paramName} className="bg-white border border-gray-200 rounded-lg overflow-hidden">
                        {/* 折叠头部 - 简洁信息展示 */}
                        <div
                          className="p-4 cursor-pointer hover:bg-gray-50 transition-colors"
                          onClick={() => toggleParameterExpanded(paramName)}
                        >
                          <div className="flex items-center justify-between">
                            <div className="flex items-center space-x-3">
                              <div className="flex items-center space-x-2">
                                {isExpanded ? (
                                  <ChevronDown className="w-4 h-4 text-gray-500" />
                                ) : (
                                  <ChevronRight className="w-4 h-4 text-gray-500" />
                                )}
                                <div className={`p-1.5 rounded ${typeInfo.bgColor}`}>
                                  <Icon className={`w-4 h-4 ${typeInfo.color}`} />
                                </div>
                              </div>

                              <div className="flex-1">
                                <div className="flex items-center space-x-2">
                                  <h4 className="font-medium text-gray-900">{paramName}</h4>
                                  <span className={`px-2 py-0.5 text-xs rounded-full ${typeInfo.bgColor} ${typeInfo.color}`}>
                                    {typeInfo.label}
                                  </span>
                                  {schema.required && (
                                    <span className="px-2 py-0.5 text-xs rounded-full bg-red-50 text-red-600">
                                      必填
                                    </span>
                                  )}
                                </div>

                                <div className="flex items-center space-x-4 mt-1 text-sm text-gray-500">
                                  <span>默认值: {formatParameterValue(schema)}</span>
                                  {schema.description && (
                                    <span className="truncate max-w-xs">描述: {schema.description}</span>
                                  )}
                                </div>
                              </div>
                            </div>

                            <div className="flex items-center space-x-2">
                              <button
                                onClick={(e) => {
                                  e.stopPropagation();
                                  removeParameter(paramName);
                                }}
                                className="p-1 text-red-600 hover:bg-red-50 rounded transition-colors"
                                title="删除参数"
                              >
                                <Trash2 className="w-4 h-4" />
                              </button>
                            </div>
                          </div>
                        </div>

                        {/* 展开的详细配置表单 */}
                        {isExpanded && (
                          <div className="border-t border-gray-200 p-4 bg-gray-50">
                            <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">
                            参数类型
                          </label>
                          <select
                            value={schema.param_type}
                            onChange={(e) => {
                              const newType = e.target.value as any;
                              const defaultConfig = getDefaultConfigForType(newType);
                              updateParameter(paramName, {
                                ...schema,
                                param_type: newType,
                                ...defaultConfig
                              });
                            }}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                          >
                            <optgroup label="基础类型">
                              <option value="string">字符串 (String)</option>
                              <option value="boolean">布尔值 (Boolean)</option>
                              <option value="array">数组 (Array)</option>
                              <option value="object">对象 (Object)</option>
                            </optgroup>
                            <optgroup label="数值类型">
                              <option value="integer">整数 (Integer)</option>
                              <option value="float">浮点数 (Float)</option>
                              <option value="number">数字 (Number)</option>
                            </optgroup>
                            <optgroup label="媒体类型">
                              <option value="image">图片 (Image)</option>
                              <option value="audio">音频 (Audio)</option>
                              <option value="video">视频 (Video)</option>
                            </optgroup>
                          </select>
                        </div>

                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-1">
                            默认值
                          </label>
                          {schema.param_type === 'boolean' ? (
                            <select
                              value={schema.default ? 'true' : 'false'}
                              onChange={(e) => updateParameter(paramName, {
                                ...schema,
                                default: e.target.value === 'true'
                              })}
                              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                            >
                              <option value="false">False</option>
                              <option value="true">True</option>
                            </select>
                          ) : schema.param_type === 'integer' || schema.param_type === 'float' || schema.param_type === 'number' ? (
                            <input
                              type="number"
                              step={schema.step || (schema.param_type === 'float' ? 0.01 : 1)}
                              min={schema.min}
                              max={schema.max}
                              value={schema.default !== undefined ? schema.default : ''}
                              onChange={(e) => updateParameter(paramName, {
                                ...schema,
                                default: schema.param_type === 'integer' ? parseInt(e.target.value) || 0 : parseFloat(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"
                              placeholder="设置默认值"
                            />
                          ) : schema.param_type === 'image' || schema.param_type === 'audio' || schema.param_type === 'video' ? (
                            <div className="space-y-2">
                              <input
                                type="text"
                                value={schema.default || ''}
                                onChange={(e) => updateParameter(paramName, {
                                  ...schema,
                                  default: 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-transparent"
                                placeholder="默认文件名或路径"
                              />
                              <p className="text-xs text-gray-500">
                                支持格式: {schema.accept || '所有格式'}
                              </p>
                            </div>
                          ) : (
                            <input
                              type="text"
                              value={schema.default || ''}
                              onChange={(e) => updateParameter(paramName, {
                                ...schema,
                                default: 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-transparent"
                              placeholder="设置默认值"
                            />
                          )}
                        </div>

                        <div className="md:col-span-2">
                          <label className="block text-sm font-medium text-gray-700 mb-1">
                            描述
                          </label>
                          <input
                            type="text"
                            value={schema.description || ''}
                            onChange={(e) => updateParameter(paramName, {
                              ...schema,
                              description: 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-transparent"
                            placeholder="参数描述"
                          />
                        </div>

                        <div className="flex items-center space-x-4">
                          <label className="flex items-center space-x-2">
                            <input
                              type="checkbox"
                              checked={schema.required || false}
                              onChange={(e) => updateParameter(paramName, {
                                ...schema,
                                required: e.target.checked
                              })}
                              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                            />
                            <span className="text-sm text-gray-700">必填参数</span>
                          </label>
                        </div>

                        {(schema.param_type === 'number' || schema.param_type === 'integer' || schema.param_type === 'float') && (
                          <div className="grid grid-cols-3 gap-2">
                            <div>
                              <label className="block text-sm font-medium text-gray-700 mb-1">
                                最小值
                              </label>
                              <input
                                type="number"
                                step={schema.param_type === 'float' ? 0.01 : 1}
                                value={schema.min !== undefined ? schema.min : ''}
                                onChange={(e) => updateParameter(paramName, {
                                  ...schema,
                                  min: e.target.value ? Number(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"
                                step={schema.param_type === 'float' ? 0.01 : 1}
                                value={schema.max !== undefined ? schema.max : ''}
                                onChange={(e) => updateParameter(paramName, {
                                  ...schema,
                                  max: e.target.value ? Number(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"
                                step={schema.param_type === 'float' ? 0.001 : 1}
                                value={schema.step !== undefined ? schema.step : ''}
                                onChange={(e) => updateParameter(paramName, {
                                  ...schema,
                                  step: e.target.value ? Number(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={schema.param_type === 'float' ? '0.01' : '1'}
                              />
                            </div>
                          </div>
                        )}

                        {(schema.param_type === 'image' || schema.param_type === 'audio' || schema.param_type === 'video') && (
                          <div className="md:col-span-2 space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                              <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                  支持的文件格式
                                </label>
                                <input
                                  type="text"
                                  value={schema.accept || ''}
                                  onChange={(e) => updateParameter(paramName, {
                                    ...schema,
                                    accept: 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-transparent"
                                  placeholder=".jpg,.png,.webp"
                                />
                              </div>
                              <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                  最大文件大小 (MB)
                                </label>
                                <input
                                  type="number"
                                  value={schema.maxSize !== undefined ? Math.round(schema.maxSize / (1024 * 1024)) : ''}
                                  onChange={(e) => updateParameter(paramName, {
                                    ...schema,
                                    maxSize: e.target.value ? Number(e.target.value) * 1024 * 1024 : 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="10"
                                />
                              </div>
                            </div>

                            {(schema.param_type === 'image' || schema.param_type === 'video') && (
                              <div className="grid grid-cols-2 gap-4">
                                <div>
                                  <label className="block text-sm font-medium text-gray-700 mb-1">
                                    推荐宽度 (px)
                                  </label>
                                  <input
                                    type="number"
                                    value={schema.width !== undefined ? schema.width : ''}
                                    onChange={(e) => updateParameter(paramName, {
                                      ...schema,
                                      width: e.target.value ? Number(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="1920"
                                  />
                                </div>
                                <div>
                                  <label className="block text-sm font-medium text-gray-700 mb-1">
                                    推荐高度 (px)
                                  </label>
                                  <input
                                    type="number"
                                    value={schema.height !== undefined ? schema.height : ''}
                                    onChange={(e) => updateParameter(paramName, {
                                      ...schema,
                                      height: e.target.value ? Number(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="1080"
                                  />
                                </div>
                              </div>
                            )}

                            {(schema.param_type === 'audio' || schema.param_type === 'video') && (
                              <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                  最大时长 (秒)
                                </label>
                                <input
                                  type="number"
                                  value={schema.duration !== undefined ? schema.duration : ''}
                                  onChange={(e) => updateParameter(paramName, {
                                    ...schema,
                                    duration: e.target.value ? Number(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="300"
                                />
                              </div>
                            )}
                          </div>
                        )}

                        {schema.param_type === 'string' && (
                          <div className="md:col-span-2">
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                              正则表达式验证
                            </label>
                            <input
                              type="text"
                              value={schema.pattern || ''}
                              onChange={(e) => updateParameter(paramName, {
                                ...schema,
                                pattern: 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="例如：^[a-zA-Z0-9]+$"
                            />
                            </div>
                          )}

                        {/* 节点关联配置 */}
                        <div className="md:col-span-2">
                          <div className="border border-gray-200 rounded-lg p-4 bg-gray-50">
                            <div className="flex items-center justify-between mb-3">
                              <div className="flex items-center space-x-2">
                                <Link className="w-4 h-4 text-blue-600" />
                                <span className="text-sm font-medium text-gray-700">工作流节点关联</span>
                              </div>
                              {schema.node_mapping && (
                                <button
                                  onClick={() => updateParameterNodeMapping(paramName, undefined)}
                                  className="text-red-600 hover:text-red-700 text-sm"
                                >
                                  清除关联
                                </button>
                              )}
                            </div>

                            {schema.node_mapping ? (
                              <div className="space-y-3">
                                <div className="flex items-center space-x-2 text-sm text-green-700 bg-green-50 p-2 rounded">
                                  <span>已关联节点:</span>
                                  <code className="bg-green-100 px-1 rounded">
                                    {schema.node_mapping.node_id}
                                  </code>
                                  <span>→</span>
                                  <code className="bg-green-100 px-1 rounded">
                                    {schema.node_mapping.input_field}
                                  </code>
                                </div>
                                <button
                                  onClick={() => setShowNodeSelector(paramName)}
                                  className="text-blue-600 hover:text-blue-700 text-sm"
                                >
                                  重新选择节点
                                </button>
                              </div>
                            ) : (
                              <div className="text-center py-4">
                                <p className="text-sm text-gray-500 mb-2">
                                  将此参数关联到工作流中的节点输入字段
                                </p>
                                <button
                                  onClick={() => setShowNodeSelector(paramName)}
                                  disabled={availableNodes.length === 0}
                                  className="px-3 py-1 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                                >
                                  {availableNodes.length === 0 ? '请先配置工作流' : '选择节点'}
                                </button>
                              </div>
                            )}
                          </div>
                        </div>
                            </div>
                          </div>
                        )}
                      </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>保存后将创建符合ComfyUI SDK规范的模板</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}
              disabled={isSaving}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2 disabled:opacity-50"
            >
              {isSaving ? (
                <Settings className="w-4 h-4 animate-spin" />
              ) : (
                <Save className="w-4 h-4" />
              )}
              <span>{isSaving ? '保存中...' : (editingTemplate ? '更新' : '创建')}</span>
            </button>
          </div>
        </div>
      </div>

      {/* 节点选择器模态框 */}
      {showNodeSelector && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-60">
          <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[80vh] flex flex-col m-4">
            <div className="flex items-center justify-between p-4 border-b border-gray-200">
              <h3 className="text-lg font-semibold text-gray-900">选择工作流节点</h3>
              <button
                onClick={() => setShowNodeSelector(null)}
                className="p-2 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="flex-1 overflow-y-auto p-4">
              {availableNodes.length === 0 ? (
                <div className="text-center py-8 text-gray-500">
                  <Settings className="w-12 h-12 mx-auto mb-3 text-gray-400" />
                  <p>没有找到可用的节点</p>
                  <p className="text-sm">请确保工作流JSON格式正确</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {availableNodes.map((node) => (
                    <div key={node.id} className="border border-gray-200 rounded-lg p-4 hover:bg-gray-50">
                      <div className="flex items-center justify-between mb-2">
                        <div>
                          <h4 className="font-medium text-gray-900">
                            {node.id}
                            {node.title && (
                              <span className="ml-2 text-sm text-gray-600">({node.title})</span>
                            )}
                          </h4>
                          <p className="text-sm text-gray-500">{node.class_type}</p>
                        </div>
                      </div>

                      {Object.keys(node.inputs).length > 0 && (
                        <div className="mt-3">
                          <p className="text-sm font-medium text-gray-700 mb-2">可用输入字段:</p>
                          <div className="grid grid-cols-2 gap-2">
                            {Object.entries(node.inputs).map(([inputField, inputValue]) => (
                              <button
                                key={inputField}
                                onClick={() => {
                                  updateParameterNodeMapping(showNodeSelector, {
                                    node_id: node.id,
                                    input_field: inputField
                                  });
                                  setShowNodeSelector(null);
                                }}
                                className="text-left p-2 border border-gray-200 rounded hover:bg-blue-50 hover:border-blue-300 transition-colors"
                              >
                                <div className="font-medium text-sm text-gray-900">{inputField}</div>
                                <div className="text-xs text-gray-500 truncate">
                                  当前值: {typeof inputValue === 'string' ? inputValue : JSON.stringify(inputValue)}
                                </div>
                              </button>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
