/**
 * 工作流执行模态框
 * 
 * 提供工作流执行界面，包括参数输入、执行进度和结果展示
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { X, Play, Square, Download, AlertCircle, CheckCircle } from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { WorkflowFormGenerator, WorkflowFormData } from './WorkflowFormGenerator';

interface WorkflowTemplate {
  id: number;
  name: string;
  base_name: string;
  version: string;
  type: string;
  description?: string;
  ui_config_json: any;
}

interface ExecutionResponse {
  execution_id: number;
  status: string;
  comfyui_prompt_id?: string;
  error_message?: string;
}

interface ExecutionStatus {
  execution_id: number;
  status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
  progress: number;
  output_data?: any;
  error_message?: string;
  comfyui_prompt_id?: string;
}

interface WorkflowExecutionModalProps {
  /** 是否显示模态框 */
  isOpen: boolean;
  /** 关闭模态框回调 */
  onClose: () => void;
  /** 工作流模板 */
  workflow: WorkflowTemplate | null;
}

/**
 * 工作流执行模态框组件
 */
export const WorkflowExecutionModal: React.FC<WorkflowExecutionModalProps> = ({
  isOpen,
  onClose,
  workflow
}) => {
  const [formData, setFormData] = useState<WorkflowFormData>({});
  const [executionStatus, setExecutionStatus] = useState<ExecutionStatus | null>(null);
  const [isExecuting, setIsExecuting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 稳定的表单数据更新回调
  const handleFormDataChange = useCallback((data: WorkflowFormData) => {
    setFormData(data);
  }, []);

  // 缓存uiConfig以避免不必要的重新渲染
  const stableUiConfig = useMemo(() => {
    return workflow?.ui_config_json;
  }, [workflow?.ui_config_json]);

  // 重置状态
  const resetState = () => {
    setFormData({});
    setExecutionStatus(null);
    setIsExecuting(false);
    setError(null);
  };

  // 当工作流变化时重置状态
  useEffect(() => {
    if (workflow) {
      resetState();
    }
  }, [workflow]);

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

    try {
      setIsExecuting(true);
      setError(null);

      const response = await invoke<ExecutionResponse>('execute_workflow_with_mapping', {
        request: {
          workflow_template_id: workflow.id,
          input_data: formData,
          execution_environment_id: undefined,
          execution_config_override: undefined
        }
      });

      // 转换响应格式
      const executionStatus: ExecutionStatus = {
        execution_id: response.execution_id,
        status: response.status as any,
        progress: 0,
        comfyui_prompt_id: response.comfyui_prompt_id,
        error_message: response.error_message
      };

      setExecutionStatus(executionStatus);

      // 开始轮询状态
      pollExecutionStatus(response.execution_id);
    } catch (err) {
      console.error('执行工作流失败:', err);
      setError(err as string);
      setIsExecuting(false);
    }
  };

  // 轮询执行状态
  const pollExecutionStatus = async (executionId: number) => {
    const pollInterval = setInterval(async () => {
      try {
        const status = await invoke<ExecutionStatus>('get_execution_status', {
          executionId
        });
        
        setExecutionStatus(status);
        
        // 如果执行完成，停止轮询
        if (['completed', 'failed', 'cancelled'].includes(status.status)) {
          clearInterval(pollInterval);
          setIsExecuting(false);
        }
      } catch (err) {
        console.error('获取执行状态失败:', err);
        clearInterval(pollInterval);
        setIsExecuting(false);
      }
    }, 2000);

    // 组件卸载时清理定时器
    return () => clearInterval(pollInterval);
  };

  // 取消执行
  const cancelExecution = async () => {
    if (!executionStatus) return;

    try {
      await invoke('cancel_execution', {
        executionId: executionStatus.execution_id
      });
    } catch (err) {
      console.error('取消执行失败:', err);
    }
  };

  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 max-w-4xl w-full mx-4 max-h-[90vh] overflow-hidden">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div>
            <h2 className="text-xl font-semibold text-gray-900">
              {workflow.name}
            </h2>
            <p className="text-sm text-gray-600 mt-1">
              {workflow.description}
            </p>
          </div>
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100 transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* 内容 */}
        <div className="p-6 overflow-y-auto max-h-[calc(90vh-140px)]">
          {!executionStatus ? (
            /* 参数输入阶段 */
            <div className="space-y-6">
              <div>
                <h3 className="text-lg font-medium text-gray-900 mb-4">
                  配置参数
                </h3>
                <WorkflowFormGenerator
                  uiConfig={stableUiConfig}
                  onFormDataChange={handleFormDataChange}
                  onSubmit={executeWorkflow}
                  disabled={isExecuting}
                />
              </div>
            </div>
          ) : (
            /* 执行状态阶段 */
            <div className="space-y-6">
              {/* 状态显示 */}
              <div className="bg-gray-50 rounded-lg p-4">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-lg font-medium text-gray-900">
                    执行状态
                  </h3>
                  <div className="flex items-center space-x-2">
                    {executionStatus.status === 'running' && (
                      <div className="flex items-center space-x-2 text-blue-600">
                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>
                        <span className="text-sm">执行中</span>
                      </div>
                    )}
                    {executionStatus.status === 'completed' && (
                      <div className="flex items-center space-x-2 text-green-600">
                        <CheckCircle className="w-4 h-4" />
                        <span className="text-sm">已完成</span>
                      </div>
                    )}
                    {executionStatus.status === 'failed' && (
                      <div className="flex items-center space-x-2 text-red-600">
                        <AlertCircle className="w-4 h-4" />
                        <span className="text-sm">执行失败</span>
                      </div>
                    )}
                  </div>
                </div>

                {/* 进度条 */}
                <div className="mb-4">
                  <div className="flex justify-between text-sm text-gray-600 mb-1">
                    <span>进度</span>
                    <span>{executionStatus.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: `${executionStatus.progress}%` }}
                    ></div>
                  </div>
                </div>

                {/* 错误信息 */}
                {executionStatus.error_message && (
                  <div className="bg-red-50 border border-red-200 rounded-lg p-3">
                    <div className="flex items-start space-x-2">
                      <AlertCircle className="w-5 h-5 text-red-500 mt-0.5" />
                      <div>
                        <h4 className="text-sm font-medium text-red-800">
                          执行错误
                        </h4>
                        <p className="text-sm text-red-700 mt-1">
                          {executionStatus.error_message}
                        </p>
                      </div>
                    </div>
                  </div>
                )}

                {/* 结果展示 */}
                {executionStatus.output_data && (
                  <div className="mt-4">
                    <h4 className="text-sm font-medium text-gray-900 mb-2">
                      执行结果
                    </h4>
                    <div className="bg-white border border-gray-200 rounded-lg p-3">
                      <pre className="text-sm text-gray-600 whitespace-pre-wrap">
                        {JSON.stringify(executionStatus.output_data, null, 2)}
                      </pre>
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* 错误信息 */}
          {error && (
            <div className="bg-red-50 border border-red-200 rounded-lg p-4">
              <div className="flex items-start space-x-2">
                <AlertCircle className="w-5 h-5 text-red-500 mt-0.5" />
                <div>
                  <h4 className="text-sm font-medium text-red-800">
                    操作失败
                  </h4>
                  <p className="text-sm text-red-700 mt-1">{error}</p>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* 底部按钮 */}
        <div className="flex items-center justify-between p-6 border-t border-gray-200">
          <div className="flex items-center space-x-2">
            {executionStatus?.comfyui_prompt_id && (
              <span className="text-xs text-gray-500">
                任务ID: {executionStatus.comfyui_prompt_id}
              </span>
            )}
          </div>
          
          <div className="flex items-center space-x-3">
            {!executionStatus ? (
              <>
                <button
                  onClick={onClose}
                  className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
                >
                  取消
                </button>
                <button
                  onClick={executeWorkflow}
                  disabled={isExecuting || Object.keys(formData).length === 0}
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors flex items-center space-x-2"
                >
                  <Play className="w-4 h-4" />
                  <span>开始执行</span>
                </button>
              </>
            ) : (
              <>
                {executionStatus.status === 'running' && (
                  <button
                    onClick={cancelExecution}
                    className="px-4 py-2 text-red-700 bg-red-100 rounded-lg hover:bg-red-200 transition-colors flex items-center space-x-2"
                  >
                    <Square className="w-4 h-4" />
                    <span>取消执行</span>
                  </button>
                )}
                
                {executionStatus.status === 'completed' && executionStatus.output_data && (
                  <button
                    onClick={() => console.log('下载结果:', executionStatus.output_data)}
                    className="px-4 py-2 text-blue-700 bg-blue-100 rounded-lg hover:bg-blue-200 transition-colors flex items-center space-x-2"
                  >
                    <Download className="w-4 h-4" />
                    <span>下载结果</span>
                  </button>
                )}
                
                <button
                  onClick={onClose}
                  className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
                >
                  关闭
                </button>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};
