import { FC } from 'react'
import Input from '../../../components/Input'
import { useTranslation } from 'react-i18next'
import { 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 '../../../components/Toast';
import { 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?.response?.data?.error?.message[0], 'error')
                },
            })
        },
    })

    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