"use client";
import element1 from "@/assets/auth/auth-element-1.png";
import element2 from "@/assets/auth/auth-element-2.svg";
import element3 from "@/assets/auth/auth-element-3.svg";
import authImage from "@/assets/auth/auth-image.png";
import line from "@/assets/auth/auth-line.svg";
import { useSettings } from "@/context/settingsContext";
import { useT } from "@/context/TranslationContext";
import ApiPath from "@/network/api/apiPath";
import NetworkService from "@/network/service/networkService";
import { decrypt } from "@/utils/crypto";
import { getSettingValue } from "@/utils/utils";
import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useRef, useState } from "react";
import { toast } from "react-toastify";
import LanguageDropdown from "../dashboard/UserDropdown/LanguageDropdown";

const ForgetPasswordOtp = () => {
  const network = new NetworkService();
  const [timeLeft, setTimeLeft] = useState(30);
  const pathname = usePathname();
  const inputRefs = useRef([]);
  const [otp, setOtp] = useState(new Array(6).fill(""));
  const searchParams = useSearchParams();
  const encryptedEmail = searchParams.get("email");
  const email = encryptedEmail ? decrypt(encryptedEmail) : null;
  const router = useRouter();
  const landingUrl = process.env.NEXT_PUBLIC_LANDING_PAGE || "/";
  const { settings } = useSettings();
  const siteLogo = getSettingValue(settings, "site_logo");
  const siteLogoHeight = getSettingValue(settings, "site_logo_height");
  const t = useT();

  // handle otp input
  const handleChange = (e, index) => {
    const value = e.target.value.replace(/\D/g, "");
    const newOtp = [...otp];
    newOtp[index] = value;
    setOtp(newOtp);

    if (value && index < 5) {
      inputRefs.current[index + 1]?.focus();
    }
  };

  // handle backspace
  const handleKeyDown = (e, index) => {
    if (e.key === "Backspace") {
      e.preventDefault();
      const newOtp = [...otp];

      if (newOtp[index]) {
        newOtp[index] = "";
        setOtp(newOtp);
      } else if (index > 0) {
        inputRefs.current[index - 1]?.focus();
        newOtp[index - 1] = "";
        setOtp(newOtp);
      }
    }
  };

  // handle paste
  const handlePaste = (e) => {
    e.preventDefault();
    const pasteData = e.clipboardData.getData("text").replace(/\D/g, "");
    if (!pasteData) return;

    const newOtp = [...otp];
    for (let i = 0; i < 6; i++) {
      newOtp[i] = pasteData[i] || "";
    }
    setOtp(newOtp);
    t;
    const lastFilledIndex = Math.min(pasteData.length, 6) - 1;
    if (lastFilledIndex >= 0) {
      inputRefs.current[lastFilledIndex]?.focus();
    }
  };

  // validate otp
  const validateOtp = () => {
    const isFilled = otp.every((digit) => digit !== "");
    if (!isFilled) {
      toast.error("Please enter all 6 digits of the OTP.");
      return false;
    }
    return true;
  };

  // handle otp submit
  const handleOtpSubmit = async () => {
    if (!validateOtp()) return;
    const fullOtp = otp.join("");
    try {
      const requestBody = { email: email, otp: fullOtp };
      const res = await network.post(ApiPath.resetVerifyOtp, requestBody);
      if (res.status === "completed") {
        toast.success(res.data.message);
        router.push(
          `/auth/login/change-password?email=${encodeURIComponent(
            encryptedEmail,
          )}&otp=${encodeURIComponent(fullOtp)}`,
        );
      }
    } finally {
    }
  };

  return (
    <div className="flex">
      <div className="left w-[40%] xl:w-[35%] 3xl:w-[30%] bg-agent-primary min-h-screen fixed hidden lg:block">
        <div className="left-content">
          <div className="content-part px-[70px] pt-[130px]">
            <div className="ps-[10px] xl:ps-[45px] 2xl:ps-[75px]">
              <h2 className="text-[26px] 2xl:text-[30px] font-bold text-white mb-[10px]">
                {t("authPages.welcomeText")}
              </h2>
              <p className="text-[14px] 2xl:text-[16px] font-medium text-[rgba(255,255,255,0.80)]">
                {t("authPages.welcomeSubText")}
              </p>
            </div>
            <div className="mt-[80px] xl:mt-[123px]">
              <div className="w-full h-auto">
                <Image
                  src={authImage}
                  height={400}
                  width={400}
                  alt="auth image"
                  className="w-full h-auto"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="right w-full lg:w-[60%] xl:w-[65%] 3xl:w-[70%] lg:rtl:mr-[40%] xl:rtl:mr-[35%] 3xl:rtl:mr-[30%] lg:ltr:ml-[40%] xl:ltr:ml-[35%] 3xl:ltr:ml-[30%] min-h-screen relative">
        <div className="absolute top-4 rtl:left-4 ltr:right-4 z-50">
          <LanguageDropdown />
        </div>
        <div className="right-content flex justify-center items-center min-h-screen pt-8 xl:pt-24 pb-8 xl:pb-24">
          <div className="min-w-full sm:min-w-[535px] mx-auto px-4 xl:px-0">
            <div>
              <Link
                href={landingUrl}
                className={`logo block h-[${siteLogoHeight}px] w-auto mb-[40px]`}
              >
                {siteLogo ? (
                  <Image
                    src={siteLogo}
                    unoptimized
                    alt="logo"
                    width={205}
                    height={50}
                    style={{ height: `${siteLogoHeight}px`, width: "auto" }}
                    className="h-full"
                  />
                ) : (
                  <div className="h-[30px] w-[100px] bg-gray-100 animate-pulse rounded"></div>
                )}
              </Link>
              <h3 className="text-[22px] sm:text-[24px] md:text-[30px] font-bold text-agent-text mb-[30px] md:mb-[50px]">
                {t("authPages.verifyOtp")}
              </h3>
              <div className="mb-[30px] md:mb-[50px]">
                <Image
                  src={line}
                  height={100}
                  width={100}
                  alt="element"
                  className="w-full h-auto"
                />
              </div>
              <div className="w-full">
                <form>
                  <div className="grid grid-cols-12 gap-3.5 sm:gap-5">
                    <div className="col-span-12">
                      <div
                        className="flex flex-wrap items-center justify-between gap-3 px-0 sm:px-10"
                        onPaste={handlePaste}
                      >
                        {otp.map((value, index) => (
                          <input
                            key={index}
                            type="text"
                            maxLength={1}
                            value={value}
                            ref={(el) => (inputRefs.current[index] = el)}
                            onChange={(e) => handleChange(e, index)}
                            onKeyDown={(e) => handleKeyDown(e, index)}
                            className={`user-input user-input-3 text-center ${
                              value ? "user-focus" : ""
                            }`}
                          />
                        ))}
                      </div>
                    </div>
                  </div>
                  <div className="mt-5 sm:mt-[30px] lg:mt-[40px] flex flex-col sm:flex-row items-center gap-5">
                    <Link
                      href="/auth/login/forget-password"
                      className="group primary-button primary-button-2 w-full"
                    >
                      <span className="primary-button-hover-effect"></span>
                      <span className="primary-button-text">
                        {t("authPages.back")}
                      </span>
                    </Link>
                    <button
                      type="button"
                      onClick={handleOtpSubmit}
                      className="group primary-button w-full"
                    >
                      <span className="primary-button-hover-effect"></span>
                      <span className="primary-button-text">
                        {t("authPages.verifyOtp")}
                      </span>
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
        <div className="auth-elements">
          <div className="elem1 absolute top-0 rtl:right-0 ltr:left-0 z-[-1]">
            <Image
              src={element1}
              height={100}
              width={100}
              alt="element"
              className="w-[500px] 3xl:w-[610px] h-auto rtl:rotate-180 rtl:scale-y-[-1]"
            />
          </div>
          <div className="elem2 absolute top-0 rtl:left-0 ltr:right-0 hidden sm:block">
            <Image
              src={element2}
              height={100}
              width={100}
              alt="element"
              className="w-[170px] 3xl:w-[223px] h-auto rtl:rotate-180"
            />
          </div>
          <div className="elem3 absolute bottom-0 rtl:right-0 ltr:left-0 hidden lg:block">
            <Image
              src={element3}
              height={100}
              width={100}
              alt="element"
              className="w-[170px] 3xl:w-[223px] h-auto rtl:rotate-180"
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default ForgetPasswordOtp;
