"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { toast } from "sonner";
import AuthCard from "./AuthCard";
import { useAppDispatch, useAppSelector } from "@/state/hooks";
import { verifyOtpAdmin, resendOtpAdmin } from "@/state/auth";

const CODE_LENGTH = 6;
const RESEND_SECONDS = 15;

export default function VerifyEmailScreen() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const dispatch = useAppDispatch();
  const { verifyStatus, resetEmail, error: reduxError } = useAppSelector(
    (state) => state.auth
  );

  const email = searchParams.get("email") || resetEmail || "";

  const [code, setCode] = useState<string[]>(Array(CODE_LENGTH).fill(""));
  const [secondsLeft, setSecondsLeft] = useState(RESEND_SECONDS);
  const [resending, setResending] = useState(false);
  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);

  useEffect(() => {
    if (secondsLeft <= 0) return;
    const timer = setTimeout(() => setSecondsLeft((s) => s - 1), 1000);
    return () => clearTimeout(timer);
  }, [secondsLeft]);

  const formatTime = (total: number) => {
    const m = Math.floor(total / 60)
      .toString()
      .padStart(2, "0");
    const s = (total % 60).toString().padStart(2, "0");
    return `${m}:${s}`;
  };

  const updateDigit = (index: number, value: string) => {
    const digit = value.replace(/\D/g, "").slice(-1);
    const next = [...code];
    next[index] = digit;
    setCode(next);

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

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

  const handleResend = async () => {
    if (secondsLeft > 0 || resending) return;
    if (!email) {
      toast.error("Email address missing. Please request a new code.");
      return;
    }

    setResending(true);
    try {
      const resultAction = await dispatch(resendOtpAdmin(email));
      if (resendOtpAdmin.fulfilled.match(resultAction)) {
        setSecondsLeft(RESEND_SECONDS);
        toast.success(
          resultAction.payload.message || "Verification code resent"
        );
      } else if (resendOtpAdmin.rejected.match(resultAction)) {
        const errorMsg =
          (resultAction.payload as { message?: string })?.message ||
          "Failed to resend code";
        toast.error(errorMsg);
      }
    } catch (err: unknown) {
      toast.error((err as Error)?.message || "Failed to resend code");
    } finally {
      setResending(false);
    }
  };

  const handleVerify = async () => {
    const otp = code.join("");
    if (otp.length < CODE_LENGTH) {
      toast.error("Please enter the full 6-digit code");
      return;
    }
    if (!email) {
      toast.error("Email address missing. Please request a new code.");
      return;
    }

    try {
      const resultAction = await dispatch(verifyOtpAdmin({ email, otp }));

      if (verifyOtpAdmin.fulfilled.match(resultAction)) {
        toast.success("Code verified successfully");
        const token = resultAction.payload.resetSessionToken;
        router.push(
          `/reset-password?email=${encodeURIComponent(email)}${
            token ? `&token=${encodeURIComponent(token)}` : ""
          }`
        );
      } else if (verifyOtpAdmin.rejected.match(resultAction)) {
        const errorMsg =
          (resultAction.payload as { message?: string })?.message ||
          "Invalid or expired verification code";
        toast.error(errorMsg);
      }
    } catch (err: unknown) {
      toast.error((err as Error)?.message || "Verification failed");
    }
  };

  const loading = verifyStatus === "loading";

  return (
    <AuthCard
      title="Verify Your Email"
      subtitle="Please enter the code from your email to reset your password."
    >
      <div>
        <div className="min-h-[220px]">
          <div>
            <label className="mb-2 block text-[14px] font-medium leading-[22px] tracking-[0.01em] text-[#4E616A]">
              Verification Code
            </label>
            <div className="flex gap-2">
              {code.map((digit, index) => (
                <input
                  key={index}
                  ref={(el) => {
                    inputRefs.current[index] = el;
                  }}
                  type="text"
                  inputMode="numeric"
                  maxLength={1}
                  value={digit}
                  onChange={(e) => updateDigit(index, e.target.value)}
                  onKeyDown={(e) => handleKeyDown(index, e)}
                  className="h-11 w-11 rounded-lg border border-[#D0D5DD] bg-white text-center text-[15px] font-medium text-[#101828] outline-none focus:border-[#1D4ED8]"
                />
              ))}
            </div>
          </div>

          <p className="mt-4 text-[12px] text-[#667085]">
            Resend code?{" "}
            {secondsLeft > 0 ? (
              <span className="font-medium text-[#98A2B3]">
                ({formatTime(secondsLeft)})
              </span>
            ) : (
              <button
                type="button"
                onClick={handleResend}
                disabled={resending}
                className="font-medium text-[#1D4ED8] hover:underline cursor-pointer disabled:opacity-60"
              >
                {resending ? "Sending..." : "Resend"}
              </button>
            )}
          </p>

          {reduxError && (
            <p className="mt-3 text-[12px] font-medium text-red-600 bg-red-50 p-2.5 rounded-lg border border-red-200">
              {reduxError}
            </p>
          )}
        </div>

        <button
          type="button"
          onClick={handleVerify}
          disabled={loading}
          className="mt-8 h-10 w-full rounded-lg bg-[#1D4ED8] text-[14px] font-medium text-white transition-colors hover:bg-[#1E40AF] disabled:opacity-60 cursor-pointer"
        >
          {loading ? "Verifying..." : "Verify Code"}
        </button>
      </div>
    </AuthCard>
  );
}
