import Input from '@/components/Input'
import { Button } from '@/components/ui/button'
import React from 'react'
import { useAuthStore } from '../store/AuthStore';
import { useAuthentication } from '../hooks/useAuthData';
import { AuthenticationType } from '../types/Types';
import { useForm } from 'react-hook-form';
import * as yup from "yup"
import { yupResolver } from "@hookform/resolvers/yup"
import { toast } from '@/components/Toast';
import { extractErrorMessage } from '@/helpers/errorUtils';
import LoginStep2 from './LoginStep2';


const LoginStep1 = () => {

    const { step, setStep, setPhone } = useAuthStore();
    const { mutate: authentication, isPending } = useAuthentication();

    const validationSchema = yup
        .object({
            phone: yup.string().required('شماره تلفن خود را وارد کنید'),
        })
        .required()

    const {
        register,
        handleSubmit,
        watch,
        formState: { errors },
    } = useForm<AuthenticationType>({
        resolver: yupResolver(validationSchema),
    })

    const onSubmit = (data: AuthenticationType) => {
        authentication(data, {
            onSuccess: () => {
                toast("کد با موفقیت ارسال شد", "success")
                setPhone(watch("phone"))
                setStep(2)
            },
            onError: (error: Error) => {
                toast(extractErrorMessage(error), 'error')
            }
        })
    }

    if (step === 2) {
        return (
            <LoginStep2 />
        )
    }


    return (
        <div className='flex-1 flex flex-col justify-center px-2 sm:px-0'>
            <div className='text-[#CCCCCC] text-xl sm:text-2xl font-black text-center sm:text-right'>ورود و ثبت نام</div>
            <div className='mt-6 sm:mt-8'>
                <Input
                    placeholder='09120000000'
                    className='text-left h-10 sm:h-11'
                    {...register("phone")}
                    error_text={errors.phone?.message}
                />
            </div>
            <div className='mt-6 sm:mt-8'>
                <Button isLoading={isPending} onClick={handleSubmit(onSubmit)} className='w-full h-10 sm:h-11'>دریافت کد</Button>
            </div>
        </div>
    )
}

export default LoginStep1