/**
 * 工作流创建器组件
 * 
 * 提供可视化的工作流创建和编辑界面，支持JSON配置和UI设计
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState, useEffect } from 'react';
import {
  X,
  Save,
  Eye,
  Code,
  Settings,
  Plus,
  Trash2,
  Copy,
  Upload,
  Download,
  TestTube,
  AlertCircle,
  CheckCircle,
  Info,
  Layers,
  Edit3,
  FileText
} from 'lucide-react';
import { UIFieldEditor } from './UIFieldEditor';
import { WorkflowPreview } from './WorkflowPreview';

// 工作流类型枚举
type WorkflowType = 'outfit_generation' | 'background_replacement' | 'portrait_enhancement' | 'image_upscaling' | 'style_transfer' | 'custom';

// UI字段类型枚举
type UIFieldType = 'text' | 'textarea' | 'number' | 'select' | 'checkbox' | 'image_upload' | 'file_upload' | 'slider' | 'color' | 'date';

// UI字段配置接口
interface UIField {
  name: string;
  type: UIFieldType;
  label: string;
  description?: string;
  required?: boolean;
  default_value?: any;
  validation?: {
    min?: number;
    max?: number;
    pattern?: string;
    options?: string[];
  };
  ui_config?: {
    placeholder?: string;
    help_text?: string;
    group?: string;
    order?: number;
    width?: 'full' | 'half' | 'third';
  };
}

// 工作流模板接口
interface WorkflowTemplate {
  id?: number;
  name: string;
  base_name: string;
  version: string;
  type: WorkflowType;
  description?: string;
  comfyui_workflow_json: any;
  ui_config_json: {
    form_fields: UIField[];
    layout?: any;
    theme?: string;
  };
  execution_config_json?: any;
  input_schema_json?: any;
  output_schema_json?: any;
  is_active: boolean;
  is_published: boolean;
  tags?: string[];
  category?: string;
  author?: string;
}

// 创建工作流请求接口
interface CreateWorkflowTemplateRequest {
  name: string;
  base_name: string;
  version: string;
  type: WorkflowType;
  description?: string;
  comfyui_workflow_json: any;
  ui_config_json: any;
  execution_config_json?: any;
  input_schema_json?: any;
  output_schema_json?: any;
  tags?: string[];
  category?: string;
  author?: string;
}

// 组件属性接口
interface WorkflowCreatorProps {
  /** 是否显示模态框 */
  isOpen: boolean;
  /** 关闭回调 */
  onClose: () => void;
  /** 保存回调 */
  onSave: (template: CreateWorkflowTemplateRequest) => void;
  /** 编辑的模板（为空时表示创建新模板） */
  editingTemplate?: WorkflowTemplate;
}

/**
 * 工作流创建器组件
 */
