/**
 * UI字段编辑器组件
 * 
 * 用于可视化编辑工作流的UI字段配置
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState } from 'react';
import { 
  Plus, 
  Trash2, 
  Edit3, 
  Move, 
  Settings, 
  Eye,
  FileText,
  Layers,
  CheckCircle,
  Upload,
  Sliders,
  Palette,
  Calendar,
  ChevronDown,
  ChevronRight,
  Copy,
  ArrowUp,
  ArrowDown
} from 'lucide-react';
import { NodeMappingEditor } from './NodeMappingEditor';
import { NodeMapping } from '../../types/workflow';

// 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;
    step?: number;
    pattern?: string;
    options?: string[];
  };
  ui_config?: {
    placeholder?: string;
    help_text?: string;
    group?: string;
    order?: number;
    width?: 'full' | 'half' | 'third';
  };
  node_mapping?: NodeMapping;
}

// 组件属性接口
interface UIFieldEditorProps {
  /** UI字段列表 */
  fields: UIField[];
  /** 字段变化回调 */
  onFieldsChange: (fields: UIField[]) => void;
  /** ComfyUI工作流JSON，用于节点映射配置 */
  workflowJson?: any;
  /** 是否只读 */
  readonly?: boolean;
}

/**
 * UI字段编辑器组件
 */
