import React, { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import {
  Play,
  RotateCcw,
  AlertCircle,
  CheckCircle,
  Clock,
  Loader2
} from 'lucide-react';
import { WorkflowTemplate, UIField, ExecuteWorkflowRequest, ExecuteWorkflowResponse } from '../../types/workflow';
import { WorkflowResultDisplay } from './WorkflowResultDisplay';
import { ErrorHandler, ErrorInfo } from '../../utils/error-handler';

interface WorkflowExecutionPageProps {
  /** 工作流模板 */
  template: WorkflowTemplate;
  /** 关闭回调 */
  onClose: () => void;
}

interface FormData {
  [key: string]: any;
}

interface ExecutionState {
  status: 'idle' | 'running' | 'completed' | 'failed';
  progress: number;
  executionId?: number;
  error?: string;
  errorInfo?: ErrorInfo;
  results?: any[];
  canRetry?: boolean;
}

export const WorkflowExecutionPage: React.FC<WorkflowExecutionPageProps> = ({
  template,
  onClose
}) => {
  const [formData, setFormData] = useState<FormData>({});
  const [executionState, setExecutionState] = useState<ExecutionState>({
    status: 'idle',
    progress: 0
  });
  const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});

  // 初始化表单数据
  useEffect(() => {
    const initialData: FormData = {};
    template.ui_config_json.form_fields.forEach(field => {
      if (field.default_value !== undefined) {
        initialData[field.name] = field.default_value;
      }
    });
    setFormData(initialData);
  }, [template]);

  // 更新表单字段值
  const updateFormField = (fieldName: string, value: any) => {
    setFormData(prev => ({ ...prev, [fieldName]: value }));
    
    // 清除该字段的验证错误
    if (validationErrors[fieldName]) {
      setValidationErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[fieldName];
        return newErrors;
      });
    }
  };

  // 验证表单
  const validateForm = (): boolean => {
    const errors: Record<string, string> = {};
    
    template.ui_config_json.form_fields.forEach(field => {
      if (field.required) {
        const value = formData[field.name];
        if (value === undefined || value === null || value === '') {
          errors[field.name] = `${field.label} 是必填字段`;
        }
      }
      
      // 类型验证
      if (formData[field.name] !== undefined && formData[field.name] !== '') {
        const value = formData[field.name];
        
        if (field.type === 'number' && isNaN(Number(value))) {
          errors[field.name] = `${field.label} 必须是数字`;
        }
        
        if (field.validation) {
          if (field.validation.min !== undefined && Number(value) < field.validation.min) {
            errors[field.name] = `${field.label} 不能小于 ${field.validation.min}`;
          }
          
          if (field.validation.max !== undefined && Number(value) > field.validation.max) {
            errors[field.name] = `${field.label} 不能大于 ${field.validation.max}`;
          }
          
          if (field.validation.pattern && !new RegExp(field.validation.pattern).test(String(value))) {
            errors[field.name] = `${field.label} 格式不正确`;
          }
        }
      }
    });
    
    setValidationErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // 执行工作流
  const executeWorkflow = async () => {
    if (!validateForm()) {
      return;
    }

    setExecutionState({
      status: 'running',
      progress: 0
    });

    try {
      const request: ExecuteWorkflowRequest = {
        workflow_template_id: template.id,
        input_data: formData,
        execution_environment_id: undefined,
        execution_config_override: undefined
      };

      const response: ExecuteWorkflowResponse = await invoke('execute_workflow_with_mapping', { request });
      
      setExecutionState({
        status: 'running',
        progress: 10,
        executionId: response.execution_id
      });

      // 开始轮询执行状态
      pollExecutionStatus(response.execution_id);
      
    } catch (error) {
      console.error('执行工作流失败:', error);
      const errorInfo = ErrorHandler.parseTauriError(error);
      setExecutionState({
        status: 'failed',
        progress: 0,
        error: errorInfo.message,
        errorInfo,
        canRetry: ErrorHandler.isRetryableError(errorInfo)
      });
    }
  };

  // 轮询执行状态
  const pollExecutionStatus = async (executionId: number) => {
    const pollInterval = setInterval(async () => {
      try {
        const status: ExecuteWorkflowResponse = await invoke('get_execution_status', { executionId });
        
        setExecutionState(prev => ({
          ...prev,
          progress: status.progress || 0
        }));

        if (status.status === 'completed') {
          clearInterval(pollInterval);
          setExecutionState({
            status: 'completed',
            progress: 100,
            executionId,
            results: status.output_data || []
          });
        } else if (status.status === 'failed') {
          clearInterval(pollInterval);
          setExecutionState({
            status: 'failed',
            progress: 0,
            executionId,
            error: status.error_message
          });
        }
      } catch (error) {
        console.error('获取执行状态失败:', error);
        clearInterval(pollInterval);
        const errorInfo = ErrorHandler.parseTauriError(error);
        setExecutionState(prev => ({
          ...prev,
          status: 'failed',
          error: errorInfo.message,
          errorInfo,
          canRetry: ErrorHandler.isRetryableError(errorInfo)
        }));
      }
    }, 2000);

    // 设置超时
    setTimeout(() => {
      clearInterval(pollInterval);
      if (executionState.status === 'running') {
        setExecutionState(prev => ({
          ...prev,
          status: 'failed',
          error: '执行超时'
        }));
      }
    }, 300000); // 5分钟超时
  };

  // 重置执行状态
  const resetExecution = () => {
    setExecutionState({
      status: 'idle',
      progress: 0
    });
  };

  // 渲染表单字段
  const renderFormField = (field: UIField) => {
    const value = formData[field.name];
    const error = validationErrors[field.name];
    const isDisabled = executionState.status === 'running';

    const baseInputClass = `w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
      error ? 'border-red-300' : 'border-gray-300'
    } ${isDisabled ? 'bg-gray-100 cursor-not-allowed' : ''}`;

    switch (field.type) {
      case 'text':
        return (
          <input
            type="text"
            value={value || ''}
            onChange={(e) => updateFormField(field.name, e.target.value)}
            placeholder={field.ui_config?.placeholder}
            className={baseInputClass}
            disabled={isDisabled}
          />
        );

      case 'textarea':
        return (
          <textarea
            value={value || ''}
            onChange={(e) => updateFormField(field.name, e.target.value)}
            placeholder={field.ui_config?.placeholder}
            rows={4}
            className={baseInputClass}
            disabled={isDisabled}
          />
        );

      case 'number':
        return (
          <input
            type="number"
            value={value || ''}
            onChange={(e) => updateFormField(field.name, Number(e.target.value))}
            min={field.validation?.min}
            max={field.validation?.max}
            className={baseInputClass}
            disabled={isDisabled}
          />
        );

      case 'select':
        return (
          <select
            value={value || ''}
            onChange={(e) => updateFormField(field.name, e.target.value)}
            className={baseInputClass}
            disabled={isDisabled}
          >
            <option value="">请选择...</option>
            {field.validation?.options?.map(option => (
              <option key={option} value={option}>{option}</option>
            ))}
          </select>
        );

      case 'checkbox':
        return (
          <label className="flex items-center space-x-2">
            <input
              type="checkbox"
              checked={value || false}
              onChange={(e) => updateFormField(field.name, e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              disabled={isDisabled}
            />
            <span className="text-sm text-gray-700">{field.label}</span>
          </label>
        );

      case 'slider':
        return (
          <div className="space-y-2">
            <input
              type="range"
              value={value || field.validation?.min || 0}
              onChange={(e) => updateFormField(field.name, Number(e.target.value))}
              min={field.validation?.min}
              max={field.validation?.max}
              className="w-full"
              disabled={isDisabled}
            />
            <div className="text-sm text-gray-600 text-center">
              {value || field.validation?.min || 0}
            </div>
          </div>
        );

      default:
        return (
          <input
            type="text"
            value={value || ''}
            onChange={(e) => updateFormField(field.name, e.target.value)}
            className={baseInputClass}
            disabled={isDisabled}
          />
        );
    }
  };

  return (
    <div className="max-w-6xl mx-auto p-6 space-y-6">
      {/* 头部 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">{template.name}</h1>
          <p className="text-gray-600">{template.description}</p>
        </div>
        
        <button
          onClick={onClose}
          className="px-4 py-2 text-gray-600 hover:text-gray-800"
        >
          关闭
        </button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 左侧：表单 */}
        <div className="space-y-6">
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">参数配置</h2>
            
            <div className="space-y-4">
              {template.ui_config_json.form_fields.map(field => (
                <div key={field.name}>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {field.label}
                    {field.required && <span className="text-red-500 ml-1">*</span>}
                  </label>
                  
                  {renderFormField(field)}
                  
                  {field.description && (
                    <p className="mt-1 text-xs text-gray-500">{field.description}</p>
                  )}
                  
                  {validationErrors[field.name] && (
                    <p className="mt-1 text-xs text-red-600">{validationErrors[field.name]}</p>
                  )}
                </div>
              ))}
            </div>

            {/* 执行按钮 */}
            <div className="mt-6 pt-4 border-t border-gray-200">
              <div className="flex items-center space-x-3">
                <button
                  onClick={executeWorkflow}
                  disabled={executionState.status === 'running'}
                  className="flex items-center space-x-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
                >
                  {executionState.status === 'running' ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <Play className="w-4 h-4" />
                  )}
                  <span>
                    {executionState.status === 'running' ? '执行中...' : '开始执行'}
                  </span>
                </button>

                {executionState.status !== 'idle' && (
                  <button
                    onClick={resetExecution}
                    className="flex items-center space-x-2 px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
                  >
                    <RotateCcw className="w-4 h-4" />
                    <span>重置</span>
                  </button>
                )}

                {executionState.status === 'failed' && executionState.canRetry && (
                  <button
                    onClick={executeWorkflow}
                    className="flex items-center space-x-2 px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700"
                  >
                    <RotateCcw className="w-4 h-4" />
                    <span>重试</span>
                  </button>
                )}
              </div>

              {/* 执行状态 */}
              {executionState.status !== 'idle' && (
                <div className="mt-4 space-y-2">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">执行进度</span>
                    <span className="text-gray-900">{executionState.progress}%</span>
                  </div>
                  
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div
                      className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                      style={{ width: `${executionState.progress}%` }}
                    />
                  </div>

                  <div className="flex items-center space-x-2 text-sm">
                    {executionState.status === 'running' && (
                      <>
                        <Clock className="w-4 h-4 text-blue-500" />
                        <span className="text-blue-600">正在执行...</span>
                      </>
                    )}
                    
                    {executionState.status === 'completed' && (
                      <>
                        <CheckCircle className="w-4 h-4 text-green-500" />
                        <span className="text-green-600">执行完成</span>
                      </>
                    )}
                    
                    {executionState.status === 'failed' && (
                      <>
                        <AlertCircle className="w-4 h-4 text-red-500" />
                        <span className="text-red-600">执行失败</span>
                      </>
                    )}
                  </div>

                  {executionState.error && (
                    <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                      <div className="flex items-start space-x-3">
                        <AlertCircle className="w-5 h-5 text-red-500 mt-0.5 flex-shrink-0" />
                        <div className="flex-1">
                          <div className="text-sm font-medium text-red-800 mb-2">
                            {executionState.error}
                          </div>

                          {executionState.errorInfo?.details && (
                            <div className="text-sm text-red-700 mb-3">
                              <div className="font-medium mb-1">详细信息：</div>
                              <div className="bg-red-100 rounded p-2 font-mono text-xs">
                                {executionState.errorInfo.details}
                              </div>
                            </div>
                          )}

                          {executionState.errorInfo?.suggestions && executionState.errorInfo.suggestions.length > 0 && (
                            <div className="text-sm text-red-700">
                              <div className="font-medium mb-2">建议解决方案：</div>
                              <ul className="list-disc list-inside space-y-1">
                                {executionState.errorInfo.suggestions.map((suggestion, index) => (
                                  <li key={index} className="text-xs">{suggestion}</li>
                                ))}
                              </ul>
                            </div>
                          )}

                          {executionState.canRetry && (
                            <div className="mt-3 text-xs text-red-600 bg-red-100 rounded p-2">
                              💡 这是一个可重试的错误，您可以点击"重试"按钮再次尝试执行。
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>

        {/* 右侧：结果展示 */}
        <div className="space-y-6">
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">执行结果</h2>
            
            {executionState.results ? (
              <WorkflowResultDisplay
                results={executionState.results}
                outputSchema={template.output_schema_json}
                showDownload={true}
                showFullscreen={true}
                layout="list"
              />
            ) : (
              <div className="text-center py-8 text-gray-500">
                <div className="text-sm">
                  {executionState.status === 'idle' && '点击"开始执行"来运行工作流'}
                  {executionState.status === 'running' && '正在执行，请稍候...'}
                  {executionState.status === 'failed' && '执行失败，请检查参数后重试'}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};
