import { AccessToken } from '@/common/cache';
import { LOGIN_PATH } from '@/requestConfig';
import { KeyOutlined, LogoutOutlined } from '@ant-design/icons';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { history, useModel } from '@umijs/max';
import { Spin } from 'antd';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, { useCallback, useState } from 'react';
import { flushSync } from 'react-dom';
import ChangePassword from '../ChangePassword';
import HeaderDropdown from '../HeaderDropdown';

export type GlobalHeaderRightProps = {
    menu?: boolean;
    children?: React.ReactNode;
};

const loginOut = async () => {
    AccessToken.clear();
    history.replace({ pathname: LOGIN_PATH });
};

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu, children }) => {
    const [showPwdModal, setShowPwdModal] = useState<boolean>(false);
    const { initialState, setInitialState } = useModel('@@initialState');

    const actionClassName = useEmotionCss(({ token }) => {
        return {
            display: 'flex',
            height: '48px',
            marginLeft: 'auto',
            overflow: 'hidden',
            alignItems: 'center',
            padding: '0 8px',
            cursor: 'pointer',
            borderRadius: token.borderRadius,
            '&:hover': {
                backgroundColor: token.colorBgTextHover,
            },
        };
    });

    const onMenuClick = useCallback(
        (event: MenuInfo) => {
            const { key } = event;
            if (key === 'logout') {
                flushSync(() => {
                    setInitialState((s) => ({ ...s, currentUser: undefined }));
                });
                loginOut();
                return;
            }
            if (key === 'password') {
                setShowPwdModal(true);
                return;
            }
            // history.push(`/account/${key}`);
        },
        [setInitialState],
    );

    const loading = (
        <span className={actionClassName}>
            <Spin size="small" style={{ marginLeft: 8, marginRight: 8 }} />
        </span>
    );

    if (!initialState) {
        return loading;
    }

    const { currentUser } = initialState;

    if (!currentUser || !currentUser.name) {
        return loading;
    }

    const menuItems = [
        ...(menu
            ? [
                //   {
                //       key: 'center',
                //       icon: <UserOutlined />,
                //       label: '个人中心',
                //   },
                //   {
                //       key: 'settings',
                //       icon: <SettingOutlined />,
                //       label: '个人设置',
                //   },
                //   {
                //       key: 'password',
                //       icon: <KeyOutlined />,
                //       label: '修改密码',
                //   },
                //   {
                //       type: 'divider' as const,
                //   },
            ]
            : []),
        {
            key: 'password',
            icon: <KeyOutlined />,
            label: '修改密码',
        },
        {
            type: 'divider' as const,
        },
        {
            key: 'logout',
            icon: <LogoutOutlined />,
            label: '退出登录',
        },
    ];

    return (
        <>
            <HeaderDropdown
                menu={{
                    selectedKeys: [],
                    onClick: onMenuClick,
                    items: menuItems,
                }}
            >
                {children}
            </HeaderDropdown>
            {showPwdModal && <ChangePassword onClose={() => setShowPwdModal(false)} />}
        </>
    );
};

export default AvatarDropdown;
