import React, { useRef, useState } from 'react';
import { PageContainer, ProTable, ProColumns, ActionType, ModalForm, ProFormText, ProFormSelect } from '@ant-design/pro-components';
import { Button, Tag, Progress, Space, message, Popconfirm } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { queryServerList, addServer, updateServer, removeServer, restartServer } from '@/services/server';
import { ServerItem } from './data';

const ServerManagement: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<ServerItem>();
    const [modalVisible, setModalVisible] = useState<boolean>(false);

    const handleRestart = async (record: ServerItem) => {
        try {
            await restartServer(record.id);
            message.success('重启命令已发送');
            actionRef.current?.reload();
        } catch (error) {
            message.error('重启失败');
        }
    };

    const handleRemove = async (record: ServerItem) => {
        try {
            await removeServer(record.id);
            message.success('删除成功');
            actionRef.current?.reload();
        } catch (error) {
            message.error('删除失败');
        }
    };

    const columns: ProColumns<ServerItem>[] = [
        {
            title: 'ID',
            dataIndex: 'id',
            copyable: true,
            search: false,
        },
        {
            title: '服务器名称',
            dataIndex: 'name',
        },
        {
            title: 'IP 地址',
            dataIndex: 'ip',
        },
        {
            title: '操作系统',
            dataIndex: 'os',
            search: false,
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueEnum: {
                online: { text: '在线', status: 'Success' },
                offline: { text: '离线', status: 'Error' },
                maintenance: { text: '维护中', status: 'Warning' },
            },
        },
        {
            title: 'CPU 使用率',
            dataIndex: 'cpu',
            search: false,
            render: (_, record) => (
                <Progress percent={record.cpu} size="small" status={record.cpu > 80 ? 'exception' : 'active'} />
            ),
        },
        {
            title: '内存 使用率',
            dataIndex: 'memory',
            search: false,
            render: (_, record) => (
                <Progress percent={record.memory} size="small" status={record.memory > 80 ? 'exception' : 'active'} />
            ),
        },
        {
            title: '操作',
            valueType: 'option',
            render: (text, record, _, action) => [
                <a
                    key="edit"
                    onClick={() => {
                        setCurrentRow(record);
                        setModalVisible(true);
                    }}
                >
                    编辑
                </a>,
                <Popconfirm
                    key="restart"
                    title="确认重启?"
                    onConfirm={() => handleRestart(record)}
                >
                    <a>重启</a>
                </Popconfirm>,
                <Popconfirm
                    key="delete"
                    title="确认删除?"
                    onConfirm={() => handleRemove(record)}
                >
                    <a style={{ color: 'red' }}>删除</a>
                </Popconfirm>,
            ],
        },
    ];

    return (
        <PageContainer>
            <ProTable<ServerItem>
                headerTitle="服务器列表"
                actionRef={actionRef}
                rowKey="id"
                search={{
                    labelWidth: 120,
                    layout: 'vertical',
                }}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            setCurrentRow(undefined);
                            setModalVisible(true);
                        }}
                    >
                        <PlusOutlined /> 新建
                    </Button>,
                ]}
                request={async (params, sort, filter) => {
                    const msg = await queryServerList({ ...params, sorter: sort, filter });
                    return {
                        data: msg.data,
                        success: msg.success,
                        total: msg.total,
                    };
                }}
                columns={columns}
            />

            <ModalForm
                key={currentRow?.id || 'new'}
                title={currentRow ? '编辑服务器' : '新建服务器'}
                width="500px"
                open={modalVisible}
                onOpenChange={setModalVisible}
                initialValues={currentRow}
                modalProps={{
                    destroyOnHidden: true
                }}
                onFinish={async (value) => {
                    try {
                        if (currentRow) {
                            await updateServer({ ...currentRow, ...value });
                            message.success('更新成功');
                        } else {
                            await addServer(value as ServerItem);
                            message.success('创建成功');
                        }
                        setModalVisible(false);
                        actionRef.current?.reload();
                        return true;
                    } catch (error) {
                        message.error('操作失败');
                        return false;
                    }
                }}
            >
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '服务器名称是必填项',
                        },
                    ]}
                    name="name"
                    label="服务器名称"
                />
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: 'IP 是必填项',
                        },
                        {
                            pattern: /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/,
                            message: '请输入有效的 IP 地址'
                        }
                    ]}
                    name="ip"
                    label="IP 地址"
                />
                <ProFormText
                    name="os"
                    label="操作系统"
                    initialValue="Ubuntu 22.04 LTS"
                />
                <ProFormSelect
                    name="status"
                    label="状态"
                    valueEnum={{
                        online: '在线',
                        offline: '离线',
                        maintenance: '维护中',
                    }}
                    initialValue="online"
                    rules={[{ required: true, message: '请选择状态' }]}
                />
            </ModalForm>
        </PageContainer>
    );
};

export default ServerManagement;
