"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Code2 } from "lucide-react";
import { Button } from "@/components/ui/button";

/** Shown instead of the locked notice on the webhooks/API-keys settings
 * pages when the user is on a paid tier — self-serve, no admin needed, no
 * added fee. Reloads the page on success since the manager component
 * needs its initial data fetched server-side. */
export function DeveloperAccessToggle({ message }: { message: string }) {
  const router = useRouter();
  const [enabling, setEnabling] = useState(false);

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

  return (
    <div className="flex items-center justify-between gap-3 rounded-lg border bg-muted/30 p-4">
      <div className="flex items-start gap-3 text-sm text-muted-foreground">
        <Code2 className="h-4 w-4 shrink-0 mt-0.5" />
        <p>{message}</p>
      </div>
      <Button type="button" size="sm" disabled={enabling} onClick={() => { void enable(); }}>
        {enabling ? "Enabling…" : "Enable"}
      </Button>
    </div>
  );
}
