"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormMessage,
} from "@/components/ui/form";
import { Icons } from "@/components/icons";
import { InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot } from "@/components/ui/input-otp";
import { useRouter, useSearchParams } from "next/navigation";
import { CardFooter } from "@/components/ui/card";
import { useEffect, useState } from "react";
import apis from "@/utils/apis";
import Loader from "@/components/common/loader";
import { useGlobalContext } from "@/context/Provider";
import { setCookie } from "nookies";




const verificationSchema = z.object({
    otp: z.string().length(6, "Please enter the complete verification code"),
});
type VerificationValues = z.infer<typeof verificationSchema>;


const Verify = () => {

    const searchParams = useSearchParams();
    const router = useRouter()
    const { Toast, setUserInfo } = useGlobalContext()
    const queryParams = Object.fromEntries(searchParams.entries());
    const [loading, setLoading] = useState(false)
    const [countdown, setCountdown] = useState(29);
    const [isResendDisabled, setIsResendDisabled] = useState(true);
    const [isSending, setIsSending] = useState(false);

    const verificationForm = useForm<VerificationValues>({
        resolver: zodResolver(verificationSchema),
        defaultValues: {
            otp: "",
            // marketingConsent: false,
            // termsAccepted: false,
        },
    });






    const onSubmit = async (data: VerificationValues) => {
        try {
            let payload = {
                unique_string: queryParams?.key,
                otp: Number(data.otp),
                is_email_enable: false
            }
            setLoading(true)
            const apiRes = await apis.Auth.verifyOtp(payload)
            setCookie(null, "COOKIES_USER_ACCESS_TOKEN", apiRes?.data?.access_token, {
                path: "/",
            })
            apis.setToken(apiRes?.data?.access_token)
            setUserInfo(apiRes.data)
            Toast.success('Verified successfully!')
            router.replace("/profile")
        } catch (error) {
            verificationForm.setValue('otp', '');
            Toast.error(error)
        } finally {
            setLoading(false)
        }

    };




    const verifyEmailOTP = async (data: any) => {
        try {
            let payload = {
                email: queryParams?.email,
                otp: Number(data.otp),
                type: "FORGOT"
            }
            setLoading(true)
            const apiRes = await apis.Auth.verifyPasswordOtp(payload);
            Toast.success('Email verified successfully!')
            router.push(`/auth/password/reset?email=${apiRes?.data?.email}`)
        } catch (error) {
            Toast.error(error)
        } finally {
            setLoading(false)
        }
    }

    useEffect(() => {
        let timer: NodeJS.Timeout;
        if (isResendDisabled && countdown > 0) {
            timer = setInterval(() => {
                setCountdown((prev) => prev - 1);
            }, 1000);
        } else if (countdown === 0) {
            setIsResendDisabled(false);
        }
        return () => clearInterval(timer);
    }, [countdown, isResendDisabled]);


    const resendOtp = async () => {
        if (isSending || isResendDisabled) return;
        setIsSending(true)
        try {
            setCountdown(29);
            let payload = {
                email: queryParams.email
            }
            const apiRes = await apis.Auth.resendOtp(payload)
            setIsResendDisabled(true)
            Toast.success(apiRes?.data?.message)
        } catch (error) {
            Toast.error(error)
        } finally {
            setIsSending(false);
        }
    }

    return (
        <div className="auth-page h-screen flex items-center justify-center ">
            <div className="w-full max-w-6xl place-items-center  grid grid-cols-1 md:grid-cols-2 gap-8  overflow-hidden">
                {/* Left Section - Hidden on mobile, visible on larger screens */}
                <div className="hidden md:flex  flex-col justify-center items-start md:p-10 lg:p-3  text-white">
                    <span className="mb-8">
                        <Icons.Logo />
                    </span>
                    <p className="text-4xl font-semibold leading-tight lg:text-6xl">OTP verification</p>
                    <p className="text-3xl mt-2  leading-relaxed lg:text-xl">Enter verification code we just sent on your email address {queryParams?.email ? queryParams?.email : "N/A"}</p>
                </div>
                {/* Right Section - Always visible, contains the login form */}
                <div className="flex items-center  max-h-56 justify-center rounded-lg p-8 md:p-10 lg:p-12 bg-white w-full">
                    <section className="w-full">
                        <Form {...verificationForm}>
                            <form onSubmit={queryParams?.type === "forgot" ? verificationForm.handleSubmit(verifyEmailOTP) : verificationForm.handleSubmit(onSubmit)} className="space-y-4">
                                <FormField
                                    name="otp"
                                    control={verificationForm.control}
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormControl>
                                                <InputOTP maxLength={6} value={field.value} onChange={field.onChange}>
                                                    <InputOTPGroup>
                                                        <InputOTPSlot index={0} />
                                                        <InputOTPSlot index={1} />
                                                        <InputOTPSlot index={2} />
                                                    </InputOTPGroup>
                                                    <InputOTPSeparator />
                                                    <InputOTPGroup>
                                                        <InputOTPSlot index={3} />
                                                        <InputOTPSlot index={4} />
                                                        <InputOTPSlot index={5} />
                                                    </InputOTPGroup>
                                                </InputOTP>
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                <div className="flex items-center">
                                    <Button type="button" className="p-0 border-0  shadow-none font-semibold theme-color bg-white" disabled={isResendDisabled} onClick={resendOtp}>Resend?</Button>
                                    <span className="ms-1">{isResendDisabled ? `00:${countdown.toString().padStart(2, "0")}` : ""}</span>
                                </div>
                                <CardFooter className="p-0 mt-4">
                                    <Button type="submit" className="w-full h-11 theme-background text-white"><Loader loading={loading} />Verify email</Button>
                                </CardFooter>
                            </form>
                        </Form>
                    </section>
                </div>
            </div>
        </div>
    );
}



export default Verify;