"use client";

import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";

export function ManageBillingButton() {
  const [loading, setLoading] = useState(false);

  async function openPortal() {
    setLoading(true);
    try {
      const res = await fetch("/api/v1/billing/portal", { method: "POST" });
      if (!res.ok) throw new Error();
      const { url } = (await res.json()) as { url: string };
      window.location.assign(url);
    } catch {
      toast.error("Couldn't open the billing portal");
      setLoading(false);
    }
  }

  return (
    <Button variant="outline" disabled={loading} onClick={() => { void openPortal(); }}>
      {loading ? "Opening…" : "Manage billing"}
    </Button>
  );
}
