/**
 * 工作流预览组件
 * 
 * 实时预览工作流的UI界面效果
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState } from 'react';
import { 
  Eye, 
  Upload, 
  Calendar, 
  Palette,
  Sliders,
  CheckCircle,
  FileText,
  Edit3,
  Layers,
  Settings,
  AlertCircle
} from 'lucide-react';

// 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 WorkflowPreviewProps {
  /** 工作流名称 */
  workflowName: string;
  /** 工作流描述 */
  description?: string;
  /** UI字段列表 */
  fields: UIField[];
  /** 预览模式 */
  mode?: 'desktop' | 'mobile';
}

/**
 * 工作流预览组件
 */
export const WorkflowPreview: React.FC<WorkflowPreviewProps> = ({
  workflowName,
  description,
  fields,
  mode = 'desktop'
}) => {
  const [formData, setFormData] = useState<Record<string, any>>({});

  // 获取字段图标
  const getFieldIcon = (type: UIFieldType) => {
    const iconMap = {
      text: Edit3,
      textarea: FileText,
      number: Settings,
      select: Layers,
      checkbox: CheckCircle,
      image_upload: Upload,
      file_upload: Upload,
      slider: Sliders,
      color: Palette,
      date: Calendar
    };
    return iconMap[type] || Settings;
  };

  // 更新表单数据
  const updateFormData = (fieldName: string, value: any) => {
    setFormData(prev => ({ ...prev, [fieldName]: value }));
  };

  // 渲染字段
  const renderField = (field: UIField) => {
    const Icon = getFieldIcon(field.type);
    const value = formData[field.name] ?? field.default_value ?? '';

    const fieldElement = (() => {
      switch (field.type) {
        case 'text':
          return (
            <input
              type="text"
              value={value}
              onChange={(e) => updateFormData(field.name, e.target.value)}
              placeholder={field.ui_config?.placeholder}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              required={field.required}
            />
          );

        case 'textarea':
          return (
            <textarea
              value={value}
              onChange={(e) => updateFormData(field.name, e.target.value)}
              placeholder={field.ui_config?.placeholder}
              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"
              required={field.required}
            />
          );

        case 'number':
          return (
            <input
              type="number"
              value={value}
              onChange={(e) => updateFormData(field.name, Number(e.target.value))}
              min={field.validation?.min}
              max={field.validation?.max}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              required={field.required}
            />
          );

        case 'select':
          return (
            <select
              value={value}
              onChange={(e) => updateFormData(field.name, 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"
              required={field.required}
            >
              <option value="">请选择...</option>
              {field.validation?.options?.map((option, index) => (
                <option key={index} value={option}>
                  {option}
                </option>
              ))}
            </select>
          );

        case 'checkbox':
          return (
            <label className="flex items-center space-x-2">
              <input
                type="checkbox"
                checked={value}
                onChange={(e) => updateFormData(field.name, e.target.checked)}
                className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              />
              <span className="text-sm text-gray-700">
                {field.ui_config?.help_text || '启用此选项'}
              </span>
            </label>
          );

        case 'slider':
          return (
            <div className="space-y-2">
              <input
                type="range"
                value={value}
                onChange={(e) => updateFormData(field.name, Number(e.target.value))}
                min={field.validation?.min || 0}
                max={field.validation?.max || 100}
                className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer slider"
              />
              <div className="flex justify-between text-xs text-gray-500">
                <span>{field.validation?.min || 0}</span>
                <span className="font-medium">{value}</span>
                <span>{field.validation?.max || 100}</span>
              </div>
            </div>
          );

        case 'color':
          return (
            <div className="flex items-center space-x-2">
              <input
                type="color"
                value={value || '#000000'}
                onChange={(e) => updateFormData(field.name, e.target.value)}
                className="w-12 h-10 border border-gray-300 rounded cursor-pointer"
              />
              <input
                type="text"
                value={value || '#000000'}
                onChange={(e) => updateFormData(field.name, e.target.value)}
                placeholder="#000000"
                className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
          );

        case 'date':
          return (
            <input
              type="date"
              value={value}
              onChange={(e) => updateFormData(field.name, 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"
              required={field.required}
            />
          );

        case 'image_upload':
        case 'file_upload':
          return (
            <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-gray-400 transition-colors">
              <Upload className="w-8 h-8 text-gray-400 mx-auto mb-2" />
              <p className="text-sm text-gray-600 mb-1">
                点击上传或拖拽文件到此处
              </p>
              <p className="text-xs text-gray-500">
                {field.type === 'image_upload' ? '支持 JPG, PNG, GIF 格式' : '支持所有文件格式'}
              </p>
              <input
                type="file"
                accept={field.type === 'image_upload' ? 'image/*' : '*/*'}
                onChange={(e) => {
                  const file = e.target.files?.[0];
                  if (file) {
                    updateFormData(field.name, file.name);
                  }
                }}
                className="hidden"
                id={`file-${field.name}`}
              />
              <label
                htmlFor={`file-${field.name}`}
                className="mt-2 inline-block px-4 py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 cursor-pointer transition-colors"
              >
                选择文件
              </label>
              {value && (
                <p className="mt-2 text-sm text-green-600">
                  已选择: {value}
                </p>
              )}
            </div>
          );

        default:
          return (
            <div className="p-4 bg-gray-100 rounded-lg text-center">
              <AlertCircle className="w-6 h-6 text-gray-400 mx-auto mb-2" />
              <p className="text-sm text-gray-600">
                不支持的字段类型: {field.type}
              </p>
            </div>
          );
      }
    })();

    // 根据宽度配置确定CSS类
    const widthClass = {
      full: 'col-span-full',
      half: 'col-span-6',
      third: 'col-span-4'
    }[field.ui_config?.width || 'full'];

    return (
      <div key={field.name} className={`${widthClass}`}>
        <div className="space-y-2">
          {/* 字段标签 */}
          <div className="flex items-center space-x-2">
            <Icon className="w-4 h-4 text-gray-500" />
            <label className="text-sm font-medium text-gray-700">
              {field.label}
              {field.required && <span className="text-red-500 ml-1">*</span>}
            </label>
          </div>

          {/* 字段描述 */}
          {field.description && (
            <p className="text-xs text-gray-600">{field.description}</p>
          )}

          {/* 字段输入 */}
          {fieldElement}

          {/* 帮助文本 */}
          {field.ui_config?.help_text && (
            <p className="text-xs text-gray-500">{field.ui_config.help_text}</p>
          )}
        </div>
      </div>
    );
  };

  // 按组分组字段
  const groupedFields = fields.reduce((groups, field) => {
    const group = field.ui_config?.group || 'default';
    if (!groups[group]) {
      groups[group] = [];
    }
    groups[group].push(field);
    return groups;
  }, {} as Record<string, UIField[]>);

  // 排序字段
  Object.keys(groupedFields).forEach(group => {
    groupedFields[group].sort((a, b) => (a.ui_config?.order || 0) - (b.ui_config?.order || 0));
  });

  return (
    <div className={`bg-white rounded-lg border border-gray-200 ${mode === 'mobile' ? 'max-w-sm' : 'max-w-2xl'}`}>
      {/* 预览头部 */}
      <div className="p-4 border-b border-gray-200">
        <div className="flex items-center space-x-2 mb-2">
          <Eye className="w-5 h-5 text-blue-600" />
          <h3 className="text-lg font-medium text-gray-900">{workflowName || '工作流预览'}</h3>
        </div>
        {description && (
          <p className="text-sm text-gray-600">{description}</p>
        )}
      </div>

      {/* 预览内容 */}
      <div className="p-4">
        {fields.length === 0 ? (
          <div className="text-center py-8">
            <Layers className="w-12 h-12 text-gray-400 mx-auto mb-4" />
            <p className="text-gray-600">还没有配置任何字段</p>
            <p className="text-sm text-gray-500 mt-1">
              在UI配置中添加字段后，这里将显示预览效果
            </p>
          </div>
        ) : (
          <form className="space-y-6">
            {Object.entries(groupedFields).map(([groupName, groupFields]) => (
              <div key={groupName}>
                {groupName !== 'default' && (
                  <h4 className="text-sm font-medium text-gray-900 mb-3 pb-2 border-b border-gray-200">
                    {groupName}
                  </h4>
                )}
                <div className="grid grid-cols-12 gap-4">
                  {groupFields.map(renderField)}
                </div>
              </div>
            ))}

            {/* 预览提交按钮 */}
            <div className="pt-4 border-t border-gray-200">
              <button
                type="button"
                className="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                disabled
              >
                执行工作流 (预览模式)
              </button>
            </div>
          </form>
        )}
      </div>

      {/* 预览底部信息 */}
      <div className="px-4 py-3 bg-gray-50 border-t border-gray-200 rounded-b-lg">
        <div className="flex items-center justify-between text-xs text-gray-500">
          <span>预览模式 - {mode === 'mobile' ? '移动端' : '桌面端'}</span>
          <span>{fields.length} 个字段</span>
        </div>
      </div>
    </div>
  );
};
