import React, {useEffect} from 'react';
import {Modal, Form, Input, message} from 'antd';
import type {WorkflowDefinition} from '../types';
import {saveDefinition, updateDefinition} from '../service';

interface EditModalProps {
    visible: boolean;
    onClose: () => void;
    onSuccess?: () => void;
    record?: WorkflowDefinition;
}

const EditModal: React.FC<EditModalProps> = ({visible, onClose, onSuccess, record}) => {
    const [form] = Form.useForm();
    const isEdit = !!record;

    useEffect(() => {
        if (visible && record) {
            form.setFieldsValue(record);
        }
    }, [visible, record]);

    const handleOk = async () => {
        try {
            const values = await form.validateFields();
            if (isEdit) {
                await updateDefinition(record.id, {
                    ...record,
                    ...values,
                });
            } else {
                await saveDefinition({
                    ...values,
                    flowVersion: 1,
                    status: 'DRAFT'
                } as WorkflowDefinition);
            }
            message.success(isEdit ? '更新成功' : '保存成功');
            onSuccess?.();
            onClose();
            form.resetFields();
        } catch (error) {
            if (error instanceof Error) {
                message.error(error.message);
            }
        }
    };

    return (
        <Modal
            title={isEdit ? '编辑流程' : '新建流程'}
            open={visible}
            onOk={handleOk}
            onCancel={() => {
                onClose();
                form.resetFields();
            }}
            destroyOnClose
        >
            <Form
                form={form}
                layout="vertical"
                preserve={false}
            >
                <Form.Item
                    name="name"
                    label="流程名称"
                    rules={[{required: true, message: '请输入流程名称'}]}
                >
                    <Input placeholder="请输入流程名称"/>
                </Form.Item>
                <Form.Item
                    name="key"
                    label="流程标识"
                    rules={[{required: true, message: '请输入流程标识'}]}
                >
                    <Input placeholder="请输入流程标识" disabled={isEdit}/>
                </Form.Item>
                <Form.Item
                    name="description"
                    label="描述"
                >
                    <Input.TextArea placeholder="请输入流程描述"/>
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default EditModal;
