import { FormEventHandler, useCallback } from 'react'
import { Button, Form } from 'react-bootstrap'

import { useSignIn, useSignUp } from '../hooks/api'
import { composeSignUpBody } from '../api/signup'
import { composeSignInBody } from '../api/token'

type AuthFormProps = {
    register: boolean,
    goBack: () => void,
}

function AuthForm({ goBack, register }: AuthFormProps) {
    const { handleSignUp, signUpButton } = useSignUp()

    const { handleSignIn, signInButton } = useSignIn()

    const handleAuth: FormEventHandler<HTMLFormElement> = useCallback((e) => {
        e.preventDefault()
        e.stopPropagation()

        const formData = new FormData(e.currentTarget)

        void (async () => {
            const accountCreated = register ? (
                await handleSignUp(composeSignUpBody(formData))
            ) : true

            if (accountCreated) {
                if (await handleSignIn(composeSignInBody(formData))) {
                    goBack()
                }
            }

        })()
    }, [register, goBack, handleSignUp, handleSignIn])

    return (
        <Form onSubmit={handleAuth}>
            <Form.Group className='mb-3' controlId='email'>
                <Form.Label>Почта</Form.Label>
                <Form.Control name='email' type='email' required />
            </Form.Group>

            {register && <>
                <Form.Group className='mb-3' controlId='name'>
                    <Form.Label>Имя</Form.Label>
                    <Form.Control name='name' type='text' required />
                </Form.Group>

                <Form.Group className='mb-3' controlId='surname'>
                    <Form.Label>Фамилия</Form.Label>
                    <Form.Control name='surname' type='text' required />
                </Form.Group>
            </>}

            <Form.Group className='mb-3' controlId='password'>
                <Form.Label>Пароль</Form.Label>
                <Form.Control name='password' type='password' required />
            </Form.Group>

            {register &&
                <Form.Group className='mb-3' controlId='privacyPolicyConsent'>
                    <Form.Check>
                        <Form.Check.Input type='checkbox' required />
                        <Form.Check.Label>
                            Я согласен с <a href={`${document.location.origin}/privacy_policy.pdf`} target='_blank'>условиями обработки персональных данных</a>
                        </Form.Check.Label>
                    </Form.Check>
                </Form.Group>
            }

            <Button variant='success' type='submit' {
                ...(register ? signUpButton : signInButton)
            } />
        </Form>
    )
}

export default AuthForm
