import { addUser, deleteUser, queryUserList, updateUser } from '@/services/user/api';
import { PlusOutlined } from '@ant-design/icons';
import {
    ActionType,
    ProColumns,
    ProTable,
    QueryFilter,
    ProFormText,
    ProFormSelect,
    PageContainer,
} from '@ant-design/pro-components';
import { Button, message, theme, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import UpdateForm from './components/UpdateForm';

const UserManagement: React.FC = () => {
    const [createModalOpen, handleModalOpen] = useState<boolean>(false);
    const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState<API.UserItem>();
    const [queryParams, setQueryParams] = useState<API.UserParams>({});
    const actionRef = useRef<ActionType>();
    const { token } = theme.useToken();
    const intl = useIntl();

    // Define Mutation Hooks using useRequest
    const { runAsync: runAdd } = useRequest(addUser, { manual: true });
    const { runAsync: runUpdate } = useRequest(updateUser, { manual: true });
    const { runAsync: runDelete, loading: deleteLoading } = useRequest(deleteUser, { manual: true });

    const handleAdd = async (fields: API.UserItem) => {
        const hide = message.loading(intl.formatMessage({ id: 'common.loading' }));
        try {
            await runAdd({ ...fields });
            hide();
            message.success(intl.formatMessage({ id: 'common.success.add' }));
            handleModalOpen(false);
            actionRef.current?.reload();
            return true;
        } catch (error) {
            hide();
            message.error(intl.formatMessage({ id: 'common.error.add' }));
            return false;
        }
    };

    const handleUpdate = async (fields: API.UserItem) => {
        const hide = message.loading(intl.formatMessage({ id: 'common.loading' }));
        try {
            await runUpdate(currentRow?.id || '', fields);
            hide();
            message.success(intl.formatMessage({ id: 'common.success.update' }));
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            actionRef.current?.reload();
            return true;
        } catch (error) {
            hide();
            message.error(intl.formatMessage({ id: 'common.error.update' }));
            return false;
        }
    };

    const handleRemove = async (selectedRow: API.UserItem) => {
        const hide = message.loading(intl.formatMessage({ id: 'common.loading' }));
        try {
            await runDelete(selectedRow.id);
            hide();
            message.success(intl.formatMessage({ id: 'common.success.delete' }));
            actionRef.current?.reload();
            return true;
        } catch (error) {
            hide();
            message.error(intl.formatMessage({ id: 'common.error.delete' }));
            return false;
        }
    };

    const columns: ProColumns<API.UserItem>[] = [
        {
            title: <FormattedMessage id="pages.userManagement.columns.username" />,
            dataIndex: 'username',
            copyable: true,
            ellipsis: true,
        },
        {
            title: <FormattedMessage id="pages.userManagement.columns.realName" />,
            dataIndex: 'realName',
        },
        {
            title: <FormattedMessage id="pages.userManagement.columns.role" />,
            dataIndex: 'role',
            valueEnum: {
                admin: {
                    text: <FormattedMessage id="pages.userManagement.role.admin" />,
                    status: 'Error',
                },
                user: {
                    text: <FormattedMessage id="pages.userManagement.role.user" />,
                    status: 'Success',
                },
            },
        },
        {
            title: <FormattedMessage id="pages.userManagement.columns.status" />,
            dataIndex: 'status',
            valueEnum: {
                active: {
                    text: <FormattedMessage id="pages.userManagement.status.active" />,
                    status: 'Success',
                },
                disabled: {
                    text: <FormattedMessage id="pages.userManagement.status.disabled" />,
                    status: 'Error',
                },
                pending: {
                    text: <FormattedMessage id="pages.userManagement.status.pending" />,
                    status: 'Processing',
                },
            },
        },
        {
            title: <FormattedMessage id="pages.userManagement.columns.mobile" />,
            dataIndex: 'mobile',
        },
        {
            title: <FormattedMessage id="pages.userManagement.columns.createdAt" />,
            dataIndex: 'createdAt',
            valueType: 'dateTime',
            sorter: true,
        },
        {
            title: <FormattedMessage id="pages.userManagement.columns.option" />,
            valueType: 'option',
            key: 'option',
            render: (text, record) => [
                <a
                    key="editable"
                    onClick={() => {
                        setCurrentRow(record);
                        handleUpdateModalOpen(true);
                    }}
                >
                    <FormattedMessage id="common.edit" />
                </a>,
                <Popconfirm
                    key="delete"
                    title={<FormattedMessage id="common.confirm.delete" />}
                    onConfirm={() => handleRemove(record)}
                    okButtonProps={{ loading: deleteLoading }}
                >
                    <a style={{ color: token.colorError }}>
                        <FormattedMessage id="common.delete" />
                    </a>
                </Popconfirm>,
            ],
        },
    ];

    return (
        <PageContainer>
            <QueryFilter<API.UserParams>
                layout="vertical"
                style={{ marginBottom: token.marginLG, background: token.colorBgContainer }}
                onFinish={async (values) => {
                    setQueryParams(values);
                }}
                onReset={() => {
                    setQueryParams({});
                }}
            >
                <ProFormText
                    name="username"
                    label={intl.formatMessage({ id: 'pages.userManagement.columns.username' })}
                />
                <ProFormText
                    name="realName"
                    label={intl.formatMessage({ id: 'pages.userManagement.columns.realName' })}
                />
                <ProFormText
                    name="mobile"
                    label={intl.formatMessage({ id: 'pages.userManagement.columns.mobile' })}
                />
                <ProFormSelect
                    name="role"
                    label={intl.formatMessage({ id: 'pages.userManagement.columns.role' })}
                    valueEnum={{
                        admin: intl.formatMessage({ id: 'pages.userManagement.role.admin' }),
                        user: intl.formatMessage({ id: 'pages.userManagement.role.user' }),
                    }}
                />
                <ProFormSelect
                    name="status"
                    label={intl.formatMessage({ id: 'pages.userManagement.columns.status' })}
                    valueEnum={{
                        active: intl.formatMessage({ id: 'pages.userManagement.status.active' }),
                        disabled: intl.formatMessage({ id: 'pages.userManagement.status.disabled' }),
                        pending: intl.formatMessage({ id: 'pages.userManagement.status.pending' }),
                    }}
                />
            </QueryFilter>
            <ProTable<API.UserItem, API.UserParams>
                headerTitle={intl.formatMessage({ id: 'pages.userManagement.title' })}
                actionRef={actionRef}
                rowKey="id"
                search={false}
                toolBarRender={() => [
                    <Button type="primary" key="primary" onClick={() => handleModalOpen(true)}>
                        <PlusOutlined />
                        <FormattedMessage id="pages.userManagement.form.new" />
                    </Button>,
                ]}
                params={queryParams}
                request={queryUserList}
                columns={columns}
            />
            {/* Create User Drawer */}
            <UpdateForm
                onSubmit={async (value) => {
                    const success = await handleAdd(value);
                    if (success) {
                        handleModalOpen(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                onCancel={(visible) => handleModalOpen(visible)}
                updateModalOpen={createModalOpen}
                values={{}}
                title={intl.formatMessage({ id: 'pages.userManagement.form.new' })}
            />
            {/* Edit User Drawer */}
            <UpdateForm
                onSubmit={async (value) => {
                    const success = await handleUpdate(value);
                    if (success) {
                        handleUpdateModalOpen(false);
                        setCurrentRow(undefined);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                onCancel={(visible) => {
                    handleUpdateModalOpen(visible);
                    if (!visible) setCurrentRow(undefined);
                }}
                updateModalOpen={updateModalOpen}
                values={currentRow || {}}
                title={intl.formatMessage({ id: 'pages.userManagement.form.edit' })}
            />
        </PageContainer>
    );
};

export default UserManagement;
