import { LoginVerifyOTPType } from '@/app/auth/login/types/Types'
import React from 'react'
import OTPInput from 'react-otp-input'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { useTranslation } from 'react-i18next'
import { useOtpVerify } from '@/app/auth/login/hooks/useAuthData'
import { toast } from '@/components/Toast'
import Button from '@/components/button/PrimaryButton'
import { extractErrorMessage } from '@/lib/func'
import { useReceiptStore } from '@/zustand/receiptStore'
import { useBulkCart } from '@/app/[name]/(Dialogs)/cart/hooks/useCartData'
import { setRefreshToken, setToken } from '@/lib/api/func'
import { useSearchParams } from 'next/navigation'


type Props = {
    phone: string,
    slug: string
}

const StepOtp = ({ phone, slug }: Props) => {
    const searchParams = useSearchParams()
    const redirectUrl = searchParams.get('redirect')
    const { t } = useTranslation('auth')
    const { mutate: mutateOtpVerify, isPending } = useOtpVerify()

    const { items, clear } = useReceiptStore()
    const { mutate: mutateBulkCart, isPending: isBulkCartPending } = useBulkCart()

    const getRedirectPath = () => {
        if (redirectUrl) {
            return decodeURIComponent(redirectUrl)
        }
        return `/${slug}`
    }

    const formik = useFormik<LoginVerifyOTPType>({
        initialValues: {
            phone: phone,
            otp: '',
            slug: slug
        },
        validationSchema: Yup.object({
            otp: Yup.string().required(t('Errors.OTPRequired'))
        }),
        onSubmit: (values) => {
            mutateOtpVerify(values, {
                onSuccess: (data) => {
                    toast(t('otp_verified'), 'success')
                    setToken(data?.data?.tokens?.accessToken?.token as string)
                    setRefreshToken(data?.data?.tokens?.refreshToken?.token as string)

                    if (Object.keys(items).length > 0) {
                        const bulkCartItems = Object.entries(items).map(([variantId, value]) => {
                            if (value.quantity > 0) {
                                return {
                                    variantId,
                                    quantity: value.quantity
                                }
                            }
                            return undefined
                        }).filter((item): item is { variantId: string; quantity: number } => item !== undefined)
                        if (!!bulkCartItems.length) {
                            mutateBulkCart({ items: bulkCartItems }, {
                                onSuccess: () => {
                                    clear()
                                    window.location.href = getRedirectPath()
                                },
                                onError: (error) => {
                                    clear()
                                    window.location.href = getRedirectPath()
                                    toast(extractErrorMessage(error), 'error')
                                }
                            })
                        } else {
                            window.location.href = getRedirectPath()
                        }
                    } else {
                        window.location.href = getRedirectPath()
                    }


                },
                onError: (error) => {
                    toast(extractErrorMessage(error), 'error')
                }
            })
        }
    })
    return (
        <div className='mt-6 sm:mt-8 dltr otp'>
            <OTPInput
                shouldAutoFocus
                value={formik.values.otp}
                numInputs={5}
                inputType='tel'
                containerStyle={{ direction: 'ltr' }}
                onChange={(otp: string) => formik.setFieldValue('otp', 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-container border border-border text-foreground outline-0 rounded-[10px] text-center text-sm' />
                }
            />

            <Button
                className='mt-10 dark:bg-white dark:text-black hover:dark:bg-white'
                disabled={!formik.isValid}
                pending={isPending || isBulkCartPending}
                type='button'
                onClick={() => formik.handleSubmit()}
            >
                {t('OTP.ButtonSubmit')}
            </Button>
        </div>
    )
}

export default StepOtp