import React, {useEffect, useState} from 'react';
import {Modal, Form, Input, message, Select} from 'antd';
import type {WorkflowDefinition, WorkflowCategory} from '../types';
import {saveDefinition, updateDefinition, getWorkflowCategories} 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;
    const [categories, setCategories] = useState<WorkflowCategory[]>([]);
    const [selectedCategory, setSelectedCategory] = useState<WorkflowCategory>();

    useEffect(() => {
        if (visible) {
            loadCategories();
        }
    }, [visible]);

    useEffect(() => {
        if (visible && record) {
            // 找到当前分类
            const category = categories.find(c => c.code === record.category);
            setSelectedCategory(category);

            // 设置表单值，使用lable显示
            form.setFieldsValue({
                ...record,
                // 分类显示lable
                category: {
                    label: category?.lable,
                    value: record.category
                },
                // 触发器显示lable
                triggers: record.triggers?.map(triggerCode => ({
                    label: category?.supportedTriggers.find(t => t.code === triggerCode)?.lable,
                    value: triggerCode
                })) || []
            });
        }
    }, [visible, record, categories]);

    const loadCategories = async () => {
        try {
            const data = await getWorkflowCategories();
            setCategories(data);
        } catch (error) {
            console.error('加载工作流分类失败:', error);
            message.error('加载工作流分类失败');
        }
    };

    const handleCategoryChange = (selected: { value: string, label: string }) => {
        const category = categories.find(c => c.code === selected.value);
        setSelectedCategory(category);
        // 当切换分类时，清空触发器选择
        form.setFieldValue('triggers', []);
    };

    const handleOk = async () => {
        try {
            const values = await form.validateFields();
            const submitData = {
                ...values,
                // 提取code值提交给后端
                category: values.category.value,
                triggers: values.triggers.map((t: {value: string}) => t.value),
                flowVersion: isEdit ? record.flowVersion : 1,
                status: isEdit ? record.status : 'DRAFT'
            };

            if (isEdit) {
                await updateDefinition(record.id, {
                    ...record,
                    ...submitData,
                });
            } else {
                await saveDefinition(submitData 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="category"
                    label="流程分类"
                    rules={[{required: true, message: '请选择流程分类'}]}
                >
                    <Select 
                        placeholder="请选择流程分类"
                        onChange={handleCategoryChange}
                        disabled={isEdit}
                        labelInValue
                    >
                        {(categories || []).map(category => (
                            <Select.Option key={category.code} value={category.code}>
                                {category.lable}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item
                    name="triggers"
                    label="触发方式"
                    rules={[{required: true, message: '请选择触发方式'}]}
                >
                    <Select 
                        mode="multiple"
                        placeholder="请选择触发方式"
                        disabled={!selectedCategory || isEdit}
                        labelInValue
                    >
                        {(selectedCategory?.supportedTriggers || []).map(trigger => (
                            <Select.Option key={trigger.code} value={trigger.code}>
                                {trigger.lable}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item
                    name="name"
                    label="流程名称"
                    rules={[{required: true, message: '请输入流程名称'}]}
                >
                    <Input placeholder="请输入流程名称"/>
                </Form.Item>
                <Form.Item
                    name="key"
                    label="流程标识"
                    rules={[
                        { required: true, message: '请输入流程标识' },
                        {
                            pattern: /^[a-zA-Z_][a-zA-Z0-9_-]*$/,
                            message: '流程标识只能包含字母、数字、下划线(_)和连字符(-)，且必须以字母或下划线开头'
                        },
                        {
                            pattern: /^(?!xml)/i,
                            message: '流程标识不能以xml开头（不区分大小写）'
                        },
                        {
                            pattern: /^[^.\s]*$/,
                            message: '流程标识不能包含空格和点号'
                        },
                        {
                            max: 64,
                            message: '流程标识长度不能超过64个字符'
                        }
                    ]}
                >
                    <Input placeholder="请输入流程标识，建议使用小写字母和下划线" disabled={isEdit}/>
                </Form.Item>
                <Form.Item
                    name="description"
                    label="描述"
                >
                    <Input.TextArea placeholder="请输入流程描述"/>
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default EditModal;
