'use client'
import Button from "@/components/ui/Button"
import { OTPInput } from "@/components/ui/OtpInput"
import { yupResolver } from "@hookform/resolvers/yup"
import { useRouter } from "next/navigation"
import { useForm } from "react-hook-form"
import { useSearchParams } from 'next/navigation'
import * as yup from 'yup'
import { decrypt, encrypt } from "@/utils/Crypto"
import { useAuthStore } from "@/zustand/auth/useAuthStore"
import { ROUTES } from "@/utils/Routing"
import { useEffect, useLayoutEffect } from "react"
import { LRFFlowContent } from "@/types/staticContent/lrfflow.content.type"

function VerifyYourEmailForm({ staticContent }: { staticContent: LRFFlowContent["VERIFY_YOUR_EMAIL"] }) {
    const router = useRouter()
    const searchParams = useSearchParams()
    const encryptedEmail = searchParams.get('email')
    const email = encryptedEmail ? decrypt(decodeURIComponent(encryptedEmail)) : ''
    const type = searchParams.get('type')
    const { verifyYourEmail, resendOtp, verifyResetPassword, isLoading, language } = useAuthStore()


    const otpSchema = yup.object({
        otp: yup
            .string()
            .required(staticContent.FORM.OTP_REQUIRED)
            .matches(/^\d{6}$/, staticContent.FORM.OTP_INVALID)
    })
    const {
        control,
        handleSubmit,
        getValues,
        reset,
        formState: { errors }
    } = useForm({
        resolver: yupResolver(otpSchema),
        defaultValues: {
            otp: ''
        }
    })
    useEffect(() => {
        // Forces form to re-validate with new resolver
        reset(
            {

            },
            { keepValues: true, keepDirty: true }
        )
    }, [language, reset, getValues])
    useLayoutEffect(() => {
        if (!email) {
            if (type === 'forgot') {
                router.push(ROUTES.FORGOT_PASSWORD)
                return
            } else if (type === 'register') {

                router.push(ROUTES.REGISTER)
                return
            }
        }
    }, [email, router])
    const onSubmit = (data: any) => {
        const payload = {
            otp: data.otp,
            email
        }
        if (type === 'forgot') {
            verifyResetPassword(payload, (success) => success && router.push(
                `${ROUTES.RESET_PASSWORD}?email=${encodeURIComponent(
                    encrypt(email)
                )}`
            ), true)
            return
        } else if (type === 'register') {

            verifyYourEmail(payload, (success) => success && router.push(ROUTES.LOGIN), true)
        }
    }

    return (
        <>
            <form onSubmit={handleSubmit(onSubmit)}>
                <OTPInput
                    name="otp"
                    control={control}
                    error={errors.otp?.message}
                />

                <span className="flex justify-center items-center gap-2 my-4 lg:my-6 text-grey92">
                    {staticContent.DIDNT_RECEIVE_OTP}{' '}
                    <button
                        type="button"
                        onClick={() =>
                            resendOtp(
                                { email, purpose: type === "forgot" ? "reset" : "verify" },
                                undefined,
                                true
                            )
                        }
                        className="text-primary"
                    >
                        {staticContent.RESEND_OTP}
                    </button>
                </span>


                <Button type="submit" variant="primary" isLoading={isLoading}>{staticContent.VERIFY}</Button>
            </form>
        </>
    )
}

export default VerifyYourEmailForm