import { Form, ContainerButton } from './styles'
import { Button, Input, Typography, CircularProgress } from '@sofaltaeu/sofaltaeu-components'
import { useForm } from 'react-hook-form'
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useMutation } from 'react-query';
import { recoverPassword } from '../../services';
import { useSwitchFormContext, FormEnum } from '../../context/switchForm';
import Animation from '../Animation'
import sendEmail from '../../../public/email.json'
import { useState } from 'react';

const schema = z.object({
    email: z.string().email('E-mail inválido'),
})
type FormData = z.infer<typeof schema>

interface FormProps {
    dominioSFE: string,
}

export const RecoveryPassword = ({dominioSFE}:FormProps) => {
    const { register, handleSubmit, formState: { errors }, setError } = useForm<FormData>({
        resolver: zodResolver(schema),
        mode: 'onBlur'
    })
    const { handleFormSwitch } = useSwitchFormContext()
    const [isSuccess, setSuccess] = useState(false)
    const mutationRecoverPassword = useMutation(({email}:{email:string})=>recoverPassword({
        apiUrl:dominioSFE,
        email:email
    }),{
        onSuccess:()=>{
            setSuccess(true)
            setTimeout(() => {
                handleFormSwitch(FormEnum.login);
            }, 3000);
        },
        onError: ({response}) => {
            setError('email', { message:response.data.message })
        }
    })

    async function onSubmit(data: FormData){
        await mutationRecoverPassword.mutateAsync({email:data.email})
    }

    if(isSuccess){
        return (
            <Animation
                json={sendEmail}
                text='Enviamos um link para redefinir sua senha'
                maxWidth={250}
            />
        )
    }
    return (
        <Form onSubmit={handleSubmit(onSubmit)}>
            <Typography variant='body2'>Digite seu endereço de e-mail e enviaremos um link para redefinir sua senha</Typography>
            <Input
                label='E-mail'
                variant={errors.email ? 'error' : 'standard'}
                helperText={errors.email?.message}
                required
                type='email'
                {...register('email')}
            />
            <ContainerButton>
                <Button  color='primary' fullWidth onClick={()=>handleFormSwitch(FormEnum.login)} variant="outlined">
                    Voltar
                </Button>
                <Button type='submit' color='primary' fullWidth>
                    {mutationRecoverPassword.isLoading ? <CircularProgress size={24} color='inherit'/> : 'Enviar'}
                </Button>
            </ContainerButton>
        </Form>
    )
}

export default RecoveryPassword