'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'

type Outcome = 'paid' | 'failed' | 'cancelled' | 'pending'

const LABELS: Array<{ outcome: Outcome; label: string; variant: 'default' | 'destructive' | 'outline' | 'secondary' }> = [
  { outcome: 'paid', label: 'Pay successfully', variant: 'default' },
  { outcome: 'failed', label: 'Fail payment', variant: 'destructive' },
  { outcome: 'cancelled', label: 'Cancel', variant: 'outline' },
  { outcome: 'pending', label: 'Leave pending', variant: 'secondary' },
]

export function MockCheckout({ purchaseReference, returnUrl, cancelUrl, totalCents }: {
  purchaseReference: string
  returnUrl: string
  cancelUrl: string
  totalCents: number
}) {
  const [busy, setBusy] = useState<Outcome | null>(null)
  const [error, setError] = useState<string | null>(null)
  const amount = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(totalCents / 100)

  async function choose(outcome: Outcome) {
    setBusy(outcome)
    setError(null)
    try {
      const res = await fetch('/api/dev-preview/synchron-payments/outcome', {
        method: 'POST', headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ purchase_reference: purchaseReference, outcome }),
      })
      if (!res.ok) { setError(`Mock outcome failed (${res.status}).`); setBusy(null); return }
      window.location.assign(outcome === 'cancelled' ? cancelUrl : returnUrl)
    } catch {
      setError('Mock outcome failed.')
      setBusy(null)
    }
  }

  return (
    <main className="flex min-h-screen items-center justify-center bg-amber-50 px-4 py-10">
      <div className="w-full max-w-md rounded-xl border-2 border-dashed border-amber-400 bg-white p-6 shadow-sm">
        <p className="mb-1 text-xs font-semibold uppercase tracking-wide text-amber-700">Development only — no money moves</p>
        <h1 className="text-lg font-semibold">Synchron Permits (mock) checkout</h1>
        <p className="mt-1 text-sm text-muted-foreground">Purchase <code className="font-mono">{purchaseReference}</code></p>
        <p className="mt-4 text-3xl font-semibold">{amount}</p>
        <p className="text-xs text-muted-foreground">Route purchase total</p>
        {error && <p className="mt-3 text-sm text-destructive">{error}</p>}
        <div className="mt-6 grid gap-2">
          {LABELS.map((b) => (
            <Button key={b.outcome} variant={b.variant} disabled={busy !== null} onClick={() => choose(b.outcome)}>
              {busy === b.outcome ? 'Working…' : b.label}
            </Button>
          ))}
        </div>
      </div>
    </main>
  )
}