export const UIFieldEditor: React.FC<UIFieldEditorProps> = ({
  fields,
  onFieldsChange,
  workflowJson,
  readonly = false
}) => {
  const [selectedFieldIndex, setSelectedFieldIndex] = useState<number | null>(null);
  const [expandedFields, setExpandedFields] = useState<Set<number>>(new Set());

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

  // 添加新字段
  const addField = (type: UIFieldType) => {
    const newField: UIField = {
      name: `field_${Date.now()}`,
      type,
      label: `新${fieldTypeConfigs[type].label}`,
      required: false,
      ui_config: {
        width: 'full',
        order: fields.length
      }
    };

    if (type === 'select') {
      newField.validation = { options: ['选项1', '选项2', '选项3'] };
    } else if (type === 'number' || type === 'slider') {
      newField.validation = { min: 0, max: 1, step: 0.01 };
    }

    const newFields = [...fields, newField];
    onFieldsChange(newFields);
    setSelectedFieldIndex(newFields.length - 1);
  };

  // 删除字段
  const deleteField = (index: number) => {
    const newFields = fields.filter((_, i) => i !== index);
    onFieldsChange(newFields);
    if (selectedFieldIndex === index) {
      setSelectedFieldIndex(null);
    } else if (selectedFieldIndex !== null && selectedFieldIndex > index) {
      setSelectedFieldIndex(selectedFieldIndex - 1);
    }
  };

  // 复制字段
  const duplicateField = (index: number) => {
    const field = fields[index];
    const newField = {
      ...field,
      name: `${field.name}_copy_${Date.now()}`,
      label: `${field.label} (副本)`
    };
    const newFields = [...fields];
    newFields.splice(index + 1, 0, newField);
    onFieldsChange(newFields);
  };

  // 移动字段
  const moveField = (index: number, direction: 'up' | 'down') => {
    const newFields = [...fields];
    const targetIndex = direction === 'up' ? index - 1 : index + 1;
    
    if (targetIndex >= 0 && targetIndex < newFields.length) {
      [newFields[index], newFields[targetIndex]] = [newFields[targetIndex], newFields[index]];
      onFieldsChange(newFields);
      setSelectedFieldIndex(targetIndex);
    }
  };

  // 更新字段
  const updateField = (index: number, updates: Partial<UIField>) => {
    const newFields = [...fields];
    newFields[index] = { ...newFields[index], ...updates };
    onFieldsChange(newFields);
  };

  // 切换字段展开状态
  const toggleFieldExpanded = (index: number) => {
    const newExpanded = new Set(expandedFields);
    if (newExpanded.has(index)) {
      newExpanded.delete(index);
    } else {
      newExpanded.add(index);
    }
    setExpandedFields(newExpanded);
  };

  return (
    <div className="space-y-6">
      {/* 字段类型选择器 */}
      {!readonly && (
        <div>
          <h3 className="text-sm font-medium text-gray-900 mb-3">添加字段</h3>
          <div className="grid grid-cols-2 md:grid-cols-5 gap-2">
            {Object.entries(fieldTypeConfigs).map(([type, config]) => {
              const Icon = config.icon;
              return (
                <button
                  key={type}
                  onClick={() => addField(type as UIFieldType)}
                  className="p-3 border border-gray-200 rounded-lg hover:border-blue-300 hover:bg-blue-50 transition-all text-left"
                  title={config.description}
                >
                  <div className="flex items-center space-x-2">
                    <Icon className={`w-4 h-4 ${config.color}`} />
                    <span className="text-xs font-medium text-gray-700">{config.label}</span>
                  </div>
                </button>
              );
            })}
          </div>
        </div>
      )}

      {/* 字段列表 */}
      <div>
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-sm font-medium text-gray-900">
            字段配置 ({fields.length})
          </h3>
          {fields.length > 0 && (
            <div className="text-xs text-gray-500">
              点击字段展开详细配置
            </div>
          )}
        </div>

        {fields.length === 0 ? (
          <div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center">
            <Layers className="w-8 h-8 text-gray-400 mx-auto mb-2" />
            <p className="text-sm text-gray-600 mb-2">还没有配置任何UI字段</p>
            <p className="text-xs text-gray-500">
              点击上方的字段类型来添加第一个字段
            </p>
          </div>
        ) : (
          <div className="space-y-2">
            {fields.map((field, index) => {
              const config = fieldTypeConfigs[field.type];
              const Icon = config.icon;
              const isExpanded = expandedFields.has(index);
              const isSelected = selectedFieldIndex === index;

              return (
                <div
                  key={index}
                  className={`border rounded-lg transition-all ${
                    isSelected 
                      ? 'border-blue-500 bg-blue-50' 
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                >
                  {/* 字段头部 */}
                  <div className="p-3">
                    <div className="flex items-center justify-between">
                      <div 
                        className="flex items-center space-x-3 flex-1 cursor-pointer"
                        onClick={() => {
                          setSelectedFieldIndex(isSelected ? null : index);
                          if (!isSelected) {
                            toggleFieldExpanded(index);
                          }
                        }}
                      >
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            toggleFieldExpanded(index);
                          }}
                          className="text-gray-400 hover:text-gray-600"
                        >
                          {isExpanded ? (
                            <ChevronDown className="w-4 h-4" />
                          ) : (
                            <ChevronRight className="w-4 h-4" />
                          )}
                        </button>

                        <Icon className={`w-4 h-4 ${config.color}`} />
                        
                        <div className="flex-1">
                          <div className="flex items-center space-x-2">
                            <span className="text-sm font-medium text-gray-900">
                              {field.label}
                            </span>
                            <span className="text-xs text-gray-500">
                              ({config.label})
                            </span>
                            {field.required && (
                              <span className="text-xs text-red-500">必填</span>
                            )}
                          </div>
                          <div className="text-xs text-gray-500">
                            字段名: {field.name}
                          </div>
                        </div>
                      </div>

                      {!readonly && (
                        <div className="flex items-center space-x-1">
                          <button
                            onClick={() => moveField(index, 'up')}
                            disabled={index === 0}
                            className="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-50"
                            title="上移"
                          >
                            <ArrowUp className="w-3 h-3" />
                          </button>
                          
                          <button
                            onClick={() => moveField(index, 'down')}
                            disabled={index === fields.length - 1}
                            className="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-50"
                            title="下移"
                          >
                            <ArrowDown className="w-3 h-3" />
                          </button>

                          <button
                            onClick={() => duplicateField(index)}
                            className="p-1 text-gray-400 hover:text-blue-600"
                            title="复制"
                          >
                            <Copy className="w-3 h-3" />
                          </button>

                          <button
                            onClick={() => deleteField(index)}
                            className="p-1 text-gray-400 hover:text-red-600"
                            title="删除"
                          >
                            <Trash2 className="w-3 h-3" />
                          </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-xs font-medium text-gray-700 mb-1">
                            字段名称
                          </label>
                          <input
                            type="text"
                            value={field.name}
                            onChange={(e) => updateField(index, { name: e.target.value })}
                            className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-transparent"
                            disabled={readonly}
                          />
                        </div>

                        <div>
                          <label className="block text-xs font-medium text-gray-700 mb-1">
                            显示标签
                          </label>
                          <input
                            type="text"
                            value={field.label}
                            onChange={(e) => updateField(index, { label: e.target.value })}
                            className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-transparent"
                            disabled={readonly}
                          />
                        </div>

                        <div className="md:col-span-2">
                          <label className="block text-xs font-medium text-gray-700 mb-1">
                            描述
                          </label>
                          <input
                            type="text"
                            value={field.description || ''}
                            onChange={(e) => updateField(index, { description: e.target.value })}
                            className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-transparent"
                            placeholder="字段的详细说明..."
                            disabled={readonly}
                          />
                        </div>

                        <div>
                          <label className="flex items-center space-x-2">
                            <input
                              type="checkbox"
                              checked={field.required || false}
                              onChange={(e) => updateField(index, { required: e.target.checked })}
                              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                              disabled={readonly}
                            />
                            <span className="text-xs text-gray-700">必填字段</span>
                          </label>
                        </div>

                        <div>
                          <label className="block text-xs font-medium text-gray-700 mb-1">
                            字段宽度
                          </label>
                          <select
                            value={field.ui_config?.width || 'full'}
                            onChange={(e) => updateField(index, { 
                              ui_config: { 
                                ...field.ui_config, 
                                width: e.target.value as 'full' | 'half' | 'third' 
                              } 
                            })}
                            className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-transparent"
                            disabled={readonly}
                          >
                            <option value="full">全宽</option>
                            <option value="half">半宽</option>
                            <option value="third">三分之一</option>
                          </select>
                        </div>

                        {/* 类型特定配置 */}
                        {(field.type === 'text' || field.type === 'textarea') && (
                          <div>
                            <label className="block text-xs font-medium text-gray-700 mb-1">
                              占位符
                            </label>
                            <input
                              type="text"
                              value={field.ui_config?.placeholder || ''}
                              onChange={(e) => updateField(index, { 
                                ui_config: { 
                                  ...field.ui_config, 
                                  placeholder: e.target.value 
                                } 
                              })}
                              className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-transparent"
                              disabled={readonly}
                            />
                          </div>
                        )}

                        {(field.type === 'number' || field.type === 'slider') && (
                          <>
                            <div>
                              <label className="block text-xs font-medium text-gray-700 mb-1">
                                最小值
                              </label>
                              <input
                                type="number"
                                step="any"
                                value={field.validation?.min !== undefined ? field.validation.min : ''}
                                onChange={(e) => updateField(index, {
                                  validation: {
                                    ...field.validation,
                                    min: e.target.value !== '' ? Number(e.target.value) : undefined
                                  }
                                })}
                                className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-transparent"
                                disabled={readonly}
                                placeholder="0"
                              />
                            </div>
                            <div>
                              <label className="block text-xs font-medium text-gray-700 mb-1">
                                最大值
                              </label>
                              <input
                                type="number"
                                step="any"
                                value={field.validation?.max !== undefined ? field.validation.max : ''}
                                onChange={(e) => updateField(index, {
                                  validation: {
                                    ...field.validation,
                                    max: e.target.value !== '' ? Number(e.target.value) : undefined
                                  }
                                })}
                                className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-transparent"
                                disabled={readonly}
                                placeholder="1"
                              />
                            </div>
                            <div>
                              <label className="block text-xs font-medium text-gray-700 mb-1">
                                步长
                              </label>
                              <input
                                type="number"
                                step="any"
                                value={field.validation?.step !== undefined ? field.validation.step : ''}
                                onChange={(e) => updateField(index, {
                                  validation: {
                                    ...field.validation,
                                    step: e.target.value !== '' ? Number(e.target.value) : undefined
                                  }
                                })}
                                className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-transparent"
                                disabled={readonly}
                                placeholder="0.01"
                              />
                            </div>
                          </>
                        )}

                        {field.type === 'select' && (
                          <div className="md:col-span-2">
                            <label className="block text-xs font-medium text-gray-700 mb-1">
                              选项列表 (每行一个)
                            </label>
                            <textarea
                              value={field.validation?.options?.join('\n') || ''}
                              onChange={(e) => updateField(index, { 
                                validation: { 
                                  ...field.validation, 
                                  options: e.target.value.split('\n').filter(opt => opt.trim()) 
                                } 
                              })}
                              rows={3}
                              className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-transparent"
                              placeholder="选项1&#10;选项2&#10;选项3"
                              disabled={readonly}
                            />
                          </div>
                        )}
                      </div>

                      {/* 节点映射配置 */}
                      <div className="md:col-span-2 mt-4">
                        <NodeMappingEditor
                          mapping={field.node_mapping}
                          onMappingChange={(mapping) => updateField(index, { node_mapping: mapping })}
                          workflowJson={workflowJson}
                          fieldName={field.name}
                          fieldType={field.type}
                          readonly={readonly}
                        />
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
};
