"use client"

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

export function CheckoutButton({
  plan,
  label,
  highlight,
  interval = "month",
  annualAvailable = false,
  paypalEnabled = 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
  // When true, also offer "Pay with PayPal" using the same interval choice.
  paypalEnabled?: boolean
}) {
  const [loading, setLoading] = useState(false)
  const [paypalLoading, setPaypalLoading] = 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)
  }

  async function handlePaypal() {
    setPaypalLoading(true)
    const res = await fetch("/api/paypal/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 {
      setPaypalLoading(false)
      if (data.error) alert(data.error)
    }
  }

  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 || paypalLoading}
        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>

      {paypalEnabled && (
        <button
          onClick={handlePaypal}
          disabled={loading || paypalLoading}
          className="flex w-full items-center justify-center gap-1.5 rounded-lg bg-[#ffc439] py-2 text-xs font-bold text-[#003087] transition hover:bg-[#f0b90b] disabled:opacity-50"
        >
          {paypalLoading ? (
            "Loading..."
          ) : (
            <>
              Pay with <span className="font-extrabold italic">Pay<span className="text-[#009cde]">Pal</span></span>
            </>
          )}
        </button>
      )}
    </div>
  )
}
