import { memo, useState } from 'react'
import { useForm } from 'antd/lib/form/Form'
import { Form, Input, Modal, FormProps } from 'antd'

import { AuthService, UserDto } from '../services/api'
import { passwordRules, createPasswordRules } from '../utils/validationRules'

import LoaderPortal from './LoaderPortal'
import { invokeWebApiWrapperAsync } from './factory'
import { UserView } from './views'
import { getUserId, getUserLogin } from '../utils/storage'

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

export type ChangePasswordProps = {
    user?: UserDto
    visible?: boolean
    onCancel?: () => void
    onOk?: () => void
}

const fieldRules = [...passwordRules, ...createPasswordRules]

export const ChangePassword = memo<ChangePasswordProps>(({ user, visible, onCancel, onOk }) => {
    const [showLoader, setShowLoader] = useState<boolean>(false)
    const [password, setPassword] = useState<string>('')
    const [isDisabled, setIsDisabled] = useState(true)

    const [form] = useForm()

    const onFormChange = async () => await form.validateFields()
        .then(() => setIsDisabled(false))
        .catch(() => setIsDisabled(true))

    const onModalCancel = () => {
        form.resetFields()
        onCancel?.()
    }

    const onFormFinish = () => invokeWebApiWrapperAsync(
        async() => {
            await AuthService.changePassword(user?.id ?? getUserId() ?? -1, `"${password}"`)
            onOk?.()
        },
        setShowLoader,
        `Не удалось сменить пароль пользователя ${getUserLogin()}`
    )

    return (
        <Modal
            centered
            title={(
                <>
                    Сменить пароль
                    {user && <>&nbsp;(<UserView user={user} />)</>}
                </>
            )}
            visible={visible}
            onCancel={onModalCancel}
            onOk={() => form.submit()}
            okText={'Сохранить'}
            okButtonProps={{
                disabled: isDisabled
            }}
        >
            <LoaderPortal show={showLoader}>
                <Form
                    {...formLayout}
                    form={form}
                    name={'change-password'}
                    onFinish={onFormFinish}
                    onChange={onFormChange}
                >
                    <Form.Item
                        label={'Новый пароль'}
                        name={'new-password'}
                        required={true}
                        rules={fieldRules}
                    >
                        <Input.Password onChange={(e) => setPassword(e.target.value)} value={password} />
                    </Form.Item>
                    <Form.Item
                        label={'Подтверждение пароля'}
                        name={'confirm-password'}
                        required={true}
                        rules={[() => ({ validator(_, value: string) {
                            if (value !== password)
                                return Promise.reject('Пароли не совпадают!')
                            return Promise.resolve()
                        }})]}
                    >
                        <Input.Password />
                    </Form.Item>
                </Form>
            </LoaderPortal>
        </Modal>
    )
})