export const WorkflowCreator: React.FC<WorkflowCreatorProps> = ({
  isOpen,
  onClose,
  onSave,
  editingTemplate
}) => {
  const [activeTab, setActiveTab] = useState<'basic' | 'ui' | 'comfyui' | 'advanced'>('basic');
  const [formData, setFormData] = useState<CreateWorkflowTemplateRequest>({
    name: '',
    base_name: '',
    version: '1.0',
    type: 'custom',
    description: '',
    comfyui_workflow_json: {},
    ui_config_json: {
      form_fields: []
    },
    execution_config_json: {},
    tags: [],
    category: '',
    author: ''
  });

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isPreviewMode, setIsPreviewMode] = useState(false);
  const [isTesting, setIsTesting] = useState(false);

  // 工作流类型配置
  const workflowTypeConfigs = {
    outfit_generation: { label: '穿搭生成', description: '生成时尚穿搭搭配' },
    background_replacement: { label: '背景替换', description: '替换图片背景' },
    portrait_enhancement: { label: '人像美化', description: '人像照片美化处理' },
    image_upscaling: { label: '图片放大', description: '提升图片分辨率' },
    style_transfer: { label: '风格转换', description: '图片风格迁移' },
    custom: { label: '自定义', description: '自定义工作流类型' }
  };

  // UI字段类型配置
  const fieldTypeConfigs = {
    text: { label: '文本输入', icon: Edit3, description: '单行文本输入框' },
    textarea: { label: '多行文本', icon: FileText, description: '多行文本输入框' },
    number: { label: '数字输入', icon: Settings, description: '数字输入框' },
    select: { label: '下拉选择', icon: Layers, description: '下拉选择框' },
    checkbox: { label: '复选框', icon: CheckCircle, description: '复选框' },
    image_upload: { label: '图片上传', icon: Upload, description: '图片文件上传' },
    file_upload: { label: '文件上传', icon: Upload, description: '通用文件上传' },
    slider: { label: '滑块', icon: Settings, description: '数值滑块' },
    color: { label: '颜色选择', icon: Settings, description: '颜色选择器' },
    date: { label: '日期选择', icon: Settings, description: '日期选择器' }
  };

  // 初始化表单数据
  useEffect(() => {
    if (editingTemplate) {
      setFormData({
        name: editingTemplate.name,
        base_name: editingTemplate.base_name,
        version: editingTemplate.version,
        type: editingTemplate.type,
        description: editingTemplate.description || '',
        comfyui_workflow_json: editingTemplate.comfyui_workflow_json,
        ui_config_json: editingTemplate.ui_config_json,
        execution_config_json: editingTemplate.execution_config_json || {},
        input_schema_json: editingTemplate.input_schema_json,
        output_schema_json: editingTemplate.output_schema_json,
        tags: editingTemplate.tags || [],
        category: editingTemplate.category || '',
        author: editingTemplate.author || ''
      });
    } else {
      // 重置为默认值
      setFormData({
        name: '',
        base_name: '',
        version: '1.0',
        type: 'custom',
        description: '',
        comfyui_workflow_json: {},
        ui_config_json: {
          form_fields: []
        },
        execution_config_json: {},
        tags: [],
        category: '',
        author: ''
      });
    }
    setErrors({});
    setActiveTab('basic');
    setIsPreviewMode(false);
  }, [editingTemplate, isOpen]);

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

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

  // 处理名称变化
  const handleNameChange = (name: string) => {
    updateField('name', name);
    if (!editingTemplate) {
      // 只在创建新模板时自动生成base_name
      updateField('base_name', generateBaseName(name));
    }
  };

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

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

    if (!formData.base_name.trim()) {
      newErrors.base_name = '基础名称不能为空';
    } else if (!/^[a-z0-9_]+$/.test(formData.base_name)) {
      newErrors.base_name = '基础名称只能包含小写字母、数字和下划线';
    }

    if (!formData.version.trim()) {
      newErrors.version = '版本号不能为空';
    }

    if (Object.keys(formData.comfyui_workflow_json).length === 0) {
      newErrors.comfyui_workflow_json = 'ComfyUI工作流配置不能为空';
    }

    if (formData.ui_config_json.form_fields.length === 0) {
      newErrors.ui_config = '至少需要配置一个UI字段';
    }

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

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

    onSave(formData);
  };

  // 处理测试
  const handleTest = async () => {
    if (!validateForm()) return;

    setIsTesting(true);
    try {
      // TODO: 实现工作流测试逻辑
      await new Promise(resolve => setTimeout(resolve, 2000)); // 模拟测试
      console.log('工作流测试成功');
    } catch (error) {
      console.error('工作流测试失败:', error);
    } finally {
      setIsTesting(false);
    }
  };

  // 导入ComfyUI工作流
  const handleImportComfyUI = () => {
    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);
            updateField('comfyui_workflow_json', workflow);
          } catch (error) {
            console.error('解析ComfyUI工作流失败:', error);
          }
        };
        reader.readAsText(file);
      }
    };
    input.click();
  };

  // 导出工作流配置
  const handleExportConfig = () => {
    const config = {
      ...formData,
      exported_at: new Date().toISOString(),
      version_info: {
        creator_version: '1.0.0',
        format_version: '1.0'
      }
    };

    const blob = new Blob([JSON.stringify(config, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${formData.base_name || 'workflow'}_v${formData.version}.json`;
    a.click();
    URL.revokeObjectURL(url);
  };

  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-6xl 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>
          
          <div className="flex items-center space-x-2">
            <button
              onClick={() => setIsPreviewMode(!isPreviewMode)}
              className={`px-3 py-1 rounded transition-colors flex items-center space-x-1 ${
                isPreviewMode 
                  ? 'bg-blue-100 text-blue-700' 
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              <Eye className="w-4 h-4" />
              <span>{isPreviewMode ? '编辑模式' : '预览模式'}</span>
            </button>

            <button
              onClick={handleTest}
              disabled={isTesting}
              className="px-3 py-1 bg-green-100 text-green-700 rounded hover:bg-green-200 transition-colors flex items-center space-x-1 disabled:opacity-50"
            >
              {isTesting ? (
                <Settings className="w-4 h-4 animate-spin" />
              ) : (
                <TestTube className="w-4 h-4" />
              )}
              <span>{isTesting ? '测试中...' : '测试'}</span>
            </button>

            <button
              onClick={handleExportConfig}
              className="px-3 py-1 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors flex items-center space-x-1"
            >
              <Download className="w-4 h-4" />
              <span>导出</span>
            </button>
            
            <button
              onClick={onClose}
              className="p-2 text-gray-400 hover:text-gray-600 transition-colors"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* 标签导航 */}
        <div className="border-b border-gray-200">
          <nav className="flex space-x-8 px-6">
            {[
              { id: 'basic', label: '基本信息', icon: Info },
              { id: 'ui', label: 'UI配置', icon: Layers },
              { id: 'comfyui', label: 'ComfyUI', icon: Code },
              { id: 'advanced', label: '高级设置', icon: Settings }
            ].map(({ id, label, icon: Icon }) => (
              <button
                key={id}
                onClick={() => setActiveTab(id as any)}
                className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors flex items-center space-x-2 ${
                  activeTab === id
                    ? 'border-blue-500 text-blue-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
              >
                <Icon className="w-4 h-4" />
                <span>{label}</span>
              </button>
            ))}
          </nav>
        </div>

        {/* 内容区域 */}
        <div className="flex-1 overflow-hidden flex">
          {/* 主要内容 */}
          <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={formData.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="例如：高级穿搭生成器"
                    />
                    {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>
                    <input
                      type="text"
                      value={formData.base_name}
                      onChange={(e) => updateField('base_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.base_name ? 'border-red-300' : 'border-gray-300'
                      }`}
                      placeholder="例如：advanced_outfit_generator"
                    />
                    {errors.base_name && (
                      <p className="mt-1 text-sm text-red-600">{errors.base_name}</p>
                    )}
                    <p className="mt-1 text-xs text-gray-500">
                      用于API调用的唯一标识符，只能包含小写字母、数字和下划线
                    </p>
                  </div>

                  <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.version}
                      onChange={(e) => updateField('version', e.target.value)}
                      className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                        errors.version ? 'border-red-300' : 'border-gray-300'
                      }`}
                      placeholder="例如：1.0"
                    />
                    {errors.version && (
                      <p className="mt-1 text-sm text-red-600">{errors.version}</p>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      工作流类型 <span className="text-red-500">*</span>
                    </label>
                    <select
                      value={formData.type}
                      onChange={(e) => updateField('type', e.target.value as WorkflowType)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    >
                      {Object.entries(workflowTypeConfigs).map(([type, config]) => (
                        <option key={type} value={type}>
                          {config.label} - {config.description}
                        </option>
                      ))}
                    </select>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      分类
                    </label>
                    <input
                      type="text"
                      value={formData.category}
                      onChange={(e) => updateField('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="例如：图像处理"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      作者
                    </label>
                    <input
                      type="text"
                      value={formData.author}
                      onChange={(e) => updateField('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="例如：张三"
                    />
                  </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={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>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    标签
                  </label>
                  <div className="flex flex-wrap gap-2 mb-2">
                    {formData.tags?.map((tag, index) => (
                      <span
                        key={index}
                        className="px-2 py-1 bg-blue-100 text-blue-800 text-sm rounded-full flex items-center space-x-1"
                      >
                        <span>{tag}</span>
                        <button
                          onClick={() => {
                            const newTags = formData.tags?.filter((_, i) => i !== index) || [];
                            updateField('tags', newTags);
                          }}
                          className="text-blue-600 hover:text-blue-800"
                        >
                          <X className="w-3 h-3" />
                        </button>
                      </span>
                    ))}
                  </div>
                  <div className="flex space-x-2">
                    <input
                      type="text"
                      placeholder="添加标签..."
                      className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      onKeyPress={(e) => {
                        if (e.key === 'Enter') {
                          const input = e.target as HTMLInputElement;
                          const tag = input.value.trim();
                          if (tag && !formData.tags?.includes(tag)) {
                            updateField('tags', [...(formData.tags || []), tag]);
                            input.value = '';
                          }
                        }
                      }}
                    />
                    <button
                      onClick={() => {
                        const input = document.querySelector('input[placeholder="添加标签..."]') as HTMLInputElement;
                        const tag = input?.value.trim();
                        if (tag && !formData.tags?.includes(tag)) {
                          updateField('tags', [...(formData.tags || []), tag]);
                          input.value = '';
                        }
                      }}
                      className="px-3 py-2 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition-colors"
                    >
                      <Plus className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              </div>
            )}

            {/* UI配置标签页 */}
            {activeTab === 'ui' && (
              <div className="space-y-6">
                <div className="flex items-center justify-between">
                  <h3 className="text-lg font-medium text-gray-900">UI字段配置</h3>
                  <div className="text-sm text-gray-500">
                    配置用户界面的输入字段
                  </div>
                </div>

                <UIFieldEditor
                  fields={formData.ui_config_json.form_fields}
                  onFieldsChange={(fields) => updateField('ui_config_json', {
                    ...formData.ui_config_json,
                    form_fields: fields
                  })}
                  workflowJson={formData.comfyui_workflow_json}
                />

                {errors.ui_config && (
                  <div className="bg-red-50 border border-red-200 rounded-lg p-3">
                    <div className="flex items-center space-x-2">
                      <AlertCircle className="w-4 h-4 text-red-500" />
                      <span className="text-sm text-red-700">{errors.ui_config}</span>
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* ComfyUI配置标签页 */}
            {activeTab === 'comfyui' && (
              <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={handleImportComfyUI}
                    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">
                    ComfyUI工作流JSON <span className="text-red-500">*</span>
                  </label>
                  <textarea
                    value={JSON.stringify(formData.comfyui_workflow_json, null, 2)}
                    onChange={(e) => {
                      try {
                        const parsed = JSON.parse(e.target.value);
                        updateField('comfyui_workflow_json', parsed);
                      } catch (error) {
                        // 保持原始文本，让用户继续编辑
                      }
                    }}
                    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.comfyui_workflow_json ? 'border-red-300' : 'border-gray-300'
                    }`}
                    placeholder="粘贴ComfyUI导出的工作流JSON..."
                  />
                  {errors.comfyui_workflow_json && (
                    <p className="mt-1 text-sm text-red-600">{errors.comfyui_workflow_json}</p>
                  )}
                  <p className="mt-1 text-xs text-gray-500">
                    从ComfyUI界面导出工作流JSON并粘贴到此处
                  </p>
                </div>

                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <h4 className="text-sm font-medium text-blue-900 mb-2">如何获取ComfyUI工作流JSON？</h4>
                  <ol className="text-sm text-blue-700 space-y-1 list-decimal list-inside">
                    <li>在ComfyUI界面中设计好你的工作流</li>
                    <li>点击"Save"按钮保存工作流</li>
                    <li>点击"Export"按钮导出JSON文件</li>
                    <li>打开JSON文件并复制内容到上方文本框</li>
                  </ol>
                </div>
              </div>
            )}

            {/* 高级设置标签页 */}
            {activeTab === 'advanced' && (
              <div className="space-y-6">
                <h3 className="text-lg font-medium text-gray-900">高级设置</h3>

                {/* 执行配置 */}
                <div>
                  <h4 className="text-sm font-medium text-gray-900 mb-3">执行配置</h4>
                  <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>
                      <input
                        type="number"
                        min="0"
                        value={formData.execution_config_json?.timeout_seconds || ''}
                        onChange={(e) => updateField('execution_config_json', {
                          ...formData.execution_config_json,
                          timeout_seconds: 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="600"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        最大内存 (MB)
                      </label>
                      <input
                        type="number"
                        min="0"
                        value={formData.execution_config_json?.max_memory_mb || ''}
                        onChange={(e) => updateField('execution_config_json', {
                          ...formData.execution_config_json,
                          max_memory_mb: 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="4096"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        优先级
                      </label>
                      <select
                        value={formData.execution_config_json?.priority || 'normal'}
                        onChange={(e) => updateField('execution_config_json', {
                          ...formData.execution_config_json,
                          priority: 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"
                      >
                        <option value="low">低</option>
                        <option value="normal">普通</option>
                        <option value="high">高</option>
                        <option value="urgent">紧急</option>
                      </select>
                    </div>

                    <div>
                      <label className="flex items-center space-x-2">
                        <input
                          type="checkbox"
                          checked={formData.execution_config_json?.auto_retry || false}
                          onChange={(e) => updateField('execution_config_json', {
                            ...formData.execution_config_json,
                            auto_retry: 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>
                  </div>
                </div>

                {/* 输入输出Schema */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      输入数据Schema (JSON)
                    </label>
                    <textarea
                      value={JSON.stringify(formData.input_schema_json || {}, null, 2)}
                      onChange={(e) => {
                        try {
                          const parsed = JSON.parse(e.target.value);
                          updateField('input_schema_json', parsed);
                        } catch (error) {
                          // 保持原始文本
                        }
                      }}
                      rows={8}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent font-mono text-sm"
                      placeholder='{"type": "object", "properties": {...}}'
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      输出数据Schema (JSON)
                    </label>
                    <textarea
                      value={JSON.stringify(formData.output_schema_json || {}, null, 2)}
                      onChange={(e) => {
                        try {
                          const parsed = JSON.parse(e.target.value);
                          updateField('output_schema_json', parsed);
                        } catch (error) {
                          // 保持原始文本
                        }
                      }}
                      rows={8}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent font-mono text-sm"
                      placeholder='{"type": "object", "properties": {...}}'
                    />
                  </div>
                </div>

                <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                  <div className="flex items-start space-x-2">
                    <Info className="w-5 h-5 text-yellow-600 mt-0.5" />
                    <div>
                      <h4 className="text-sm font-medium text-yellow-800">关于Schema配置</h4>
                      <p className="text-sm text-yellow-700 mt-1">
                        Schema用于验证输入输出数据格式。如果不配置，系统将根据UI字段自动生成基础Schema。
                        高级用户可以手动配置更详细的验证规则。
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* 预览面板 */}
          {isPreviewMode && (
            <div className="w-1/3 border-l border-gray-200 bg-gray-50 overflow-y-auto">
              <div className="p-4">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-sm font-medium text-gray-900">实时预览</h3>
                  <div className="flex items-center space-x-2">
                    <button
                      onClick={() => {/* TODO: 切换预览模式 */}}
                      className="text-xs text-gray-500 hover:text-gray-700"
                    >
                      桌面端
                    </button>
                  </div>
                </div>

                <WorkflowPreview
                  workflowName={formData.name || '未命名工作流'}
                  description={formData.description}
                  fields={formData.ui_config_json.form_fields}
                  mode="desktop"
                />
              </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>{editingTemplate ? '更新' : '创建'}</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};
