import React, { useState } from 'react';
import { X, Upload, AlertCircle, CheckCircle } from 'lucide-react';
import ComfyuiService from '../services/comfyuiService';
import type { 
  PublishWorkflowRequest, 
  PublishWorkflowResponse,
  WorkflowFormData 
} from '../types/comfyui';

interface ComfyUIPublishModalProps {
  isOpen: boolean;
  onClose: () => void;
  onPublishComplete: (result: PublishWorkflowResponse) => void;
}

/**
 * ComfyUI 发布工作流模态框
 */
const ComfyUIPublishModal: React.FC<ComfyUIPublishModalProps> = ({
  isOpen,
  onClose,
  onPublishComplete,
}) => {
  const [formData, setFormData] = useState<WorkflowFormData>({
    name: '',
    description: '',
    version: '1.0',
    workflow_data: '{}',
  });
  const [publishing, setPublishing] = useState(false);
  const [result, setResult] = useState<PublishWorkflowResponse | null>(null);
  const [errors, setErrors] = useState<Record<string, string>>({});

  // ============================================================================
  // 表单验证
  // ============================================================================

  const validateForm = (): Record<string, string> => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = '工作流名称不能为空';
    } else if (!/^[a-zA-Z0-9_-]+$/.test(formData.name.trim())) {
      newErrors.name = '工作流名称只能包含字母、数字、下划线和连字符';
    }

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

    if (!formData.workflow_data.trim()) {
      newErrors.workflow_data = '工作流数据不能为空';
    } else {
      const validation = ComfyuiService.validateJson(formData.workflow_data);
      if (!validation.valid) {
        newErrors.workflow_data = `JSON 格式错误: ${validation.error}`;
      }
    }

    return newErrors;
  };

  // ============================================================================
  // 事件处理
  // ============================================================================

  const handleInputChange = (field: keyof WorkflowFormData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    
    // 清除对应字段的错误
    if (errors[field]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  const handlePublish = async () => {
    const validationErrors = validateForm();
    if (Object.keys(validationErrors).length > 0) {
      setErrors(validationErrors);
      return;
    }

    setPublishing(true);
    setResult(null);

    try {
      const request: PublishWorkflowRequest = {
        name: formData.name.trim(),
        description: formData.description.trim() || undefined,
        version: formData.version.trim(),
        workflow_data: JSON.parse(formData.workflow_data),
      };

      const response = await ComfyuiService.publishWorkflow(request);
      setResult(response);
      onPublishComplete(response);
      
      if (response.success) {
        // 发布成功后清空表单
        setFormData({
          name: '',
          description: '',
          version: '1.0',
          workflow_data: '{}',
        });
      }
    } catch (error) {
      setResult({
        success: false,
        message: `发布失败: ${error}`,
      });
    } finally {
      setPublishing(false);
    }
  };

  const handleReset = () => {
    setFormData({
      name: '',
      description: '',
      version: '1.0',
      workflow_data: '{}',
    });
    setErrors({});
    setResult(null);
  };

  const formatJsonData = () => {
    try {
      const parsed = JSON.parse(formData.workflow_data);
      const formatted = JSON.stringify(parsed, null, 2);
      handleInputChange('workflow_data', formatted);
    } catch (error) {
      // JSON 格式错误，不做处理
    }
  };

  const loadSampleWorkflow = () => {
    const sampleWorkflow = {
      "nodes": [
        {
          "id": "1",
          "type": "LoadImage",
          "inputs": {
            "image": "sample.png"
          }
        },
        {
          "id": "2",
          "type": "SaveImage",
          "inputs": {
            "images": ["1", 0]
          }
        }
      ],
      "links": [
        ["1", 0, "2", 0]
      ],
      "metadata": {
        "title": "Sample Workflow",
        "description": "A simple image processing workflow"
      }
    };
    
    handleInputChange('workflow_data', JSON.stringify(sampleWorkflow, null, 2));
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-4xl mx-4 max-h-[90vh] overflow-y-auto">
        {/* 标题栏 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 className="text-xl font-semibold text-gray-900">发布工作流</h2>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* 表单内容 */}
        <div className="p-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* 左侧：基本信息 */}
            <div className="space-y-4">
              <h3 className="text-lg font-medium text-gray-900">基本信息</h3>
              
              {/* 工作流名称 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  工作流名称 *
                </label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => handleInputChange('name', e.target.value)}
                  className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                    errors.name ? 'border-red-300' : 'border-gray-300'
                  }`}
                  placeholder="my_workflow"
                />
                {errors.name && (
                  <p className="mt-1 text-sm text-red-600">{errors.name}</p>
                )}
                <p className="mt-1 text-xs text-gray-500">
                  只能包含字母、数字、下划线和连字符
                </p>
              </div>

              {/* 版本 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  版本 *
                </label>
                <input
                  type="text"
                  value={formData.version}
                  onChange={(e) => handleInputChange('version', e.target.value)}
                  className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                    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-2">
                  描述（可选）
                </label>
                <textarea
                  value={formData.description}
                  onChange={(e) => handleInputChange('description', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  rows={4}
                  placeholder="工作流的详细描述..."
                />
              </div>

              {/* 发布结果 */}
              {result && (
                <div className={`p-4 rounded-md ${
                  result.success ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'
                }`}>
                  <div className="flex items-start gap-2">
                    {result.success ? (
                      <CheckCircle className="w-5 h-5 text-green-500 mt-0.5" />
                    ) : (
                      <AlertCircle className="w-5 h-5 text-red-500 mt-0.5" />
                    )}
                    <div>
                      <p className={`font-medium ${
                        result.success ? 'text-green-700' : 'text-red-700'
                      }`}>
                        {result.success ? '发布成功' : '发布失败'}
                      </p>
                      {result.message && (
                        <p className={`text-sm mt-1 ${
                          result.success ? 'text-green-600' : 'text-red-600'
                        }`}>
                          {result.message}
                        </p>
                      )}
                      {result.workflow && (
                        <p className="text-sm text-green-600 mt-1">
                          工作流名称: {result.workflow.name}
                        </p>
                      )}
                    </div>
                  </div>
                </div>
              )}
            </div>

            {/* 右侧：工作流数据 */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-medium text-gray-900">工作流数据</h3>
                <div className="flex items-center gap-2">
                  <button
                    onClick={loadSampleWorkflow}
                    className="text-xs text-blue-600 hover:text-blue-700"
                  >
                    加载示例
                  </button>
                  <button
                    onClick={formatJsonData}
                    className="text-xs text-blue-600 hover:text-blue-700"
                  >
                    格式化
                  </button>
                </div>
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  工作流配置 (JSON) *
                </label>
                <textarea
                  value={formData.workflow_data}
                  onChange={(e) => handleInputChange('workflow_data', e.target.value)}
                  className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm ${
                    errors.workflow_data ? 'border-red-300' : 'border-gray-300'
                  }`}
                  rows={16}
                  placeholder='{"nodes": [], "links": [], "metadata": {}}'
                />
                {errors.workflow_data && (
                  <p className="mt-1 text-sm text-red-600">{errors.workflow_data}</p>
                )}
                <p className="mt-1 text-xs text-gray-500">
                  请输入有效的 JSON 格式的工作流配置数据
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* 操作按钮 */}
        <div className="flex items-center justify-between p-6 border-t border-gray-200">
          <button
            onClick={handleReset}
            className="px-4 py-2 text-gray-600 hover:text-gray-800 transition-colors"
          >
            重置表单
          </button>
          
          <div className="flex items-center gap-3">
            <button
              onClick={onClose}
              className="px-4 py-2 text-gray-600 hover:text-gray-800 transition-colors"
            >
              取消
            </button>
            
            <button
              onClick={handlePublish}
              disabled={publishing}
              className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors disabled:opacity-50"
            >
              <Upload className={`w-4 h-4 ${publishing ? 'animate-pulse' : ''}`} />
              {publishing ? '发布中...' : '发布工作流'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ComfyUIPublishModal;
