import { FC, useEffect } from 'react'
import { useAuthentication, useVerifyOtp } from '../hooks/useAuthData'
import { Button } from '@/components/ui/button'
import OTPInput from 'react-otp-input'
import { useForm } from 'react-hook-form'
import { VerifyOtpType } from '../types/Types'
import * as yup from "yup"
import { yupResolver } from "@hookform/resolvers/yup"
import { useAuthStore } from '../store/AuthStore'
import { toast } from '@/components/Toast'
import { extractErrorMessage } from '@/helpers/errorUtils'
import Error from '@/components/Error'
import { setRefreshToken, setToken } from '@/config/func'
import { useCountDown } from '@/hooks/useCountDown'
import { useBulkAddCart } from '@/app/cart/hooks/useCartData'
import { useLocalCart } from '@/app/product/hooks/useLocalCart'
import { useSharedStore } from '@/share/store/sharedStore'

const LoginStep2: FC = () => {

    const { phone } = useAuthStore()
    const { isPending, mutate: verifyOtp } = useVerifyOtp()
    const { mutate: authentication, isPending: isAuthenticationPending } = useAuthentication();
    const { mutate: bulkAddCart } = useBulkAddCart()
    const { getLocalCartItems, clearLocalCart } = useLocalCart()
    const { setIsLogin } = useSharedStore()

    const { value: countdownValue, reset: resetCountdown } = useCountDown(2, true, () => {
        // When countdown ends, enable resend button
    })

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

    const {
        handleSubmit,
        watch,
        setValue,
        formState: { errors },
    } = useForm<VerifyOtpType>({
        resolver: yupResolver(validationSchema),
        defaultValues: {
            phone: phone,
        },
    })

    const onSubmit = (data: VerifyOtpType) => {
        verifyOtp(data, {
            onSuccess: (data) => {
                toast('ورود با موفقیت انجام شد', 'success')
                setToken(data?.results?.data?.accessToken?.token)
                setRefreshToken(data?.results?.data?.refreshToken?.token)
                setIsLogin(true)

                // همگام‌سازی سبد خرید آفلاین
                const localCartItems = getLocalCartItems()
                if (localCartItems.length > 0) {
                    const bulkItems = localCartItems.map(item => ({
                        productId: item.productId,
                        variantId: item.variantId,
                        quantity: item.quantity
                    }))

                    bulkAddCart({ items: bulkItems }, {
                        onSuccess: () => {
                            toast('سبد خرید آفلاین با موفقیت همگام‌سازی شد', 'success')
                            clearLocalCart()
                        },
                        onError: (error) => {
                            toast(extractErrorMessage(error), 'error')
                        }
                    })
                }

                window.location.href = '/'

            },
            onError: (error: Error) => {
                toast(extractErrorMessage(error), 'error')
            }
        })
    }

    const handleResendOtp = () => {
        authentication({
            phone: phone,
        }, {
            onSuccess: () => {
                resetCountdown()
                toast('کد جدید ارسال شد', 'success')
            }
        })
    }

    useEffect(() => {
        if (watch('otpCode')?.length === 5) {
            onSubmit({
                otpCode: watch('otpCode'),
                phone: phone,
            })
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [watch('otpCode')])

    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 dltr otp'>
                <OTPInput
                    shouldAutoFocus
                    value={watch("otpCode")}
                    numInputs={5}
                    inputType='tel'
                    containerStyle={{ direction: 'ltr' }}
                    onChange={(otp: string) => setValue('otpCode', otp)}
                    renderInput={(props) =>
                        <input
                            {...props}
                            type='tel'
                            autoComplete="one-time-code"
                            inputMode="numeric"
                            className='w-full h-[45px] sm:h-[50px] flex-1 mx-1 sm:mx-2 bg-white border rounded-[10px] text-center text-lg sm:text-xl' />
                    }
                />
            </div>
            {
                errors.otpCode?.message && <Error errorText={errors.otpCode.message} />
            }
            <div className='mt-6 sm:mt-8'>
                <Button isLoading={isPending} className='w-full h-10 sm:h-11' onClick={handleSubmit(onSubmit)}>تایید</Button>
            </div>

            {/* Countdown and Resend Section */}
            <div className='mt-4 sm:mt-6'>
                <div className='flex flex-col sm:flex-row items-center justify-between gap-2 sm:gap-0'>
                    <span className='text-[#CCCCCC] text-xs sm:text-sm text-center sm:text-right'>کد فعالسازی را دریافت نکردید؟</span>
                    {countdownValue !== '00:00' ? (
                        <span className='text-primary font-medium text-xs sm:text-sm'>{countdownValue}</span>
                    ) : (
                        <Button
                            variant={'ghost'}
                            isLoading={isAuthenticationPending}
                            onClick={handleResendOtp}
                            className='text-primary hover:text-primary/80 cursor-pointer text-xs sm:text-sm font-medium transition-colors'
                        >
                            دوباره امتحان کنید
                        </Button>
                    )}
                </div>
            </div>
        </div>
    )
}

export default LoginStep2