import React, { useState, useEffect } from 'react';
import { X, Play, FileText, AlertCircle, CheckCircle, Clock, Settings } from 'lucide-react';
import ComfyuiService from '../services/comfyuiService';
import { AutoFormGenerator } from './AutoFormGenerator';
import type {
  Workflow,
  ExecuteWorkflowRequest,
  ExecuteWorkflowResponse,
  ExecuteWorkflowFormData,
  WorkflowInputs,
  AutoFormData,
  GetWorkflowSpecResponse
} from '../types/comfyui';

interface ComfyUIExecuteModalProps {
  isOpen: boolean;
  onClose: () => void;
  workflow: Workflow | null;
  onExecutionComplete: (result: ExecuteWorkflowResponse) => void;
}

/**
 * ComfyUI 执行工作流模态框
 */
const ComfyUIExecuteModal: React.FC<ComfyUIExecuteModalProps> = ({
  isOpen,
  onClose,
  workflow,
  onExecutionComplete,
}) => {
  const [formData, setFormData] = useState<ExecuteWorkflowFormData>({
    base_name: '',
    version: '',
    request_data: '{}',
  });
  const [executing, setExecuting] = useState(false);
  const [result, setResult] = useState<ExecuteWorkflowResponse | null>(null);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [showSpec, setShowSpec] = useState(false);
  const [spec, setSpec] = useState<GetWorkflowSpecResponse | null>(null);
  const [loadingSpec, setLoadingSpec] = useState(false);
  const [useAutoForm, setUseAutoForm] = useState(true);
  const [autoFormData, setAutoFormData] = useState<AutoFormData>({});
  const [workflowInputs, setWorkflowInputs] = useState<WorkflowInputs>({});

  useEffect(() => {
    if (isOpen && workflow) {
      const parsed = ComfyuiService.parseWorkflowName(workflow.name);
      setFormData({
        base_name: parsed.baseName,
        version: parsed.version || '',
        request_data: JSON.stringify({}, null, 2),
      });
      setResult(null);
      setErrors({});
      setSpec(null);
      setShowSpec(false);
      setAutoFormData({});
      setWorkflowInputs({});

      // 自动加载工作流规范
      loadWorkflowSpec(parsed.baseName, parsed.version);
    }
  }, [isOpen, workflow]);

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

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

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

    if (useAutoForm) {
      // 自动表单模式验证
      if (Object.keys(workflowInputs).length === 0) {
        newErrors.workflow = '请先加载工作流规范';
        return newErrors;
      }

      // 验证必填字段 - 只有 image 类型字段是必填的
      Object.entries(workflowInputs).forEach(([key, _field]) => {
        const parts = key.split('_');
        if (parts.length < 2) return;

        const type = parts[parts.length - 1];
        if (type === 'upload') return; // 忽略upload类型

        // 只有 image 类型字段是必填的，value 类型字段是可选的
        if (type === 'image') {
          const value = autoFormData[key];
          if (!value || (typeof value === 'string' && !value.trim())) {
            const label = parts.slice(0, -1).join('_');
            newErrors[key] = `${label} 不能为空`;
          }
        }
      });
    } else {
      // JSON模式验证
      if (!formData.request_data.trim()) {
        newErrors.request_data = '请求数据不能为空';
      } else {
        const validation = ComfyuiService.validateJson(formData.request_data);
        if (!validation.valid) {
          newErrors.request_data = `JSON 格式错误: ${validation.error}`;
        }
      }
    }

    return newErrors;
  };

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

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

  /**
   * 加载工作流规范
   */
  const loadWorkflowSpec = async (baseName: string, version?: string) => {
    if (!baseName.trim()) return;

    setLoadingSpec(true);
    try {
      const specResponse = await ComfyuiService.getWorkflowSpec({
        base_name: baseName,
        version: version || undefined,
      });
      setSpec(specResponse);

      // 解析工作流输入
      if (specResponse.spec && specResponse.spec.inputs) {
        setWorkflowInputs(specResponse.spec.inputs);
      }
    } catch (error) {
      console.error('获取工作流规范失败:', error);
      setErrors({ spec: `获取工作流规范失败: ${error}` });
    } finally {
      setLoadingSpec(false);
    }
  };

  const handleLoadSpec = async () => {
    if (!formData.base_name.trim()) {
      setErrors({ base_name: '请先输入工作流名称' });
      return;
    }

    await loadWorkflowSpec(formData.base_name, formData.version);
    setShowSpec(true);
  };

  /**
   * 处理自动表单数据变化
   */
  const handleAutoFormDataChange = (data: AutoFormData) => {
    setAutoFormData(data);
    // 同时更新传统表单的request_data
    setFormData(prev => ({
      ...prev,
      request_data: JSON.stringify(data, null, 2),
    }));
  };

  /**
   * 将自动表单数据转换为工作流执行格式
   * 直接使用工作流规范中的字段名作为键
   */
  const formatAutoFormDataForExecution = (data: AutoFormData): any => {
    console.log('开始格式化自动表单数据:', data);
    console.log('工作流输入字段:', workflowInputs);

    const executionData: any = {};

    Object.entries(data).forEach(([key, value]) => {
      const inputField = workflowInputs[key];
      if (!inputField) {
        console.warn(`未找到输入字段配置: ${key}`);
        return;
      }

      console.log(`处理字段 ${key}: value=${value}`);

      // 直接使用工作流规范中的字段名作为键
      executionData[key] = value;
    });

    console.log('格式化后的执行数据:', executionData);
    return executionData;
  };

  const handleExecute = async () => {
    console.log('开始执行工作流...');
    console.log('当前表单数据:', formData);
    console.log('使用自动表单:', useAutoForm);
    console.log('自动表单数据:', autoFormData);
    console.log('工作流输入:', workflowInputs);

    const validationErrors = validateForm();
    console.log('验证错误:', validationErrors);

    if (Object.keys(validationErrors).length > 0) {
      console.log('验证失败，设置错误信息');
      setErrors(validationErrors);
      return;
    }

    setExecuting(true);
    setResult(null);

    try {
      const requestData = useAutoForm
        ? formatAutoFormDataForExecution(autoFormData)
        : JSON.parse(formData.request_data);

      // 调试：打印请求数据
      console.log('执行工作流请求数据:', {
        base_name: formData.base_name,
        version: formData.version,
        request_data: requestData,
        useAutoForm,
        autoFormData,
        workflowInputs
      });

      // 验证参数格式
      if (useAutoForm) {
        console.log('✅ 使用新的参数格式 - 直接使用字段名作为键:');
        Object.entries(requestData).forEach(([key, value]) => {
          console.log(`  ${key}: ${value}`);
        });
      }

      const request: ExecuteWorkflowRequest = {
        base_name: formData.base_name,
        version: formData.version || undefined,
        request_data: requestData,
      };

      const response = await ComfyuiService.executeWorkflow(request);
      setResult(response);
      onExecutionComplete(response);
    } catch (error) {
      console.error('工作流执行错误:', error);

      // 检查是否是服务器端 ComfyUI 服务错误
      const errorMessage = String(error);
      let displayError = `执行失败: ${error}`;

      if (errorMessage.includes('comfyui-for-waas-ui')) {
        displayError = `服务器端 ComfyUI 服务暂时不可用，请稍后重试。技术详情: ${error}`;
      } else if (errorMessage.includes('Bad Request')) {
        displayError = `请求参数错误，请检查输入数据格式。详情: ${error}`;
      }

      setResult({
        error: displayError,
      });
    } finally {
      setExecuting(false);
    }
  };

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

  /**
   * 重置表单状态
   */
  const resetForm = () => {
    setFormData({
      base_name: '',
      version: '',
      request_data: '{}',
    });
    setAutoFormData({});
    setWorkflowInputs({});
    setSpec(null);
    setResult(null);
    setErrors({});
    setShowSpec(false);
    setLoadingSpec(false);
  };

  /**
   * 关闭模态框
   */
  const handleClose = () => {
    if (!executing) {
      resetForm();
      onClose();
    }
  };

  if (!isOpen || !workflow) 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">
          <div>
            <h2 className="text-xl font-semibold text-gray-900">执行工作流</h2>
            <p className="text-sm text-gray-600 mt-1">工作流: {workflow.name}</p>
          </div>
          <button
            onClick={handleClose}
            disabled={executing}
            className={`text-gray-400 hover:text-gray-600 transition-colors ${
              executing ? 'opacity-50 cursor-not-allowed' : ''
            }`}
          >
            <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">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-medium text-gray-900">执行参数</h3>

                {/* 表单模式切换 */}
                <div className="flex items-center space-x-2">
                  <button
                    onClick={() => setUseAutoForm(true)}
                    className={`px-3 py-1 text-sm rounded-md transition-colors ${
                      useAutoForm
                        ? 'bg-blue-100 text-blue-700 border border-blue-300'
                        : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                    }`}
                  >
                    <Settings className="w-4 h-4 inline mr-1" />
                    自动表单
                  </button>
                  <button
                    onClick={() => setUseAutoForm(false)}
                    className={`px-3 py-1 text-sm rounded-md transition-colors ${
                      !useAutoForm
                        ? 'bg-blue-100 text-blue-700 border border-blue-300'
                        : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                    }`}
                  >
                    <FileText className="w-4 h-4 inline mr-1" />
                    JSON模式
                  </button>
                </div>
              </div>

              {/* 工作流名称 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  工作流基础名称 *
                </label>
                <input
                  type="text"
                  value={formData.base_name}
                  onChange={(e) => handleInputChange('base_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.base_name ? 'border-red-300' : 'border-gray-300'
                  }`}
                  placeholder="my_workflow"
                />
                {errors.base_name && (
                  <p className="mt-1 text-sm text-red-600">{errors.base_name}</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 border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="1.0"
                />
              </div>

              {/* 获取规范按钮 */}
              {!useAutoForm && (
                <div>
                  <button
                    onClick={handleLoadSpec}
                    disabled={loadingSpec}
                    className="flex items-center gap-2 px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition-colors disabled:opacity-50"
                  >
                    <FileText className={`w-4 h-4 ${loadingSpec ? 'animate-pulse' : ''}`} />
                    {loadingSpec ? '加载中...' : '查看工作流规范'}
                  </button>
                  {errors.spec && (
                    <p className="mt-1 text-sm text-red-600">{errors.spec}</p>
                  )}
                </div>
              )}

              {/* 参数输入区域 */}
              {useAutoForm ? (
                /* 自动表单模式 */
                <div>
                  {loadingSpec ? (
                    <div className="flex items-center justify-center py-8">
                      <Clock className="w-6 h-6 animate-spin text-gray-400" />
                      <span className="ml-2 text-gray-500">加载工作流规范中...</span>
                    </div>
                  ) : Object.keys(workflowInputs).length > 0 ? (
                    <AutoFormGenerator
                      workflowInputs={workflowInputs}
                      onFormDataChange={handleAutoFormDataChange}
                      disabled={executing}
                    />
                  ) : (
                    <div className="text-center py-8 text-gray-500">
                      <FileText className="w-8 h-8 mx-auto mb-2" />
                      <p>暂无可配置的参数</p>
                      <p className="text-sm">请确认工作流规范包含inputs字段</p>
                    </div>
                  )}
                </div>
              ) : (
                /* JSON模式 */
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <label className="block text-sm font-medium text-gray-700">
                      请求数据 (JSON) *
                    </label>
                    <button
                      onClick={formatJsonData}
                      className="text-xs text-blue-600 hover:text-blue-700"
                    >
                      格式化
                    </button>
                  </div>
                  <textarea
                    value={formData.request_data}
                    onChange={(e) => handleInputChange('request_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.request_data ? 'border-red-300' : 'border-gray-300'
                    }`}
                    rows={8}
                    placeholder='{"param1": "value1", "param2": "value2"}'
                  />
                  {errors.request_data && (
                    <p className="mt-1 text-sm text-red-600">{errors.request_data}</p>
                  )}
                </div>
              )}
            </div>

            {/* 右侧：工作流规范或执行结果 */}
            <div className="space-y-4">
              {(showSpec || useAutoForm) && spec ? (
                <div>
                  <h3 className="text-lg font-medium text-gray-900 mb-2">工作流规范</h3>
                  {useAutoForm ? (
                    /* 自动表单模式下显示友好的规范信息 */
                    <div className="bg-gray-50 border border-gray-200 rounded-md p-4">
                      <div className="space-y-3">
                        {spec.name && (
                          <div>
                            <span className="text-sm font-medium text-gray-700">名称: </span>
                            <span className="text-sm text-gray-600">{spec.name}</span>
                          </div>
                        )}
                        {spec.version && (
                          <div>
                            <span className="text-sm font-medium text-gray-700">版本: </span>
                            <span className="text-sm text-gray-600">{spec.version}</span>
                          </div>
                        )}
                        {spec.description && (
                          <div>
                            <span className="text-sm font-medium text-gray-700">描述: </span>
                            <span className="text-sm text-gray-600">{spec.description}</span>
                          </div>
                        )}

                        {/* 输入参数统计 */}
                        <div>
                          <span className="text-sm font-medium text-gray-700">输入参数: </span>
                          <span className="text-sm text-gray-600">
                            {Object.keys(workflowInputs).length} 个字段
                          </span>
                        </div>

                        {/* 显示完整规范的按钮 */}
                        <button
                          onClick={() => setShowSpec(!showSpec)}
                          className="text-xs text-blue-600 hover:text-blue-700"
                        >
                          {showSpec ? '隐藏' : '查看'}完整规范
                        </button>

                        {/* 完整规范（可折叠） */}
                        {showSpec && (
                          <div className="mt-3 pt-3 border-t border-gray-200">
                            <div className="bg-white border border-gray-200 rounded p-3 max-h-64 overflow-y-auto">
                              <pre className="text-xs text-gray-700 whitespace-pre-wrap">
                                {JSON.stringify(spec.spec, null, 2)}
                              </pre>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  ) : (
                    /* JSON模式下显示完整规范 */
                    <div className="bg-gray-50 border border-gray-200 rounded-md p-4 max-h-96 overflow-y-auto">
                      <pre className="text-sm text-gray-700 whitespace-pre-wrap">
                        {JSON.stringify(spec.spec, null, 2)}
                      </pre>
                    </div>
                  )}
                </div>
              ) : result ? (
                <div>
                  <h3 className="text-lg font-medium text-gray-900 mb-2">执行结果</h3>
                  <div className={`border rounded-md p-4 ${
                    result.error ? 'border-red-200 bg-red-50' : 'border-green-200 bg-green-50'
                  }`}>
                    {result.error ? (
                      <div className="flex items-start gap-2">
                        <AlertCircle className="w-5 h-5 text-red-500 mt-0.5" />
                        <div>
                          <p className="font-medium text-red-700">执行失败</p>
                          <p className="text-sm text-red-600 mt-1">{result.error}</p>
                        </div>
                      </div>
                    ) : (
                      <div className="space-y-3">
                        <div className="flex items-center gap-2">
                          <CheckCircle className="w-5 h-5 text-green-500" />
                          <span className="font-medium text-green-700">执行成功</span>
                        </div>
                        
                        {result.task_id && (
                          <div>
                            <span className="text-sm font-medium text-gray-700">任务ID: </span>
                            <span className="text-sm text-gray-600">{result.task_id}</span>
                          </div>
                        )}
                        
                        {result.status && (
                          <div>
                            <span className="text-sm font-medium text-gray-700">状态: </span>
                            <span className="text-sm text-gray-600">{result.status}</span>
                          </div>
                        )}
                        
                        {result.message && (
                          <div>
                            <span className="text-sm font-medium text-gray-700">消息: </span>
                            <span className="text-sm text-gray-600">{result.message}</span>
                          </div>
                        )}
                        
                        {result.result && (
                          <div>
                            <span className="text-sm font-medium text-gray-700">结果数据:</span>
                            <pre className="text-xs text-gray-600 mt-1 bg-white border border-gray-200 rounded p-2 max-h-32 overflow-y-auto">
                              {JSON.stringify(result.result, null, 2)}
                            </pre>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              ) : (
                <div className="text-center py-8 text-gray-500">
                  <FileText className="w-12 h-12 text-gray-300 mx-auto mb-4" />
                  <p>点击"查看工作流规范"或"执行"查看内容</p>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* 操作按钮 */}
        <div className="flex items-center justify-end gap-3 p-6 border-t border-gray-200">
          <button
            onClick={handleClose}
            disabled={executing}
            className={`px-4 py-2 text-gray-600 hover:text-gray-800 transition-colors ${
              executing ? 'opacity-50 cursor-not-allowed' : ''
            }`}
          >
            取消
          </button>
          
          <button
            onClick={handleExecute}
            disabled={executing}
            className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors disabled:opacity-50"
          >
            {executing ? (
              <Clock className="w-4 h-4 animate-spin" />
            ) : (
              <Play className="w-4 h-4" />
            )}
            {executing ? '执行中...' : '执行工作流'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default ComfyUIExecuteModal;
