import { memo, MouseEventHandler, useCallback, useState } from 'react'
import { Link, useHistory, useLocation } 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 location = useLocation()

    const onChangePasswordClick: MouseEventHandler = useCallback((e) => {
      setIsModalVisible(true)
      e.preventDefault()
    }, [])

    const onChangePasswordOk = useCallback(() => {
        setIsModalVisible(false)
        history.push({ pathname: '/login', state: { from: location.pathname }})
    }, [history, location])

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