"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { ShieldAlert } from "lucide-react"
import { authClient } from "@/lib/auth-client"

/**
 * Shown in the app shell whenever the current session was created via admin
 * impersonation. Lets the admin end the impersonation and return to /admin.
 */
export function ImpersonationBanner({ label }: { label?: string }) {
  const router = useRouter()
  const [loading, setLoading] = useState(false)

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

  return (
    <div className="sticky top-0 z-[60] flex items-center justify-center gap-3 bg-amber-500 px-4 py-2 text-center text-sm font-semibold text-black">
      <ShieldAlert className="h-4 w-4 shrink-0" />
      <span>Viewing as {label ?? "another user"} — actions affect their account.</span>
      <button
        onClick={stop}
        disabled={loading}
        className="rounded-md bg-black/85 px-3 py-1 text-xs font-bold text-white transition hover:bg-black disabled:opacity-60"
      >
        {loading ? "Returning…" : "Return to admin"}
      </button>
    </div>
  )
}
