/**
 * 自动表单生成组件
 *
 * 功能说明：
 * - 根据 ComfyUI 工作流规范自动生成表单字段
 * - 支持文本输入字段（type: 'value'）和图片上传字段（type: 'image'）
 * - 自动忽略上传类型字段（type: 'upload'）
 * - 提供表单验证和数据收集功能
 * - 集成云端文件上传服务
 *
 * 使用方式：
 * ```tsx
 * <AutoFormGenerator
 *   workflowInputs={workflowInputs}
 *   onFormDataChange={(data) => console.log('表单数据变化:', data)}
 *   onSubmit={(data) => console.log('提交数据:', data)}
 *   disabled={false}
 * />
 * ```
 *
 * 遵循 Tauri 开发规范的组件设计原则
 */

import React, { useState, useCallback, useEffect } from 'react';
import { Upload, Image, FileText, Loader2, CheckCircle, XCircle } from 'lucide-react';
import type { 
  WorkflowInputs, 
  AutoFormField, 
  AutoFormData, 
  FormFieldType,
  FileUploadResult 
} from '../types/comfyui';
import fileUploadService from '../services/fileUploadService';

/**
 * 自动表单生成器属性
 */
interface AutoFormGeneratorProps {
  /** 工作流输入定义 */
  workflowInputs: WorkflowInputs;
  /** 表单数据变化回调 */
  onFormDataChange?: (data: AutoFormData) => void;
  /** 表单提交回调 */
  onSubmit?: (data: AutoFormData) => void;
  /** 是否禁用表单 */
  disabled?: boolean;
  /** 自定义样式类名 */
  className?: string;
}

/**
 * 自动表单生成器组件
 */
