"use client";
import React, { useState, useRef, useEffect } from "react";
import Link from "next/link";
import AuthHeader from "@/components/auth/AuthHeader";
import { useSearchParams } from "next/navigation";
import axios from "axios";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { toast, ToastContainer } from "react-toastify";
import { getStoredLocale } from "@/lib/getLocale";
import { decryptData } from "@/lib/cryptoUtils";
import { useAppDispatch, useAppSelector } from "@/app/store/hooks";
import { setUser } from "@/app/store/slices/authSlice";

export default function OTPVerification() {
  const t = useTranslations();

  const dispatch = useAppDispatch();
  const { user } = useAppSelector((state) => state?.auth);

  const [otp, setOtp] = useState(["", "", "", "", "", ""]);
  const inputsRef = useRef<Array<HTMLInputElement | null>>([]);
  const searchParams = useSearchParams();
  const email_or_phone = searchParams.get("email_or_phone") || "";
  const token = searchParams.get("token") || "";
  const type = decryptData(searchParams.get("type") || "");
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);
  const locale = getStoredLocale();
  const [isVerifying, setIsVerifying] = useState(false);
  const [resendTimer, setResendTimer] = useState(120);
  const [resendAvailable, setResendAvailable] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    const extra = searchParams.get("extra");

    if (extra === "register_success") {
      toast.success(t("validation.register_successfully"), {
        autoClose: 3000,
      });
    } else if(extra === "login") {
      toast.error(t("validation.account_not_verified"));
    }
  }, [searchParams, t]);

  useEffect(() => {
    if (resendTimer > 0) {
      const timer = setInterval(() => {
        setResendTimer((prev) => prev - 1);
      }, 1000);
      return () => clearInterval(timer);
    } else {
      setResendAvailable(true);
    }
  }, [resendTimer]);

  useEffect(() => {
    if (!email_or_phone || !type) {
      toast.error(t("validation.missing_parameters"));
      router.push("/login");
      return;
    }
  }, [email_or_phone, token, t, router]);

  const handleOtpChange = (index: number, value: string) => {
    if (!/^[0-9]$/.test(value)) return;
    const newOtp = [...otp];
    newOtp[index] = value;
    setOtp(newOtp);
    // Auto-focus next input
    if (value && index < 5) {
      inputsRef.current[index + 1]?.focus();
    }
  };

  const handleKeyDown = (
    index: number,
    e: React.KeyboardEvent<HTMLInputElement>,
  ) => {
    if (e.key === "Backspace" || e.key === "Delete") {
      e.preventDefault();
      const newOtp = [...otp];
      newOtp[index] = "";
      setOtp(newOtp);
      if (index > 0) {
        inputsRef.current[index - 1]?.focus();
      }
    }
  };

  const isOTPComplete = otp.every((digit) => digit !== "");

  const handleVerifyOTP = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!isOTPComplete) {
      toast.error(t("validation.enter_complete_otp"));
      return;
    }
    setIsSubmitting(true);
    const enteredOTP = otp.join("");
    setIsVerifying(true);
    var urlRedirect = "";
    try {
      const payload = {
        email_or_phone: email_or_phone,
        token: token || "",
        type: type,
        otp: enteredOTP,
      };
      const response = await axios.post(
        `${process.env.NEXT_PUBLIC_API_URL}/verify-email`,
        payload,
        {
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            "Accept-Language": locale,
          },
        },
      );
      setOtp(["", "", "", "", "", ""]);
      if (response.data.status === true) {
        toast.success(t("validation.otp_verified"));
        if (type === "register") {
          urlRedirect = "/login";
        } else if (type === "forgot-password") {
          const searchParams = new URLSearchParams({
            email_or_phone: email_or_phone,
            token: response.data?.data?.token,
          }).toString();
          urlRedirect = `/reset-password?${searchParams}`;
        } else if (type === "login") {
          const userData = response?.data?.data?.token;
          if (userData) {
            dispatch(setUser(response?.data?.data));
          } else {
            toast.error(t(`validation.error_msg`));
          }
        }
      } else {
        console.log("Hii");
        const errMessage = response?.data?.message ?? t(`validation.error_msg`);
        toast.error(errMessage);
      }
    } catch (error: any) {
      console.log("Hello");
      const errMessage =
        error?.response?.data?.message ?? t(`validation.error_msg`);
      toast.error(errMessage);
    } finally {
      setIsVerifying(false);
      setIsSubmitting(false);
      if (urlRedirect) {
        const redurectTimer = setTimeout(() => {
          router.push(urlRedirect);
        }, 2000);
        return () => clearTimeout(redurectTimer);
      }
    }
  };
  // redirect to home page
  useEffect(() => {
    if (user) {
      setTimeout(() => {
        router.replace("/");
      }, 2000);
    }
  }, [user, dispatch]);
  // redirect to home page

  const handleResend = async () => {
    setResendAvailable(false);
    setResendTimer(60);
    try {
      setIsLoading(true);
      const payload = { email_or_phone: email_or_phone, token: token, type };
      const response = await axios.post(
        `${process.env.NEXT_PUBLIC_API_URL}/resend-verification-email`,
        payload,
        {
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            "Accept-Language": locale,
          },
        },
      );
      toast.success(t("validation.otp_resent"));
    } catch (error: any) {
      const errMessage =
        error?.response?.data?.message ?? t(`validation.error_msg`);
      toast.error(errMessage);
    } finally {
      setIsLoading(false);
      setResendTimer(60);
      setResendAvailable(false);
    }
  };

  // for bg-img
  const [isMobile, setIsMobile] = useState(false);
  useEffect(() => {
    const handleResize = () => setIsMobile(window.innerWidth < 580);
    handleResize();
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return (
    <>
      <ToastContainer position="top-right" />
      <div
        className="login-wrapper bg-BlueZodiac text-white bg-cover bg-left lg:bg-center px-4 md:px-6 dark:bg-background"
        style={{
          backgroundImage: isMobile ? "none" : 'url("/login-bg.webp")',
        }}
      >
        <div className="max-w-w1660 mx-auto">
          <div className="flex min-h-screen">
            <div className="w-1/2 hidden lg:flex items-end py-8">
              <div className="hidden lg:block">
                <Link href="/" className="text-4xl font-bold">
                  {t("kanzy")}
                </Link>
                <p className="text-sm mt-2">{t("kanzy_description")}</p>
              </div>
            </div>

            <div className="w-full lg:w-1/2 flex items-center justify-center lg:justify-end pt-16 lg:pt-12 py-8 relative">
              <AuthHeader />
              <div className="w-full max-w-2xl bg-white/30 backdrop-blur-2xl rounded-2xl px-4 sm:px-5 py-8 md:p-10 shadow-xl dark:bg-cardfooter">
                <div className="mb-5 md:mb-7.5">
                  <h2 className="text-xl md:text-2xl lg:text-3xl font-bold mb-2.5 text-center">
                    {t("otp_verification_page.title")}
                  </h2>
                </div>
                <form
                  className="space-y-5 md:space-y-7.5"
                  onSubmit={handleVerifyOTP}
                >
                  <div>
                    <div className="text-center text-sm md:text-base mb-5 md:mb-7.5">
                      {t("otp_verification_page.description")}
                      <p className="underline font-semibold">
                        {email_or_phone}
                      </p>
                    </div>
                    <div className="flex gap-2 md:gap-4 justify-center">
                      {otp.map((digit, i) => (
                        <input
                          key={i}
                          ref={(el) => {
                            inputsRef.current[i] = el;
                          }}
                          type="text"
                          inputMode="numeric"
                          maxLength={1}
                          value={digit}
                          onChange={(e) => {
                            // Only allow numbers
                            const value = e.target.value.replace(/[^0-9]/g, "");
                            handleOtpChange(i, value);
                          }}
                          onKeyDown={(e) => {
                            // Prevent non-numeric input
                            if (
                              !/^[0-9]$/.test(e.key) &&
                              e.key !== "Backspace" &&
                              e.key !== "Delete" &&
                              e.key !== "Tab" &&
                              !e.ctrlKey
                            ) {
                              e.preventDefault();
                            }
                            handleKeyDown(i, e);
                          }}
                          onPaste={(e) => {
                            e.preventDefault();
                            const paste = e.clipboardData.getData("text");
                            const numbers = paste
                              .replace(/[^0-9]/g, "")
                              .split("")
                              .slice(0, 6);
                            if (numbers.length === 0) return;
                            const newOtp = ["", "", "", "", "", ""];
                            let lastFilledIndex = 0;
                            for (let idx = 0; idx < numbers.length; idx++) {
                              newOtp[idx] = numbers[idx];
                              lastFilledIndex = idx;
                            }
                            setOtp(newOtp);
                            setTimeout(() => {
                              inputsRef.current[
                                lastFilledIndex < 5 ? lastFilledIndex + 1 : 5
                              ]?.focus();
                            }, 0);
                          }}
                          className="w-8 h-8 md:w-11 md:h-11 text-center text-sm md:text-base rounded-lg bg-white text-neutrals600 outline-none border border-neutrals200"
                          required
                        />
                      ))}
                    </div>
                    <p className="text-center text-sm mt-3 text-white flex items-center justify-center">
                      {!resendAvailable ? (
                        <>
                          {t("otp_verification_page.not_received_otp")}
                          <span className="block mx-0.5">
                            {t("otp_verification_page.resend_in")}{" "}
                          </span>
                          {String(Math.floor(resendTimer / 60)).padStart(
                            2,
                            "0",
                          )}
                          :{String(resendTimer % 60).padStart(2, "0")}
                        </>
                      ) : (
                        <>
                          {t("otp_verification_page.not_received_otp")}
                          <button
                            type="button"
                            onClick={handleResend}
                            className="text-white underline ms-1"
                          >
                            {t("otp_verification_page.resend_otp")}
                          </button>
                        </>
                      )}
                    </p>
                  </div>
                  <button
                    type="submit"
                    disabled={!isOTPComplete || isVerifying || isSubmitting}
                    className={`w-full py-3 px-4 rounded-lg text-white font-medium ${
                      isOTPComplete
                        ? isVerifying
                          ? "bg-primary500 cursor-not-allowed dark:bg-primary400 dark:text-white"
                          : "bg-primary500 hover:bg-primary600 dark:bg-primary400 dark:text-white"
                        : "bg-gray-400 cursor-not-allowed"
                    } flex items-center justify-center transition-colors duration-200`}
                  >
                    {isVerifying ? (
                      <>
                        <svg
                          className="animate-spin -ml-1 mr-2 h-4 w-4 text-white"
                          xmlns="http://www.w3.org/2000/svg"
                          fill="none"
                          viewBox="0 0 24 24"
                        >
                          <circle
                            className="opacity-25"
                            cx="12"
                            cy="12"
                            r="10"
                            stroke="currentColor"
                            strokeWidth="4"
                          ></circle>
                          <path
                            className="opacity-75"
                            fill="currentColor"
                            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                          ></path>
                        </svg>
                        {t("button.verifying")}
                      </>
                    ) : (
                      t("button.verify")
                    )}
                  </button>
                  <div className="flex justify-center">
                    <Link
                      href={`/${type}`}
                      className="hover:underline dark:hover:text-primary400 hover:text-primary500"
                    >
                      {t("otp_verification_page.go_back")}
                    </Link>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
