import { memo, MouseEventHandler, useState } from 'react'
import { Link, useHistory } from 'react-router-dom'
import { Button, Dropdown, DropDownProps, Menu } from 'antd'
import { UserOutlined } from '@ant-design/icons'

import { getUserLogin, removeUser } from '@utils/storage'

import { ChangePassword } from './ChangePassword'
import { PrivateMenuItemLink } from './Private/PrivateMenuItem'

type UserMenuProps = Omit<DropDownProps, 'overlay'> & { isAdmin?: boolean }

export const UserMenu = memo<UserMenuProps>(({ isAdmin, ...other }) => {
    const [isModalVisible, setIsModalVisible] = useState<boolean>(false)

    const history = useHistory()

    const onChangePasswordClick: MouseEventHandler = (e) => {
      setIsModalVisible(true)
      e.preventDefault()
    }

    const onChangePasswordOk = () => {
        setIsModalVisible(false)
        history.push('/login')
    }

    return (
        <>
            <Dropdown
                {...other}
                placement={'bottomRight'}
                overlay={(
                    <Menu style={{ textAlign: 'right' }}>
                        {isAdmin ? (
                            <PrivateMenuItemLink path={'/'} title={'Вернуться на сайт'}/>
                        ) : (
                            <PrivateMenuItemLink path={'/admin'} title={'Панель администратора'}/>
                        )}
                        <Menu.Item>
                            <Link to={'/'} onClick={onChangePasswordClick}>Сменить пароль</Link>
                        </Menu.Item>
                        <Menu.Item>
                            <Link to={'/login'} onClick={removeUser}>Выход</Link>
                        </Menu.Item>
                    </Menu>
                )}
            >
                <Button icon={<UserOutlined/>}>{getUserLogin()}</Button>
            </Dropdown>
            <ChangePassword
                visible={isModalVisible}
                onOk={onChangePasswordOk}
                onCancel={() => setIsModalVisible(false)}
            />
        </>
    )
})
