"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Eye, Loader2 } from "lucide-react";
import { authClient } from "@/lib/auth/auth-client";

/**
 * Sticky banner shown while an admin is impersonating a user. Reads the live
 * session; renders nothing for normal sessions. "Stop" ends impersonation and
 * returns to the admin surface.
 */
export function ImpersonationBanner() {
  const { data: session } = authClient.useSession();
  const router = useRouter();
  const [busy, setBusy] = useState(false);

  // `impersonatedBy` is set on the session row by the better-auth admin plugin.
  const impersonatedBy = session?.session
    ? (session.session as { impersonatedBy?: string | null }).impersonatedBy
    : null;
  if (!impersonatedBy) return null;

  const who = session?.user?.email ?? session?.user?.name ?? "this user";

  async function stop() {
    setBusy(true);
    try {
      await authClient.admin.stopImpersonating();
    } finally {
      router.push("/admin");
      router.refresh();
    }
  }

  return (
    <div className="sticky top-0 z-40 flex items-center justify-center gap-3 bg-warning px-4 py-2 text-center text-sm font-medium text-warning-foreground">
      <span className="inline-flex items-center gap-1.5">
        <Eye className="h-4 w-4" />
        Viewing as {who}
      </span>
      <button
        onClick={stop}
        disabled={busy}
        className="inline-flex items-center gap-1 rounded-full bg-warning-foreground/15 px-3 py-0.5 font-semibold transition-colors hover:bg-warning-foreground/25 disabled:opacity-60"
      >
        {busy && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
        Stop
      </button>
    </div>
  );
}
