'use client'

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

type Outcome = 'confirmed' | 'failed' | 'pending'

export function MockCardSetup({ setupReference, returnUrl, mode, cardId }: {
  setupReference: string
  returnUrl: string
  mode: 'add' | 'confirm'
  cardId: string | null
}) {
  const [busy, setBusy] = useState<Outcome | null>(null)
  const [error, setError] = useState<string | null>(null)

  async function choose(outcome: Outcome) {
    setBusy(outcome)
    setError(null)
    try {
      const res = await fetch('/api/dev-preview/synchron-payments/card-setup', {
        method: 'POST', headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ setup_reference: setupReference, outcome }),
      })
      if (!res.ok) { setError(`Mock card setup failed (${res.status}).`); setBusy(null); return }
      window.location.assign(returnUrl)
    } catch {
      setError('Mock card setup 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 card data is collected</p>
        <h1 className="text-lg font-semibold">Synchron Permits (mock) — {mode === 'confirm' ? 'Confirm card ending 4242 — CVV (mock)' : 'Enter card (mock)'}</h1>
        <p className="mt-1 text-sm text-muted-foreground">
          Setup <code className="font-mono">{setupReference}</code>{cardId ? <> · card <code className="font-mono">{cardId}</code></> : null}
        </p>
        <div className="mt-4 rounded-md border border-dashed border-border bg-muted/40 p-4 text-sm text-muted-foreground">
          {mode === 'confirm' ? 'A real Synchron page would ask for the CVV here.' : 'A real Synchron page would show a Stripe card form here.'}
        </div>
        {error && <p className="mt-3 text-sm text-destructive">{error}</p>}
        <div className="mt-6 grid gap-2">
          <Button disabled={busy !== null} onClick={() => choose('confirmed')}>{busy === 'confirmed' ? 'Working…' : 'Confirm'}</Button>
          <Button variant="destructive" disabled={busy !== null} onClick={() => choose('failed')}>{busy === 'failed' ? 'Working…' : 'Fail'}</Button>
          <Button variant="secondary" disabled={busy !== null} onClick={() => choose('pending')}>{busy === 'pending' ? 'Working…' : 'Leave pending'}</Button>
        </div>
      </div>
    </main>
  )
}
