'use client'

import { useCallback, useEffect, useState } from 'react'
import { formatARS } from '@/lib/money'
import QrCharge from './QrCharge'

type Order = { id: string; number: number; buyerName: string | null; totalCents: number; items: { name: string; quantity: number }[] }
type Boot = { qrEnabled?: boolean; station: { name: string }; event: { id: string; name: string }; orders: Order[] }

// La caja cobra en efectivo o con QR de MercadoPago (si el organizador lo tiene conectado).
export default function CashierApp({ stationId }: { stationId: string }) {
  const [boot, setBoot] = useState<Boot | null>(null)
  const [q, setQ] = useState('')
  const [busy, setBusy] = useState<string | null>(null)
  const [done, setDone] = useState<number | null>(null)
  const [online, setOnline] = useState(true)
  const [qr, setQr] = useState<Order | null>(null)

  const refresh = useCallback(async () => {
    try {
      const r = await fetch('/api/estacion/bootstrap', { cache: 'no-store' })
      if (r.status === 401) { window.location.reload(); return }
      setBoot(await r.json()); setOnline(true)
    } catch { setOnline(false) }
  }, [])

  useEffect(() => { refresh(); const t = setInterval(refresh, 10000); return () => clearInterval(t) }, [refresh, stationId])
  useEffect(() => {
    if (!boot?.event.id) return
    const es = new EventSource(`/api/stream/${boot.event.id}`)
    es.onmessage = () => refresh()
    return () => es.close()
  }, [boot?.event.id, refresh])

  async function charge(o: Order) {
    setBusy(o.id)
    try {
      const r = await fetch('/api/estacion/cobrar', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ orderId: o.id }) })
      if (!r.ok) throw new Error()
      try { navigator.vibrate?.([40, 30, 40]) } catch {}
      setDone(o.number); setQ(''); setTimeout(() => setDone(null), 2500)
      await refresh()
    } catch { alert('Sin conexión: no se pudo registrar el cobro. Reintentá.') }
    finally { setBusy(null) }
  }

  if (!boot) return <main className="flex min-h-dvh items-center justify-center bg-ink-950 text-gray-400">Cargando caja…</main>
  const list = q ? boot.orders.filter(o => String(o.number).startsWith(q)) : boot.orders

  return (
    <main className="min-h-dvh bg-ink-950 text-white">
      <header className="flex items-center justify-between border-b border-ink-800 px-4 py-3">
        <div><p className="text-xs text-gray-500">{boot.event.name}</p><h1 className="text-lg font-semibold">{boot.station.name} · {boot.qrEnabled ? 'Efectivo o QR' : 'Efectivo'}</h1></div>
        <span className={`chip ${online ? 'bg-live/15 text-green-300' : 'bg-amber-500/20 text-amber-200'}`}>{online ? 'En línea' : 'Sin conexión'}</span>
      </header>
      <div className="p-4">
        <input value={q} onChange={e => setQ(e.target.value.replace(/\D/g, ''))} inputMode="numeric" autoFocus placeholder="Número de pedido"
          className="w-full rounded-control border border-ink-700 bg-ink-900 px-4 py-4 text-center text-3xl tabular-nums outline-none focus:border-brand-400" />
        {done && <p className="mt-3 animate-scale-in rounded-control bg-live px-4 py-3 text-center text-lg font-bold text-ink-950">#{done} cobrado ✓</p>}
      </div>
      <ul className="space-y-2 px-4 pb-8">
        {list.length === 0 && <li className="py-12 text-center text-gray-500">{q ? 'No hay pedidos con ese número' : 'No hay pedidos esperando pago'}</li>}
        {list.map(o => (
          <li key={o.id} className="flex items-center gap-4 rounded-card bg-ink-900 p-4">
            <span className="text-4xl font-bold tabular-nums">#{o.number}</span>
            <div className="min-w-0 flex-1 text-sm text-gray-400">
              {o.buyerName && <p className="text-brand-200">{o.buyerName}</p>}
              <p className="truncate">{o.items.map(i => `${i.quantity}× ${i.name}`).join(', ')}</p>
            </div>
            <div className="flex flex-col items-stretch gap-2 sm:flex-row">
              <button onClick={() => charge(o)} disabled={busy === o.id} className="btn bg-white px-5 py-3 text-ink-950">
                {busy === o.id ? '…' : `Efectivo ${formatARS(o.totalCents)}`}
              </button>
              {boot.qrEnabled && <button onClick={() => setQr(o)} className="btn-brand px-5 py-3">QR</button>}
            </div>
          </li>
        ))}
      </ul>
      {qr && (
        <QrCharge order={qr}
          onPaid={() => { setDone(qr.number); setQr(null); setQ(''); setTimeout(() => setDone(null), 2500); refresh() }}
          onClose={() => { setQr(null); refresh() }}
          onCash={() => { const o = qr; setQr(null); charge(o) }} />
      )}
    </main>
  )
}
