"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { grantSuperUser } from "../superuser-requests/actions";
import { ShieldCheck } from "lucide-react";

export function GrantSuperUserButton({ userId }: { userId: string }) {
  const router = useRouter();
  const [pending, setPending] = useState(false);
  const [error, setError] = useState("");

  async function handle() {
    if (!confirm("Grant this user SuperUser access?")) return;
    setPending(true);
    setError("");
    const result = await grantSuperUser(userId);
    setPending(false);
    if ("error" in result) setError(result.error);
    else router.refresh();
  }

  return (
    <span title={error || undefined}>
      <button
        onClick={handle}
        disabled={pending}
        title="Grant SuperUser access"
        className="inline-flex items-center gap-1 rounded border border-primary-200 bg-primary-50 px-2 py-1 text-xs font-medium text-primary-700 hover:bg-primary-100 disabled:opacity-50 transition-colors"
      >
        <ShieldCheck className="h-3 w-3" />
        {pending ? "…" : "SuperUser"}
      </button>
    </span>
  );
}
