"use client";

import { useSession } from "next-auth/react";
import { useState } from "react";

/** Shown while a super-admin is viewing a client workspace. */
export function ImpersonationBanner() {
  const { data: session } = useSession();
  const [pending, setPending] = useState(false);

  if (!session?.user?.impersonatorAdminId) return null;

  async function stopImpersonation() {
    setPending(true);
    try {
      const res = await fetch("/api/admin/stop-impersonate", {
        method: "POST",
      });
      const data = (await res.json()) as { redirectTo?: string };
      window.location.assign(data.redirectTo ?? "/admin/clients");
    } catch {
      setPending(false);
    }
  }

  return (
    <div className="flex shrink-0 flex-wrap items-center justify-between gap-2 bg-navy px-4 py-2 text-sm text-white">
      <p>
        Viewing as{" "}
        <span className="font-semibold">
          {session.user.name ?? session.user.email}
        </span>
        . Passwords cannot be shown — this is a support login.
      </p>
      <button
        type="button"
        disabled={pending}
        onClick={() => void stopImpersonation()}
        className="rounded-sm bg-white px-3 py-1 text-xs font-semibold text-navy hover:bg-white/90 disabled:opacity-60"
      >
        {pending ? "Returning…" : "Return to admin"}
      </button>
    </div>
  );
}
