"use client";

import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { Mail, X, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";

type Status = "loading" | "verified" | "unverified";

export function EmailVerificationBanner() {
  const { data: session, status: sessionStatus, update } = useSession();
  const [dismissed, setDismissed] = useState(false);
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);
  const [status, setStatus] = useState<Status>("loading");

  // Authoritative check against the DB. The JWT cookie can be stale (e.g.
  // user verified their email in another tab, or was auto-verified by the
  // invite flow on an existing session), so we confirm with the server
  // before ever showing the banner. If the DB disagrees with the session,
  // we also trigger a session update so the banner hides immediately on
  // subsequent renders without requiring a full sign-out.
  useEffect(() => {
    if (sessionStatus !== "authenticated") return;

    let cancelled = false;
    (async () => {
      try {
        const res = await fetch("/api/auth/verify-email/status", {
          cache: "no-store",
        });
        if (!res.ok) {
          if (!cancelled) setStatus("unverified");
          return;
        }
        const data = (await res.json()) as { verified: boolean };
        if (cancelled) return;
        setStatus(data.verified ? "verified" : "unverified");
        if (data.verified && session?.user && !session.user.isEmailVerified) {
          void update();
        }
      } catch {
        if (!cancelled) setStatus("unverified");
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [sessionStatus, session?.user, update]);

  if (
    sessionStatus !== "authenticated" ||
    !session?.user ||
    session.user.isEmailVerified ||
    status === "loading" ||
    status === "verified" ||
    dismissed
  ) {
    return null;
  }

  async function handleResend() {
    setSending(true);
    try {
      const res = await fetch("/api/auth/verify-email/send", { method: "POST" });
      if (res.ok) setSent(true);
    } catch {
      // silent fail — user can try again
    } finally {
      setSending(false);
    }
  }

  return (
    <div className="relative flex items-center gap-3 rounded-lg border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm text-amber-200">
      <Mail className="size-4 shrink-0 text-amber-400" />
      <p className="flex-1">
        {sent ? (
          "Verification email sent — check your inbox."
        ) : (
          <>
            Please verify your email address.{" "}
            <button
              onClick={handleResend}
              disabled={sending}
              className="inline-flex items-center gap-1 font-medium text-amber-400 underline underline-offset-2 hover:text-amber-300 disabled:opacity-60"
            >
              {sending && <Loader2 className="size-3 animate-spin" />}
              Resend verification email
            </button>
          </>
        )}
      </p>
      <Button
        variant="ghost"
        size="icon"
        className="size-6 shrink-0 text-amber-400 hover:bg-amber-500/20 hover:text-amber-300"
        onClick={() => setDismissed(true)}
      >
        <X className="size-3.5" />
      </Button>
    </div>
  );
}
