import { Box, Button, CircularProgress, Container, Fade, Grow, Stack, TextField, Typography } from '@mui/material'
import { useState } from 'react'
import { SubmitHandler, useForm } from 'react-hook-form';
import AuthService from '../../services/AuthService';
import { CheckCircle } from '@mui/icons-material';

interface PasswordResetProps {
    email: string;
}

function PasswordReset() {
    const [success, setSuccess] = useState(false)

    const { register, handleSubmit, watch, setError, formState: { errors, isSubmitting } } = useForm<PasswordResetProps>({
        defaultValues: {
            email: ''
        }
    })

    const onSubmit: SubmitHandler<PasswordResetProps> = async (data) => {
        await AuthService.resetPassword(data.email).then(response => {
            if (response.status === 200) {
                //setError('email', { message: response.data.msg })
                setSuccess(true)
            } else if (response.status === 422) {
                setError('email', { message: response.statusText })
            }
        }).catch((error: Error) => {
            setError('email', { message: error.message })
        })
    }

    return (
        <Container maxWidth="sm">
            <Box my={4}>
                <Typography variant="h4" component="h1" gutterBottom>
                    Восстановление пароля
                </Typography>

                <form onSubmit={handleSubmit(onSubmit)}>
                    {!success && <Fade in={!success}>
                        <Stack spacing={2}>
                            <Typography>
                                Введите адрес электронной почты, на который будут отправлены новые данные для авторизации:
                            </Typography>

                            <TextField
                                fullWidth
                                margin="normal"
                                label="E-mail"
                                required
                                {...register('email', { required: 'Введите E-mail' })}
                                error={!!errors.email}
                                helperText={errors.email?.message}
                            />

                            <Box sx={{ display: 'flex', gap: '16px' }}>
                                <Button fullWidth type="submit" disabled={isSubmitting || watch('email').length == 0} variant="contained" color="primary">
                                    {isSubmitting ? <CircularProgress size={16} /> : 'Восстановить пароль'}
                                </Button>

                                <Button fullWidth href="/auth/signin" type="button" variant="text" color="primary">
                                    Назад
                                </Button>
                            </Box>

                        </Stack>
                    </Fade>}
                    {success &&
                        <Grow in={success}>
                            <Stack spacing={2}>
                                <Stack direction='row' alignItems='center' spacing={2}>
                                    <CheckCircle color='success' />
                                    <Typography>
                                        На указанный адрес было отправлено письмо с новыми данными для авторизации.
                                    </Typography>
                                </Stack>
                                <Box sx={{ display: 'flex', gap: '16px' }}>
                                    <Button fullWidth href="/auth/signin" type="button" variant="contained" color="primary">
                                        Войти
                                    </Button>
                                </Box>
                            </Stack>
                        </Grow>
                    }
                </form>
            </Box>
        </Container>
    )
}

export default PasswordReset