"use client"

import { useState } from "react"

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

  async function handleClick() {
    if (!confirm("Cancel your PayPal subscription? You'll keep access until the end of the current billing period.")) {
      return
    }
    setLoading(true)
    const res = await fetch("/api/paypal/cancel", { method: "POST" })
    const data = await res.json().catch(() => ({}))
    if (res.ok) {
      window.location.href = "/settings/billing?canceled=true"
    } else {
      setLoading(false)
      alert(data.error || "Could not cancel the subscription.")
    }
  }

  return (
    <button
      onClick={handleClick}
      disabled={loading}
      className="rounded-lg border border-white/10 px-4 py-2 text-sm text-white/60 hover:border-white/20 hover:text-white transition disabled:opacity-50"
    >
      {loading ? "Canceling..." : "Cancel Subscription"}
    </button>
  )
}
