"use client";

import { useState, useEffect, useCallback, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { OTPInput } from "@/components/ui/OTPInput";
import { ApiError, apiFetch } from "@/lib/apiClient";
import { useAuth } from "@/context/AuthContext";
import type { AuthResponse } from "@/types";

function VerifyOTPForm() {
  const router = useRouter();
  const params = useSearchParams();
  const { login } = useAuth();

  const userId = params.get("userId") ?? "";
  const email  = params.get("email")  ?? "";

  const [otp, setOtp]         = useState<string[]>(Array(6).fill(""));
  const [loading, setLoading]   = useState(false);
  const [resending, setResending] = useState(false);
  const [error, setError]       = useState("");
  const [seconds, setSeconds]   = useState(600);
  const [canResend, setCanResend] = useState(false);

  useEffect(() => {
    if (!userId) router.replace("/register");
  }, [userId, router]);

  useEffect(() => {
    const timer = setInterval(() => {
      setSeconds((s) => {
        if (s <= 1) { clearInterval(timer); setCanResend(true); return 0; }
        return s - 1;
      });
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  const timerLabel   = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
  const timerPercent = (seconds / 600) * 100;
  const timerUrgent  = seconds < 60;

  async function handleVerify(e: React.FormEvent) {
    e.preventDefault();
    const code = otp.join("");
    if (code.length !== 6) { setError("Enter all 6 digits."); return; }
    setError("");
    setLoading(true);
    try {
      const data = await apiFetch<AuthResponse>("/auth/verify-otp", {
        method: "POST",
        body: JSON.stringify({ userId, otp: code }),
        skipAuth: true,
      });
      login(data.accessToken, data.user);
      router.push("/dashboard");
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "Verification failed. Check your code.");
      setOtp(Array(6).fill(""));
    } finally {
      setLoading(false);
    }
  }

  const handleResend = useCallback(async () => {
    setResending(true);
    try {
      await apiFetch("/auth/resend-otp", {
        method: "POST",
        body: JSON.stringify({ userId }),
        skipAuth: true,
      });
      setSeconds(600);
      setCanResend(false);
      setOtp(Array(6).fill(""));
      setError("");
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "Resend failed. Try again.");
    } finally {
      setResending(false);
    }
  }, [userId]);

  return (
    <main className="min-h-screen bg-[#f3f3f3] flex flex-col items-center justify-center px-4 py-8 relative overflow-hidden">

      {/* Subtle atmosphere */}
      <div className="fixed inset-0 -z-10 pointer-events-none">
        <div className="absolute top-0 left-1/2 -translate-x-1/2 w-[900px] h-[280px] bg-[#040b61]/4 blur-[140px] rounded-full" />
        <div className="absolute bottom-0 right-0 w-[360px] h-[280px] bg-[#FED665]/10 blur-[100px] rounded-full" />
      </div>

      <div className="w-full max-w-md">

        {/* Back */}
        <div className="mb-8">
          <button
            onClick={() => router.push("/register")}
            className="w-10 h-10 rounded-full border border-[#c6c5d3] bg-white flex items-center justify-center text-[#464651] hover:border-[#040b61] hover:text-[#040b61] transition-all shadow-sm"
          >
            <span className="material-symbols-outlined text-lg">arrow_back</span>
          </button>
        </div>

        <div className="bg-white rounded-[2rem] p-8 border border-[#e2e2e2] shadow-[0_8px_48px_-8px_rgba(4,11,97,0.10)]">

          {/* Hero */}
          <div className="text-center mb-8">
            <div className="w-16 h-16 rounded-2xl bg-[#040b61] flex items-center justify-center mx-auto mb-5 shadow-[0_8px_24px_rgba(4,11,97,0.25)]">
              <span className="material-symbols-outlined text-[#FED665] text-3xl" style={{ fontVariationSettings: "'FILL' 1" }}>mark_email_unread</span>
            </div>
            <h1
              className="text-[#040b61] font-black text-[24px] leading-tight mb-2"
              style={{ fontFamily: "Plus Jakarta Sans, sans-serif", letterSpacing: "-0.02em" }}
            >
              Check your email
            </h1>
            <p className="text-[#767682] text-sm leading-relaxed">
              We sent a 6-digit code to{" "}
              <span className="text-[#040b61] font-semibold">{email}</span>
            </p>
          </div>

          {/* Error */}
          {error && (
            <div className="mb-5 flex items-center gap-3 p-4 rounded-2xl bg-red-50 border border-red-200">
              <span className="material-symbols-outlined text-red-500 text-lg shrink-0">error</span>
              <p className="text-red-600 text-sm font-medium">{error}</p>
            </div>
          )}

          <form onSubmit={handleVerify}>
            {/* OTP input */}
            <div className="mb-6">
              <OTPInput value={otp} onChange={setOtp} disabled={loading} />
            </div>

            {/* Timer */}
            <div className="mb-6">
              <div className="flex items-center justify-between mb-2">
                <span className="text-[#767682] text-[11px] font-bold uppercase tracking-widest">Code expires in</span>
                <span className={`text-sm font-black tabular-nums ${timerUrgent ? "text-red-500" : "text-[#040b61]"}`}>
                  {timerLabel}
                </span>
              </div>
              <div className="w-full h-1.5 bg-[#e2e2e2] rounded-full overflow-hidden">
                <div
                  className="h-full rounded-full transition-all duration-1000"
                  style={{
                    width: `${timerPercent}%`,
                    background: timerUrgent
                      ? "linear-gradient(to right, #ef4444, #f87171)"
                      : "linear-gradient(to right, #D4AF37, #FED665)",
                  }}
                />
              </div>
            </div>

            {/* Resend */}
            <div className="text-center mb-6">
              <button
                type="button"
                onClick={handleResend}
                disabled={!canResend || resending}
                className="text-[#755b00] hover:text-[#040b61] text-sm font-bold disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
              >
                {resending ? "Sending new code…" : canResend ? "Resend code →" : "Resend available after timer"}
              </button>
            </div>

            {/* Submit */}
            <button
              type="submit"
              disabled={loading || otp.join("").length !== 6}
              className="w-full py-4 rounded-full bg-[#040b61] text-white font-bold text-[15px] hover:bg-[#0a1580] active:scale-[0.98] transition-all shadow-[0_4px_20px_rgba(4,11,97,0.25)] flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {loading ? (
                <>
                  <span className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                  Verifying…
                </>
              ) : (
                <>
                  Verify & Continue
                  <span className="material-symbols-outlined text-xl" style={{ fontVariationSettings: "'FILL' 1" }}>check_circle</span>
                </>
              )}
            </button>
          </form>
        </div>

        <p className="text-center text-[#767682] text-xs mt-6">
          Wrong email?{" "}
          <button onClick={() => router.push("/register")}
            className="text-[#040b61] font-bold hover:underline transition-colors">
            Start over
          </button>
        </p>
      </div>
    </main>
  );
}

export default function VerifyPage() {
  return (
    <Suspense>
      <VerifyOTPForm />
    </Suspense>
  );
}
