import { FC } from 'react'
import { useTranslation } from 'react-i18next'
import Input from '../../../components/Input'
import { useFormik } from 'formik'
import { ForgotPasswordType } from '../types/AuthTypes'
import * as Yup from 'yup'
import Button from '../../../components/Button'
import { useForgotPassword } from '../hooks/useAuthData'
import { toast } from '../../../components/Toast'
import { ErrorType } from '../../../helpers/types'

type Props = {
    changeStep: (value: number) => void,
    changeEmail: (value: string) => void,
}

const ForgotStep1: FC<Props> = ({ changeStep, changeEmail }) => {

    const { t } = useTranslation('global')
    const { mutate, isPending } = useForgotPassword()
    const formik = useFormik<ForgotPasswordType>({
        initialValues: {
            email: ''
        },
        validationSchema: Yup.object({
            email: Yup.string().email(t('errors.format_email_error')).required(t('errors.required'))
        }),
        onSubmit: (values) => {
            mutate(values, {
                onSuccess: (data) => {
                    toast(data?.data?.message)
                    changeEmail(values.email)
                    changeStep(2)
                },
                onError: (error: ErrorType) => {
                    toast(error.response?.data?.error.message[0])
                }
            })
        }
    })

    return (
        <div className='mt-5'>
            <h2 className='text-2xl font-bold'>
                {t('auth.welcome_forgot')}
            </h2>
            <p className='text-description text-sm mt-2'>
                {t('auth.enter_info_forgot')}
            </p>

            <div className='mt-16'>
                <Input
                    label={t('email')}
                    {...formik.getFieldProps('email')}
                    error_text={formik.touched.email && formik.errors.email ? formik.errors.email : ''}
                />
            </div>

            <Button
                label={t('auth.next')}
                className='mt-8'
                onClick={() => formik.handleSubmit()}
                isLoading={isPending}
            />
        </div>
    )
}

export default ForgotStep1