import React, {useState} from 'react';
import {PageContainer} from '@ant-design/pro-components';
import {Button, Space, Popconfirm, Tag, App, Select} from 'antd';
import {PlusOutlined, EditOutlined, DeleteOutlined} from '@ant-design/icons';
import {getEnvironmentPage, deleteEnvironment} from './service';
import type {Environment, EnvironmentQueryParams} from './types';
import {BuildTypeEnum, DeployTypeEnum} from './types';
import {getBuildTypeInfo, getDeployTypeInfo} from './utils';
import EnvironmentModal from './components/EnvironmentModal';
import {ProTable} from '@ant-design/pro-components';
import type {ProColumns, ActionType} from '@ant-design/pro-components';

const EnvironmentList: React.FC = () => {
    const [modalVisible, setModalVisible] = useState(false);
    const [currentEnvironment, setCurrentEnvironment] = useState<Environment>();
    const actionRef = React.useRef<ActionType>();
    const {message: messageApi} = App.useApp();

    const handleDelete = async (id: number) => {
        try {
            await deleteEnvironment(id);
            messageApi.success('删除成功');
            actionRef.current?.reload();
        } catch (error) {
            messageApi.error('删除失败');
        }
    };

    const handleAdd = () => {
        setCurrentEnvironment(undefined);
        setModalVisible(true);
    };

    const handleEdit = (environment: Environment) => {
        setCurrentEnvironment(environment);
        setModalVisible(true);
    };

    const handleModalClose = () => {
        setModalVisible(false);
        setCurrentEnvironment(undefined);
    };

    const handleSuccess = () => {
        setModalVisible(false);
        setCurrentEnvironment(undefined);
        actionRef.current?.reload();
    };

    const columns: ProColumns<Environment>[] = [
        {
            title: '环境编码',
            dataIndex: 'envCode',
            width: 120,
            copyable: true,
            ellipsis: true,
            fixed: 'left',
        },
        {
            title: '环境名称',
            dataIndex: 'envName',
            width: 150,
            ellipsis: true,
        },
        {
            title: '环境描述',
            dataIndex: 'envDesc',
            ellipsis: true,
        },
        {
            title: '构建类型',
            dataIndex: 'buildType',
            width: 120,
            render: (buildType) => {
                const typeInfo = getBuildTypeInfo(buildType as BuildTypeEnum);
                return (
                    <Tag color={typeInfo.color}>
                        <Space>
                            {typeInfo.icon}
                            {typeInfo.label}
                        </Space>
                    </Tag>
                );
            },
            filters: [
                {text: 'Jenkins构建', value: BuildTypeEnum.JENKINS},
                {text: 'GitLab Runner构建', value: BuildTypeEnum.GITLAB_RUNNER},
                {text: 'GitHub Action构建', value: BuildTypeEnum.GITHUB_ACTION},
            ],
            filterMode: 'menu',
            filtered: false,
        },
        {
            title: '部署类型',
            dataIndex: 'deployType',
            width: 120,
            render: (deployType) => {
                const typeInfo = getDeployTypeInfo(deployType as DeployTypeEnum);
                return (
                    <Tag color={typeInfo.color}>
                        <Space>
                            {typeInfo.icon}
                            {typeInfo.label}
                        </Space>
                    </Tag>
                );
            },
            filters: [
                {text: 'Kubernetes集群部署', value: DeployTypeEnum.K8S},
                {text: 'Docker容器部署', value: DeployTypeEnum.DOCKER},
                {text: '虚拟机部署', value: DeployTypeEnum.VM},
            ],
            filterMode: 'menu',
            filtered: false,
        },
        {
            title: '状态',
            dataIndex: 'enabled',
            width: 100,
            valueEnum: {
                true: {text: '启用', status: 'Success'},
                false: {text: '禁用', status: 'Default'},
            },
        },
        {
            title: '排序',
            dataIndex: 'sort',
            width: 80,
            sorter: true,
        },
        {
            title: '操作',
            width: 180,
            key: 'action',
            valueType: 'option',
            fixed: 'right',
            render: (_, record) => [
                <Button
                    key="edit"
                    type="link"
                    onClick={() => handleEdit(record)}
                >
                    <Space>
                        <EditOutlined/>
                        编辑
                    </Space>
                </Button>,
                <Popconfirm
                    key="delete"
                    title="确定要删除该环境吗？"
                    description="删除后将无法恢复，请谨慎操作"
                    onConfirm={() => handleDelete(record.id)}
                >
                    <Button
                        type="link"
                        danger
                    >
                        <Space>
                            <DeleteOutlined/>
                            删除
                        </Space>
                    </Button>
                </Popconfirm>
            ],
        },
    ];

    return (
        <PageContainer
            header={{
                title: '环境管理'
            }}
        >
            <ProTable<Environment>
                columns={columns}
                actionRef={actionRef}
                scroll={{x: 'max-content'}}
                cardBordered
                rowKey="id"
                search={false}
                options={{
                    setting: false,
                    density: false,
                    fullScreen: false,
                    reload: false,
                }}
                toolbar={{
                    actions: [
                        <Button
                            key="add"
                            type="primary"
                            onClick={handleAdd}
                            icon={<PlusOutlined/>}
                        >
                            新建环境
                        </Button>
                    ],
                }}
                form={{
                    syncToUrl: true,
                }}
                pagination={{
                    pageSize: 10,
                    showQuickJumper: true,
                }}
                request={async (params) => {
                    try {
                        const queryParams: EnvironmentQueryParams = {
                            pageSize: params.pageSize,
                            pageNum: params.current,
                            envCode: params.envCode as string,
                            envName: params.envName as string,
                            buildType: params.buildType as BuildTypeEnum,
                            deployType: params.deployType as DeployTypeEnum,
                        };
                        const data = await getEnvironmentPage(queryParams);
                        return {
                            data: data.content || [],
                            success: true,
                            total: data.totalElements || 0,
                        };
                    } catch (error) {
                        messageApi.error('获取环境列表失败');
                        return {
                            data: [],
                            success: false,
                            total: 0,
                        };
                    }
                }}
            />

            {modalVisible && (
                <EnvironmentModal
                    open={modalVisible}
                    onCancel={handleModalClose}
                    onSuccess={handleSuccess}
                    initialValues={currentEnvironment}
                />
            )}
        </PageContainer>
    );
};

export default EnvironmentList;
