import { type FC } from 'react'
import Input from '../../../components/Input'
import { useTranslation } from 'react-i18next'
import { type CheckHasAccountType } from '../types/AuthTypes'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { useAuthStore } from '../store/AuthStore'
import Error from '../../../components/Error'
import Button from '../../../components/Button'
import { useCheckHasAccount } from '../hooks/useAuthData'
import { toast } from 'react-toastify'
import { type ErrorType } from '../../../helpers/types'

const RegisterStep1: FC = () => {

    const { t } = useTranslation('global')
    const { setEmail } = useAuthStore()
    const checkHasAccount = useCheckHasAccount()

    const formik = useFormik<CheckHasAccountType>({
        initialValues: {
            email: '',
        },
        validationSchema: Yup.object({
            email: Yup.string()
                .email(t('errors.invalid_email'))
                .required(t('errors.required'))
        }),
        onSubmit(values) {
            checkHasAccount.mutate(values, {
                onSuccess() {
                    setEmail(values.email)
                    // Redirect to register step 2 or handle as needed
                },
                onError(error: ErrorType) {
                    toast.error(error?.response?.data?.error?.message[0])
                },
            })
        },
    })

    return (
        <div className='flex-1'>

            <div className='mt-16'>
                <Input
                    label={t('auth.email')}
                    placeholder={t('auth.enter_email')}
                    type='email'
                    className='text-right'
                    name='email'
                    onChange={formik.handleChange}
                    value={formik.values.email}
                />

                {
                    formik.touched.email && formik.errors.email &&
                    <Error
                        errorText={formik.errors.email}
                    />
                }

            </div>

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

export default RegisterStep1