import { type FC } from 'react'
import Input from '../../../components/Input'
import { useTranslation } from 'react-i18next'
import { type CheckHasAccountPhoneType } 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 { useCheckHasAccountRegister, useLoginWithOtp } from '../hooks/useAuthData'
import { toast } from 'react-toastify'
import { type ErrorType } from '../../../helpers/types'

const RegisterStep1: FC = () => {

    const { t } = useTranslation('global')
    const { setPhone, setStepLogin } = useAuthStore()
    const loginWithOtp = useLoginWithOtp()
    const checkHasAccount = useCheckHasAccountRegister()

    const formik = useFormik<CheckHasAccountPhoneType>({
        initialValues: {
            phone: '',
        },
        validationSchema: Yup.object({
            phone: Yup.string()
                .required(t('errors.required'))
        }),
        onSubmit(values) {
            checkHasAccount.mutate(values, {
                onSuccess() {
                    setPhone(values.phone)
                    setStepLogin(2)
                },
                onError(error: ErrorType) {
                    toast.error(error?.response?.data?.error?.message[0])
                },
            })
        },
    })

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


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

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

            </div>


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

export default RegisterStep1