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

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

const handleLogout = () => {
    localStorage.removeItem('login')
    localStorage.removeItem('token')
}

type UserMenuProps = {
    isAdmin?: boolean
}

export const UserMenu: React.FC<UserMenuProps> = ({ isAdmin }) => {
    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
                placement={'bottomRight'}
                overlay={(
                    <Menu style={{ textAlign: 'right' }}>
                        <PrivateMenuItem roles={'admin'}>
                            {isAdmin ? (
                                <Link to={'/'}>Вернуться на сайт</Link>
                            ) : (
                                <Link to={'/admin'}>Панель администратора</Link>
                            )}
                        </PrivateMenuItem>
                        <Menu.Item>
                            <Link to={'/'} onClick={onChangePasswordClick}>Сменить пароль</Link>
                        </Menu.Item>
                        <Menu.Item>
                            <Link to={'/login'} onClick={handleLogout}>Выход</Link>
                        </Menu.Item>
                    </Menu>
                )}
            >
                <Button icon={<UserOutlined/>}>{localStorage['login']}</Button>
            </Dropdown>
            <ChangePassword
                visible={isModalVisible}
                onOk={onChangePasswordOk}
                onCancel={() => setIsModalVisible(false)}
            />
        </>
    )
}
