"use client";

import { useEffect, useRef, useState } from "react";
import { FiLock } from "react-icons/fi";
import Button from "../../ui/Button";
import { useModal } from "../../../lib/modal-system/ModalContext";
import useVerifyNewMail from "../../../hooks/features/profile/email/useVerifyNewMail";
import useSendNewEmailOtp from "../../../hooks/features/profile/email/useSendNewEmailOtp";

const OTP_LENGTH = 6;
const EXPIRE_SECONDS = 12 * 60 + 43;

export default function NewEmailOtpVerification({ email }: { email: string }) {
  const [otp, setOtp] = useState<string[]>(Array(OTP_LENGTH).fill(""));
  const [timer, setTimer] = useState(EXPIRE_SECONDS);
  const { openModal } = useModal();

  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
  const { handleVerifyNewMail, loading } = useVerifyNewMail();
  const { handleSendNewEmailOtp } = useSendNewEmailOtp();

  useEffect(() => {
    if (timer <= 0) return;

    const interval = setInterval(() => {
      setTimer((prev) => prev - 1);
    }, 1000);

    return () => clearInterval(interval);
  }, [timer]);

  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 nextIndex = Math.min(pastedOtp.length, OTP_LENGTH - 1);

    inputRefs.current[nextIndex]?.focus();
  };

  const handleConfirm = async () => {
    const otpValue = otp.join("");

    if (otpValue.length !== OTP_LENGTH) return;

    try {
      // await handleVerifyNewMail({ email, otp: otpValue });
      openModal("EMAIL_UPDATED", { email });
    } catch (error) {}
  };

  const handleResend = async () => {
    setOtp(Array(OTP_LENGTH).fill(""));
    setTimer(EXPIRE_SECONDS);

    try {
      await handleSendNewEmailOtp({ email });
    } catch (error) {}
  };

  const minutes = Math.floor(timer / 60);
  const seconds = timer % 60;

  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">
        <FiLock size={22} />
      </div>

      {/* Heading */}
      <h2 className="mt-7 font-heading text-2xl font-semibold text-heading">
        Check your email
      </h2>

      {/* Description */}
      <p className="mx-auto mt-4 max-w-[320px] font-body text-base leading-7 text-text">
        We sent a 6-digit code to your current email
        <br />
        <span className="font-medium text-link-1">{email}</span>
      </p>

      {/* OTP Inputs */}
      <div className="mt-8 flex justify-center 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-12 w-12 rounded-lg border border-[#E7E1F5] text-center text-lg font-medium outline-none transition-colors focus:border-link-1"
          />
        ))}
      </div>

      {/* Expiry Timer */}
      <p className="mt-5 text-sm text-heading">
        Expires in{" "}
        <span className="text-link-1">
          {minutes}:{seconds.toString().padStart(2, "0")}
        </span>
      </p>

      {/* Confirm Button */}
      <Button
        onClick={handleConfirm}
        className="mt-8 w-full"
        disabled={otp.join("").length !== OTP_LENGTH || loading}
      >
        Confirm New Email
      </Button>

      {/* Resend */}
      <button
        type="button"
        onClick={handleResend}
        className="mt-6 cursor-pointer text-sm font-medium text-link-1"
      >
        Resend Code
      </button>
    </div>
  );
}