export const AutoFormGenerator: React.FC<AutoFormGeneratorProps> = ({
  workflowInputs,
  onFormDataChange,
  onSubmit,
  disabled = false,
  className = '',
}) => {
  const [formFields, setFormFields] = useState<AutoFormField[]>([]);
  const [formData, setFormData] = useState<AutoFormData>({});
  const [uploadStates, setUploadStates] = useState<Record<string, FileUploadResult>>({});
  const [errors, setErrors] = useState<Record<string, string>>({});

  /**
   * 解析工作流输入并生成表单字段
   *
   * 解析规则：
   * 1. 字段名格式：{label}_{type}，如 "模特图_image"、"模特描述_value"
   * 2. 支持的类型：
   *    - 'image': 图片上传字段，可选
   *    - 'value': 文本输入字段，可选
   *    - 'upload': 忽略此类型字段
   * 3. 生成的字段包含：key、label、type、required、node_id、widget_name
   *
   * @param inputs - 工作流输入配置对象
   * @returns 解析后的表单字段数组
   */
  const parseWorkflowInputs = useCallback((inputs: WorkflowInputs): AutoFormField[] => {
    const fields: AutoFormField[] = [];

    Object.entries(inputs).forEach(([key, field]) => {
      // 解析字段名称格式：[label]_[type]
      const parts = key.split('_');
      if (parts.length < 2) return;

      const type = parts[parts.length - 1] as FormFieldType;
      const label = parts.slice(0, -1).join('_');

      // 忽略 upload 类型的字段
      if (type === 'upload') return;

      // 只处理 image 和 value 类型
      if (type === 'image' || type === 'value') {
        fields.push({
          key,
          label,
          type,
          required: type === 'image', // 只有图片字段必填，value 字段都是可选的
          node_id: field.node_id,
          widget_name: field.widget_name,
          value: '',
        });
      }
    });

    return fields;
  }, []);

  /**
   * 初始化表单字段
   */
  useEffect(() => {
    const fields = parseWorkflowInputs(workflowInputs);
    setFormFields(fields);
    
    // 初始化表单数据
    const initialData: AutoFormData = {};
    fields.forEach(field => {
      initialData[field.key] = '';
    });
    setFormData(initialData);
  }, [workflowInputs, parseWorkflowInputs]);

  /**
   * 更新表单数据
   */
  const updateFormData = useCallback((key: string, value: string) => {
    const newData = { ...formData, [key]: value };
    setFormData(newData);
    onFormDataChange?.(newData);

    // 清除该字段的错误
    if (errors[key]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[key];
        return newErrors;
      });
    }
  }, [formData, onFormDataChange, errors]);

  /**
   * 处理文本输入变化
   */
  const handleTextChange = useCallback((key: string, value: string) => {
    updateFormData(key, value);
  }, [updateFormData]);

  /**
   * 处理图片上传
   *
   * 流程：
   * 1. 调用文件选择对话框让用户选择图片
   * 2. 将选中的图片上传到云端存储
   * 3. 获取上传后的 HTTPS URL
   * 4. 更新表单数据和上传状态
   * 5. 提供上传进度反馈和错误处理
   *
   * @param key - 表单字段的键名
   */
  const handleImageUpload = useCallback(async (key: string) => {
    if (disabled) return;

    try {
      // 设置上传状态
      setUploadStates(prev => ({
        ...prev,
        [key]: { status: 'uploading', progress: 0 }
      }));

      // 选择并上传图片
      const result = await fileUploadService.selectAndUploadImage((progress) => {
        setUploadStates(prev => ({
          ...prev,
          [key]: { status: 'uploading', progress }
        }));
      });

      // 更新上传状态
      setUploadStates(prev => ({
        ...prev,
        [key]: result
      }));

      if (result.status === 'success' && result.url) {
        updateFormData(key, result.url);
      } else {
        setErrors(prev => ({
          ...prev,
          [key]: result.error || '上传失败'
        }));
      }
    } catch (error) {
      console.error('图片上传失败:', error);
      setUploadStates(prev => ({
        ...prev,
        [key]: { 
          status: 'error', 
          error: error instanceof Error ? error.message : '上传失败',
          progress: 0
        }
      }));
      setErrors(prev => ({
        ...prev,
        [key]: error instanceof Error ? error.message : '上传失败'
      }));
    }
  }, [disabled, updateFormData]);

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

    formFields.forEach(field => {
      if (field.required && !formData[field.key]) {
        newErrors[field.key] = `${field.label}是必填项`;
      }
    });

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [formFields, formData]);

  /**
   * 处理表单提交
   */
  const handleSubmit = useCallback(() => {
    if (disabled) return;

    if (validateForm()) {
      onSubmit?.(formData);
    }
  }, [disabled, validateForm, onSubmit, formData]);

  /**
   * 渲染文本输入字段
   */
  const renderTextField = (field: AutoFormField) => (
    <div key={field.key} className="space-y-2">
      <label htmlFor={field.key} className="block text-sm font-medium text-gray-700">
        {field.label}
        {field.required && <span className="text-red-500 ml-1">*</span>}
      </label>
      <input
        id={field.key}
        type="text"
        value={formData[field.key] || ''}
        onChange={(e) => handleTextChange(field.key, e.target.value)}
        placeholder={`请输入${field.label}`}
        disabled={disabled}
        className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${
          errors[field.key] ? 'border-red-500' : 'border-gray-300'
        } ${disabled ? 'bg-gray-100 cursor-not-allowed' : ''}`}
      />
      {errors[field.key] && (
        <p className="text-sm text-red-500">{errors[field.key]}</p>
      )}
    </div>
  );

  /**
   * 渲染图片上传字段
   */
  const renderImageField = (field: AutoFormField) => {
    const uploadState = uploadStates[field.key];
    const hasImage = formData[field.key];

    return (
      <div key={field.key} className="space-y-2">
        <label className="block text-sm font-medium text-gray-700">
          {field.label}
          {field.required && <span className="text-red-500 ml-1">*</span>}
        </label>
        <div className="border-2 border-dashed border-gray-300 rounded-lg p-4">
          {!hasImage ? (
            <div className="text-center">
              <div className="flex flex-col items-center space-y-2">
                <Image className="h-8 w-8 text-gray-400" />
                <p className="text-sm text-gray-500">点击上传{field.label}</p>
                <button
                  type="button"
                  onClick={() => handleImageUpload(field.key)}
                  disabled={disabled || uploadState?.status === 'uploading'}
                  className="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {uploadState?.status === 'uploading' ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin inline" />
                      上传中 {uploadState.progress?.toFixed(0)}%
                    </>
                  ) : (
                    <>
                      <Upload className="h-4 w-4 mr-2 inline" />
                      选择图片
                    </>
                  )}
                </button>
              </div>
            </div>
          ) : (
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <CheckCircle className="h-5 w-5 text-green-500" />
                <span className="text-sm text-green-600">图片已上传</span>
              </div>
              <button
                type="button"
                onClick={() => handleImageUpload(field.key)}
                disabled={disabled}
                className="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                重新上传
              </button>
            </div>
          )}
        </div>
        {uploadState?.status === 'error' && (
          <div className="bg-red-50 border border-red-200 rounded-md p-3">
            <div className="flex items-center">
              <XCircle className="h-4 w-4 text-red-500 mr-2" />
              <span className="text-sm text-red-700">{uploadState.error}</span>
            </div>
          </div>
        )}
        {errors[field.key] && (
          <p className="text-sm text-red-500">{errors[field.key]}</p>
        )}
      </div>
    );
  };

  if (formFields.length === 0) {
    return (
      <div className={`bg-white border border-gray-200 rounded-lg shadow-sm ${className}`}>
        <div className="p-6">
          <div className="text-center text-gray-500">
            <FileText className="h-8 w-8 mx-auto mb-2" />
            <p>暂无可配置的表单字段</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={`bg-white border border-gray-200 rounded-lg shadow-sm ${className}`}>
      <div className="px-6 py-4 border-b border-gray-200">
        <h3 className="text-lg font-medium text-gray-900 flex items-center space-x-2">
          <FileText className="h-5 w-5" />
          <span>工作流参数配置</span>
        </h3>
      </div>
      <div className="p-6 space-y-4">
        {formFields.map(field => (
          field.type === 'value' ? renderTextField(field) : renderImageField(field)
        ))}

        {onSubmit && (
          <div className="pt-4 border-t">
            <button
              onClick={handleSubmit}
              disabled={disabled}
              className="w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              提交配置
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default AutoFormGenerator;
