import React, {useState} from 'react';
import {Modal, Form, Input, Select, Switch, InputNumber, message} from 'antd';
import type {Environment} from '../types';
import {BuildTypeEnum, DeployTypeEnum} from '../types';
import {createEnvironment, updateEnvironment} from '../service';

interface EnvironmentModalProps {
    open: boolean;
    onCancel: () => void;
    onSuccess: () => void;
    initialValues?: Environment;
}

const EnvironmentModal: React.FC<EnvironmentModalProps> = ({
    open,
    onCancel,
    onSuccess,
    initialValues,
}) => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const isEdit = !!initialValues?.id;

    const handleSubmit = async () => {
        try {
            setLoading(true);
            const values = await form.validateFields();
            if (isEdit) {
                await updateEnvironment({
                    ...values,
                    id: initialValues.id,
                });
            } else {
                await createEnvironment(values);
            }
            message.success(`${isEdit ? '更新' : '创建'}成功`);
            form.resetFields();
            onSuccess();
        } catch (error) {
            if (error instanceof Error) {
                message.error(`${isEdit ? '更新' : '创建'}失败: ${error.message}`);
            } else {
                message.error(`${isEdit ? '更新' : '创建'}失败`);
            }
        } finally {
            setLoading(false);
        }
    };

    return (
        <Modal
            title={`${isEdit ? '编辑' : '新建'}环境`}
            open={open}
            onCancel={() => {
                form.resetFields();
                onCancel();
            }}
            onOk={handleSubmit}
            confirmLoading={loading}
            maskClosable={false}
            destroyOnClose
        >
            <Form
                form={form}
                layout="vertical"
                initialValues={{
                    enabled: true,
                    sort: 0,
                    ...initialValues,
                }}
            >
                <Form.Item
                    name="envCode"
                    label="环境编码"
                    rules={[
                        {required: true, message: '请输入环境编码'},
                        {max: 50, message: '环境编码不能超过50个字符'},
                    ]}
                    tooltip="环境的唯一标识，创建后不可修改"
                >
                    <Input
                        placeholder="请输入环境编码"
                        disabled={isEdit}
                        maxLength={50}
                    />
                </Form.Item>

                <Form.Item
                    name="envName"
                    label="环境名称"
                    rules={[
                        {required: true, message: '请输入环境名称'},
                        {max: 50, message: '环境名称不能超过50个字符'},
                    ]}
                    tooltip="环境的显示名称"
                >
                    <Input
                        placeholder="请输入环境名称"
                        maxLength={50}
                    />
                </Form.Item>

                <Form.Item
                    name="buildType"
                    label="构建类型"
                    rules={[{required: true, message: '请选择构建类型'}]}
                    tooltip="环境的构建类型，创建后不可修改"
                >
                    <Select
                        placeholder="请选择构建类型"
                        disabled={isEdit}
                    >
                        <Select.Option value={BuildTypeEnum.JENKINS}>Jenkins</Select.Option>
                        <Select.Option value={BuildTypeEnum.GITLAB_RUNNER}>GitLab Runner</Select.Option>
                        <Select.Option value={BuildTypeEnum.GITHUB_ACTION}>GitHub Action</Select.Option>
                    </Select>
                </Form.Item>

                <Form.Item
                    name="deployType"
                    label="部署类型"
                    rules={[{required: true, message: '请选择部署类型'}]}
                    tooltip="环境的部署类型，创建后不可修改"
                >
                    <Select
                        placeholder="请选择部署类型"
                        disabled={isEdit}
                    >
                        <Select.Option value={DeployTypeEnum.K8S}>Kubernetes</Select.Option>
                        <Select.Option value={DeployTypeEnum.DOCKER}>Docker</Select.Option>
                        <Select.Option value={DeployTypeEnum.VM}>虚拟机</Select.Option>
                    </Select>
                </Form.Item>

                <Form.Item
                    name="envDesc"
                    label="环境描述"
                    rules={[{max: 200, message: '环境描述不能超过200个字符'}]}
                    tooltip="环境的详细描述信息"
                >
                    <Input.TextArea
                        placeholder="请输入环境描述"
                        maxLength={200}
                        showCount
                        rows={4}
                    />
                </Form.Item>

                <Form.Item
                    name="enabled"
                    label="状态"
                    valuePropName="checked"
                    tooltip="是否启用该环境"
                >
                    <Switch checkedChildren="启用" unCheckedChildren="禁用"/>
                </Form.Item>

                <Form.Item
                    name="sort"
                    label="排序"
                    tooltip="数字越小越靠前"
                >
                    <InputNumber min={0} style={{width: '100%'}}/>
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default EnvironmentModal;
