"use client";

import { useEffect, useRef, useState } from "react";
import Button from "../../ui/Button";
import { FiShield } from "react-icons/fi";
import { useModal } from "../../../lib/modal-system/ModalContext";
import useVerifyCurrentEmail from "../../../hooks/features/profile/email/useVerifyCurrentEmail";
import useSendEmailToExisting from "../../../hooks/features/profile/email/useSendEmailToExisting";

const OTP_LENGTH = 6;
const EXPIRE_SECONDS = 5 * 60;
const RESEND_COOLDOWN = 60;

export default function EmailOTPVerification({ email }: { email: string }) {
  const [otp, setOtp] = useState<string[]>(Array(OTP_LENGTH).fill(""));
  const [timer, setTimer] = useState(EXPIRE_SECONDS);
  const [resendCooldown, setResendCooldown] = useState(RESEND_COOLDOWN);
  const { openModal } = useModal();
  const { handleSendEmailToExisting, loading: sendingMail } =
    useSendEmailToExisting();

  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
  const { handleVerifyCurrentEmail, loading } = useVerifyCurrentEmail();

  useEffect(() => {
    if (timer <= 0) return;

    const interval = setInterval(() => {
      setTimer((prev) => prev - 1);
    }, 1000);

    return () => clearInterval(interval);
  }, [timer]);

  useEffect(() => {
    if (resendCooldown <= 0) return;
    const tick = setTimeout(() => setResendCooldown((prev) => prev - 1), 1000);
    return () => clearTimeout(tick);
  }, [resendCooldown]);

  const handleChange = (value: string, index: number) => {
    const digit = value.replace(/\D/g, "").slice(-1);

    const updatedOtp = [...otp];
    updatedOtp[index] = digit;
    setOtp(updatedOtp);

    if (digit && index < OTP_LENGTH - 1) {
      inputRefs.current[index + 1]?.focus();
    }
  };

  const handleKeyDown = (
    e: React.KeyboardEvent<HTMLInputElement>,
    index: number,
  ) => {
    if (e.key === "Backspace" && !otp[index] && index > 0) {
      inputRefs.current[index - 1]?.focus();
    }
  };

  const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
    e.preventDefault();

    const pastedOtp = e.clipboardData
      .getData("text")
      .replace(/\D/g, "")
      .slice(0, OTP_LENGTH);

    const updatedOtp = [...otp];

    pastedOtp.split("").forEach((digit, index) => {
      updatedOtp[index] = digit;
    });

    setOtp(updatedOtp);
  };

  const handleConfirm = async () => {
    const otpValue = otp.join("");
    try {
      await handleVerifyCurrentEmail({ otp: otpValue });
      openModal("ENTER_NEW_MAIL", {});
    } catch (error) {}
  };

  const minutes = Math.floor(timer / 60);
  const seconds = timer % 60;

  const onResend = async () => {
    if (resendCooldown > 0 || sendingMail) return;
    try {
      await handleSendEmailToExisting();
      setResendCooldown(RESEND_COOLDOWN);
    } catch (error) {}
  };

  return (
    <div className="text-center">
      {/* Icon */}
      <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full border border-[#E5D8FF] text-link-1 md:h-16 md:w-16">
        <FiShield size={22} />
      </div>

      {/* Heading */}
      <h2 className="mt-7 font-heading text-xl font-semibold text-heading">
        Confirm it's you
      </h2>

      {/* Description */}
      <p className="mx-auto mt-4 max-w-[320px] font-body text-sm sm:text-base text-text">
        We sent a 6-digit code to your current email
        <br />
        <span className="font-medium text-link-1">{email}</span>
      </p>

      {/* OTP */}
      <div className="mt-8 flex justify-center gap-1.5 sm:gap-3">
        {otp.map((digit, index) => (
          <input
            key={index}
            ref={(el) => {
              inputRefs.current[index] = el;
            }}
            value={digit}
            type="text"
            maxLength={1}
            inputMode="numeric"
            onChange={(e) => handleChange(e.target.value, index)}
            onKeyDown={(e) => handleKeyDown(e, index)}
            onPaste={handlePaste}
            className="h-8 w-8 sm:h-12 sm:w-12 rounded-lg border border-gray-200 text-center text-sm sm:text-lg font-medium outline-none focus:border-link-1"
          />
        ))}
      </div>

      {/* Expiry */}
      {/* <p className="mt-5 text-sm text-text">
        Expires in{" "}
        <span className="font-medium text-link-1">
          {minutes}:{seconds.toString().padStart(2, "0")}
        </span>
      </p> */}

      {/* CTA */}
      <Button
        onClick={handleConfirm}
        className="mt-6 w-full"
        disabled={otp.join("").length !== OTP_LENGTH || loading}
        BtnInnerclassName="text-sm xl:text-lg py-3.5!"
      >
        {loading ? "Verifying..." : "Verify & Continue"}
      </Button>

      {/* Resend */}
      <button
        type="button"
        disabled={resendCooldown > 0 || sendingMail}
        onClick={onResend}
        className="mt-6 text-sm font-medium cursor-pointer text-link-1 disabled:cursor-not-allowed disabled:opacity-50"
      >
        {sendingMail
          ? "Sending…"
          : resendCooldown > 0
            ? `Resend in ${resendCooldown}s`
            : "Resend Code"}
      </button>
    </div>
  );
}
