import { MouseEventHandler, useState } from 'react'
import { Link, useHistory } from 'react-router-dom'
import { Button, Dropdown, Menu, Modal, Form, Input, FormProps } from 'antd'
import { useForm } from 'antd/lib/form/Form'
import { UserOutlined } from '@ant-design/icons'
import { AuthService } from '../services/api'
import { passwordRules } from '../utils/validationRules'
import { invokeWebApiWrapperAsync } from './factory'
import { PrivateMenuItem } from './Private'
import LoaderPortal from './LoaderPortal'

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

const formLayout: FormProps = { labelCol: { span: 11 }, wrapperCol: { span: 16 } }

type UserMenuProps = {
    isAdmin?: boolean
}

export const UserMenu: React.FC<UserMenuProps> = ({ isAdmin }) => {
    const [form] = useForm()
    const [isModalVisible, setIsModalVisible] = useState<boolean>(false)
    const [showLoader, setShowLoader] = useState<boolean>(false)
    const [password, setPassword] = useState<string>('')

    const history = useHistory()

    const changePassword = () => invokeWebApiWrapperAsync(
      async() => {
        await AuthService.changePassword(localStorage['userId'], `"${password}"`)
        history.push('/login')
      },
      setShowLoader,
      `Не удалось сменить пароль пользователя ${localStorage['login']}`
    )

    const onFormCancel = () => {
      form.resetFields()
      setIsModalVisible(false)
    }

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

    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>
            <Modal
                title={'Сменить пароль'}
                centered
                visible={isModalVisible}
                onCancel={onFormCancel}
                onOk={() => form.submit()}
            >
                <LoaderPortal show={showLoader}>
                <Form
                    {...formLayout}
                    form={form}
                    name={'change-password'}
                    onFinish={changePassword}
                >
                    <Form.Item label={'Новый пароль'} name={'new-password'} rules={passwordRules}>
                        <Input.Password onChange={(e) => setPassword(e.target.value)} value={password} />
                    </Form.Item>
                </Form>
                </LoaderPortal>
            </Modal>
        </>
    )
}
