/**
 * 启动工作流弹窗组件
 * 在工作流定义列表页使用，用于启动工作流实例
 */

import React, { useRef, useState } from 'react';
import { Modal, Button } from 'antd';
import { FormRenderer, type FormRendererRef } from '@/components/FormDesigner';
import { useToast } from '@/components/ui/use-toast';
import type { FormDefinitionResponse } from '@/pages/Form/Definition/List/types';
import type { WorkflowDefinition } from '../types';

interface StartWorkflowModalProps {
  /** 是否显示弹窗 */
  open: boolean;
  /** 关闭弹窗回调 */
  onClose: () => void;
  /** 工作流定义 */
  workflowDefinition: WorkflowDefinition | null;
  /** 表单定义数据 */
  formDefinition: FormDefinitionResponse | null;
  /** 提交回调 */
  onSubmit: (workflowDefinition: WorkflowDefinition, formData: Record<string, any>) => Promise<void>;
}

const StartWorkflowModal: React.FC<StartWorkflowModalProps> = ({
  open,
  onClose,
  workflowDefinition,
  formDefinition,
  onSubmit,
}) => {
  const formRef = useRef<FormRendererRef>(null);
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  // 处理提交
  const handleSubmit = async (formData: Record<string, any>) => {
    if (!workflowDefinition) {
      return;
    }

    console.log('🚀 启动工作流:', {
      workflowId: workflowDefinition.id,
      workflowName: workflowDefinition.name,
      workflowKey: workflowDefinition.key,
      formData: formData,
    });

    await onSubmit(workflowDefinition, formData);
    onClose();

    return {
      success: true,
      workflowDefinitionId: workflowDefinition.id,
      data: formData,
    };
  };

  // 处理取消 - 直接关闭弹窗
  const handleCancel = () => {
    onClose();
  };

  // 处理重置
  const handleReset = () => {
    formRef.current?.reset();
    toast({
      title: "表单已重置",
      description: "所有字段已恢复为初始状态",
    });
  };

  // 处理表单提交触发
  const handleTriggerSubmit = async () => {
    setLoading(true);
    try {
      await formRef.current?.submit();
    } catch (error) {
      console.error('启动工作流失败:', error);
    } finally {
      setLoading(false);
    }
  };

  if (!workflowDefinition || !formDefinition) {
    return null;
  }

  const { schema } = formDefinition;

  return (
    <Modal
      title={
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingRight: '40px' }}>
          <span>{formDefinition.name || `启动工作流：${workflowDefinition.name}`}</span>
          <div style={{ display: 'flex', gap: '8px', fontSize: '12px' }}>
            <span style={{
              background: '#f5f5f5',
              padding: '2px 10px',
              borderRadius: '12px',
              color: '#666',
              fontWeight: 'normal'
            }}>
              工作流 v{workflowDefinition.flowVersion}
            </span>
            <span style={{
              background: '#f5f5f5',
              padding: '2px 10px',
              borderRadius: '12px',
              color: '#666',
              fontWeight: 'normal'
            }}>
              表单 v{formDefinition.formVersion}
            </span>
          </div>
        </div>
      }
      open={open}
      onCancel={handleCancel}
      width={schema.formConfig.formWidth || 600}
      centered
      footer={
        <div style={{ display: 'flex', justifyContent: 'center', gap: '12px' }}>
          <Button 
            key="reset"
            onClick={handleReset}
            style={{ minWidth: '88px' }}
          >
            重置
          </Button>
          <Button 
            key="cancel"
            onClick={handleCancel}
            style={{ minWidth: '88px' }}
          >
            取消
          </Button>
          <Button
            key="submit"
            type="primary"
            loading={loading}
            onClick={handleTriggerSubmit}
            style={{ 
              minWidth: '120px',
              backgroundColor: '#000',
              borderColor: '#000'
            }}
          >
            启动工作流
          </Button>
        </div>
      }
    >
      <FormRenderer
        ref={formRef}
        schema={schema}
        onSubmit={handleSubmit}
      />
    </Modal>
  );
};

export default StartWorkflowModal;

