"use client"

import { useState } from "react"
import { cn } from "@/lib/utils"

export function CheckoutButton({
  plan,
  label,
  highlight,
  interval = "month",
  annualAvailable = false,
}: {
  plan: string
  label: string
  highlight?: boolean
  interval?: "month" | "year"
  // When true, show a monthly/annual choice. Only pass this for subscription
  // plans and only when annual billing is actually configured server-side.
  annualAvailable?: boolean
}) {
  const [loading, setLoading] = useState(false)
  const [chosenInterval, setChosenInterval] = useState<"month" | "year">(interval)

  const effectiveInterval = annualAvailable ? chosenInterval : interval

  async function handleClick() {
    setLoading(true)
    const res = await fetch("/api/stripe/checkout", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ plan, interval: effectiveInterval }),
    })
    const data = await res.json()
    if (data.url) window.location.href = data.url
    else setLoading(false)
  }

  return (
    <div className="space-y-2">
      {annualAvailable && (
        <div className="flex rounded-lg border border-white/10 p-0.5 text-[11px] font-medium">
          <button
            type="button"
            onClick={() => setChosenInterval("month")}
            className={cn(
              "flex-1 rounded-md py-1 transition",
              chosenInterval === "month" ? "bg-white/10 text-white" : "text-white/40 hover:text-white/70"
            )}
          >
            Monthly
          </button>
          <button
            type="button"
            onClick={() => setChosenInterval("year")}
            className={cn(
              "flex-1 rounded-md py-1 transition",
              chosenInterval === "year" ? "bg-white/10 text-white" : "text-white/40 hover:text-white/70"
            )}
          >
            Annual
          </button>
        </div>
      )}
      <button
        onClick={handleClick}
        disabled={loading}
        className={cn(
          "w-full rounded-lg py-2 text-xs font-semibold transition disabled:opacity-50",
          highlight
            ? "bg-indigo-600 text-white hover:bg-indigo-500"
            : "border border-white/10 text-white/70 hover:border-white/20 hover:text-white"
        )}
      >
        {loading ? "Loading..." : label}
      </button>
    </div>
  )
}
