"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";

/** Turning developer access off is always self-serve regardless of tier
 * or who granted it — only turning it back on (for a free-tier user)
 * requires an admin. */
export function DisableDeveloperAccessButton() {
  const router = useRouter();
  const [disabling, setDisabling] = useState(false);

  async function disable() {
    setDisabling(true);
    try {
      const res = await fetch("/api/v1/users/me/developer-access", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ enabled: false }),
      });
      if (!res.ok) throw new Error();
      router.refresh();
    } catch {
      toast.error("Couldn't disable developer access");
      setDisabling(false);
    }
  }

  return (
    <button
      type="button"
      disabled={disabling}
      onClick={() => { void disable(); }}
      className="text-xs text-muted-foreground hover:text-destructive underline underline-offset-2"
    >
      {disabling ? "Disabling…" : "Disable developer access"}
    </button>
  );
}
