"use client";

import { useState } from "react";
import { Loader2 } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";

export function ManageSubscriptionButton() {
  const [busy, setBusy] = useState(false);

  async function open() {
    setBusy(true);
    try {
      const res = await fetch("/api/subscriptions/portal", { method: "POST" });
      const json = (await res.json()) as { portalUrl?: string; error?: string };
      if (!res.ok || !json.portalUrl) throw new Error(json.error ?? "Failed to open portal");
      window.location.href = json.portalUrl;
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Portal failed");
    } finally {
      setBusy(false);
    }
  }

  return (
    <Button variant="outline" onClick={open} disabled={busy}>
      {busy ? (
        <>
          <Loader2 className="size-4 animate-spin" /> Opening…
        </>
      ) : (
        "Manage subscription"
      )}
    </Button>
  );
}
