"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 { useEffect, useState } from "react";
import apis from "@/utils/apis";
import { destroyCookie, setCookie } from "nookies";
import { useGlobalContext } from "@/context/Provider";
import { useRouter, useSearchParams } from "next/navigation";
import Loader from "@/components/common/loader";
import { COOKIES_USER_ACCESS_TOKEN } from "@/context/actionTypes";
import AuthLayout from "@/components/layout/layout";
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSlot,
} from "@/components/ui/input-otp";
import authBanner from "@/assets/images/AuthImages/auth.png";
import { maskEmail } from "@/lib/utils";

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

const Login = () => {
  const searchParams = useSearchParams();
  const router = useRouter();
  const queryParams = Object.fromEntries(searchParams.entries());
  const { setUserInfo, Toast, requestNotification } = useGlobalContext();
  const [loading, setLoading] = useState(false);
  const [otp, setOtp] = useState("");
  const [isSending, setIsSending] = useState(false);
  const verificationForm = useForm<VerificationValues>({
    resolver: zodResolver(verificationSchema),
    defaultValues: {
      otp: "",
      // marketingConsent: false,
      // termsAccepted: false,
    },
  });
  let email = sessionStorage.getItem("email");
  function getDeviceType() {
    const userAgent = navigator.userAgent.toLowerCase();
    const width = window.screen.width;
    const height = window.screen.height;
    if (/mobile/i.test(userAgent)) {
      return "mobile";
    } else if (/tablet/i.test(userAgent)) {
      return "tablet";
    } else if (width > 1024 && height <= 800) {
      return "laptop";
    } else {
      return "computer";
    }
  }

  const handleSubmit = async (data: any) => {
    try {
      let payload: any = {
        otp: otp,
      };
      setLoading(true);
      const fcm_token = await requestNotification();
      if (fcm_token) {
        payload['fcm_token'] = fcm_token;
      }
      const system_type = getDeviceType();
      if (system_type) {
        payload['system_type'] = system_type;
      }
      const apiRes = await apis.Auth.VerifyE(payload);
      if (apiRes) {
        const token = sessionStorage.getItem("token");
        if (token) {
          setCookie(null, COOKIES_USER_ACCESS_TOKEN, token, {
            path: "/",
          });
        }
        localStorage.removeItem("cartItems");
        router.replace("/home");
        sessionStorage.removeItem("email");
        sessionStorage.removeItem("otpTokenEmail");
      }
    } catch (error) {
      Toast.error(error);
      setOtp('')
    } finally {
      setLoading(false);
    }
  };

  const [countdown, setCountdown] = useState(29);
  const [isResendDisabled, setIsResendDisabled] = useState(true);
  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: email,
      };
      const apiRes = await apis.Profile.UpdateProfile(payload);
      setIsResendDisabled(true);
      sessionStorage.setItem("otpTokenEmail", apiRes?.token);
      Toast.success("Otp sent successfully!");
    } catch (error) {
      Toast.error(error);
      setOtp('')
    } finally {
      setIsSending(false);
    }
  };
  return (
    <>
      <section className="w-full ">
        {/* <Form {...verificationForm}>
          <form onSubmit={verificationForm.handleSubmit(onSubmit)} className="">
            <FormField
              name="otp"
              control={verificationForm.control}
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormControl className="w-full">
                    <InputOTP
                      className="w-full"
                      maxLength={4}
                      value={field.value}
                      onChange={field.onChange}
                    >
                      {[...Array(4)].map((_, index) => (
                        <InputOTPGroup key={index}>
                          <InputOTPSlot
                            index={index}
                            className="h-14 w-14 rounded-md border border-gray-300 bg-white text-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                          />
                        </InputOTPGroup>
                      ))}
                    </InputOTP>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="mt-4 p-0">
              <Button
                type="submit"
                className="theme-background h-11 w-full text-white"
              >
                <Loader loading={loading} />
                Verify
              </Button>
            </div>
            <div className="mt-0 flex w-full flex-col items-center justify-start">
              <span className="mb-2 mt-3">
                {isResendDisabled ? (
                  `Didn’t receive the OTP? Retry in 00:${countdown
                    .toString()
                    .padStart(2, '0')}`
                ) : (
                  <Button
                    type="button"
                    variant="link"
                    className="theme-color m-0 flex items-center border-0 bg-white p-0 font-semibold text-black shadow-none"
                    disabled={isResendDisabled}
                    onClick={resendOtp}
                  >
                    Resend Otp
                  </Button>
                )}
              </span>
            </div>
          </form>
        </Form> */}
        <div className="bg-white p-6 rounded-xl shadow-md">
          <h2 className="text-lg font-semibold">Verify your</h2>
          <h1 className="text-3xl font-[500] ">Email</h1>

          <span className="block mt-4 mb-4 text-sm text-gray-500">
            Please input the 4-digit code that has been sent to you via
            email {' ' + maskEmail(email)}.
          </span>
          <InputOTP
            className="w-full"
            maxLength={4}
            value={otp}
            onChange={setOtp}
          >
            {[...Array(4)].map((_, index) => (
              <InputOTPGroup key={index} className="rounded-full">
                <InputOTPSlot
                  index={index}
                  className="h-14 w-14 rounded-full border border-gray-300 bg-white text-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </InputOTPGroup>
            ))}
          </InputOTP>
          <span className="block mt-2 mb-3 text-sm text-gray-500">
            <span className="mb-2 mt-3">
              {isResendDisabled ? (
                `Didn’t receive the OTP? Retry in 00:${countdown
                  .toString()
                  .padStart(2, "0")}`
              ) : (
                <Button
                  type="button"
                  variant="link"
                  className="theme-color m-0 flex items-center border-0 bg-white p-0 font-semibold text-black shadow-none"
                  disabled={isResendDisabled}
                  onClick={resendOtp}
                >
                  Resend Otp
                </Button>
              )}
            </span>
          </span>
          {/* <button className="mt-6 w-full bg-yellow-400 text-black py-2 rounded-lg font-medium hover:bg-yellow-500 transition">
            Verify and Proceed
          </button> */}
          <Button
            // onClick={() => router.push("/home")}
            onClick={handleSubmit}
            className="theme-background mt-6 btn-text-color h-11 w-full text-white"
            variant={"default"}
          >
            <Loader loading={loading} />
            Verify and Proceed
          </Button>
        </div>
      </section>
    </>
  );
};

export default function LoginPage() {
  const phone: any = sessionStorage.getItem("phone");
  return (
    <AuthLayout backgroundImage={authBanner.src}>
      <Login />
    </AuthLayout>
  );
}
