"use client";

import { useState, useRef, useEffect, FormEvent, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Mail, CheckCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { AuthFormWrapper } from "@/components/auth/auth-form-wrapper";
import { useVerifyEmail, useResendOtp } from "@/lib/api/hooks/useAuth";
import { ApiRequestError } from "@/lib/api";
import { ROUTES } from "@/lib/constants";

function VerifyEmailForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const email = searchParams.get("email") ?? "";
  const type = (searchParams.get("type") ?? "verification") as
    | "verification"
    | "password-reset";

  const verifyEmail = useVerifyEmail();
  const resendOtp = useResendOtp();

  const [otp, setOtp] = useState(["", "", "", "", "", ""]);
  const [error, setError] = useState("");
  const [resendTimer, setResendTimer] = useState(60);
  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);

  // Auto-focus first input
  useEffect(() => {
    inputRefs.current[0]?.focus();
  }, []);

  // Countdown timer
  useEffect(() => {
    if (resendTimer > 0) {
      const timer = setTimeout(() => setResendTimer(resendTimer - 1), 1000);
      return () => clearTimeout(timer);
    }
  }, [resendTimer]);

  function handleChange(index: number, value: string) {
    if (value.length > 1) return;
    const newOtp = [...otp];
    newOtp[index] = value;
    setOtp(newOtp);
    setError("");

    if (value && index < 5) {
      inputRefs.current[index + 1]?.focus();
    }
  }

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

  function handlePaste(e: React.ClipboardEvent) {
    e.preventDefault();
    const pasted = e.clipboardData.getData("text").replace(/\D/g, "").slice(0, 6);
    const newOtp = pasted.split("").concat(Array(6 - pasted.length).fill(""));
    setOtp(newOtp);
    const lastIndex = Math.min(pasted.length, 5);
    inputRefs.current[lastIndex]?.focus();
  }

  function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setError("");
    const otpValue = otp.join("");

    if (otpValue.length !== 6) {
      setError("Please enter the complete 6-digit code");
      return;
    }

    verifyEmail.mutate(
      { email, otp: otpValue },
      {
        onSuccess: (data) => {
          if (data.setPasswordToken) {
            router.push(
              `${ROUTES.SET_PASSWORD}?token=${data.setPasswordToken}`
            );
          } else {
            router.push(ROUTES.LOGIN);
          }
        },
        onError: (err) => {
          if (err instanceof ApiRequestError) {
            setError(err.message);
          } else {
            setError("Something went wrong. Please try again.");
          }
        },
      }
    );
  }

  function handleResend() {
    setError("");
    resendOtp.mutate(
      { email, type },
      {
        onSuccess: () => {
          setResendTimer(60);
          setOtp(["", "", "", "", "", ""]);
          inputRefs.current[0]?.focus();
        },
        onError: (err) => {
          if (err instanceof ApiRequestError) setError(err.message);
        },
      }
    );
  }

  return (
    <AuthFormWrapper
      icon={Mail}
      iconGradient="from-blue-500 to-blue-600"
      title="Verify Your Email"
      subtitle=""
      backLabel="Back to Login"
      onBack={() => router.push(ROUTES.LOGIN)}
    >
      {/* Email display */}
      <div className="text-center -mt-4 mb-8">
        <p className="text-gray-400 text-sm sm:text-base">
          We&apos;ve sent a 6-digit code to
        </p>
        <p className="text-blue-400 font-medium mt-1">{email}</p>
      </div>

      <form onSubmit={handleSubmit}>
        {/* OTP Inputs */}
        <div className="mb-6">
          <div className="flex gap-2 sm:gap-3 justify-center mb-4">
            {otp.map((digit, index) => (
              <input
                key={index}
                ref={(el) => {
                  inputRefs.current[index] = el;
                }}
                type="text"
                inputMode="numeric"
                maxLength={1}
                value={digit}
                onChange={(e) =>
                  handleChange(index, e.target.value.replace(/\D/g, ""))
                }
                onKeyDown={(e) => handleKeyDown(index, e)}
                onPaste={index === 0 ? handlePaste : undefined}
                className="w-11 h-13 sm:w-14 sm:h-16 text-center text-xl sm:text-2xl font-bold bg-gray-800 border-2 border-gray-700 rounded-xl text-white focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 transition-all outline-none"
              />
            ))}
          </div>
          {error && (
            <p className="text-red-400 text-sm text-center">{error}</p>
          )}
        </div>

        {/* Verify Button */}
        <Button
          type="submit"
          disabled={verifyEmail.isPending}
          className="w-full text-lg py-6 mb-4"
        >
          <CheckCircle className="size-5 mr-2" />
          {verifyEmail.isPending ? "Verifying..." : "Verify & Continue"}
        </Button>

        {/* Resend */}
        <div className="text-center">
          {resendTimer > 0 ? (
            <p className="text-gray-400 text-sm">
              Resend code in{" "}
              <span className="text-white font-semibold">{resendTimer}s</span>
            </p>
          ) : (
            <button
              type="button"
              onClick={handleResend}
              disabled={resendOtp.isPending}
              className="text-blue-400 hover:text-blue-300 font-medium text-sm transition-colors"
            >
              {resendOtp.isPending ? "Sending..." : "Resend OTP"}
            </button>
          )}
        </div>
      </form>
    </AuthFormWrapper>
  );
}

export default function VerifyEmailPage() {
  return (
    <Suspense>
      <VerifyEmailForm />
    </Suspense>
  );
}
