'use client'

import { useEffect, useRef, useState } from 'react'
import { formatARS } from '@/lib/money'

type Props = { order: { id: string; number: number; totalCents: number }; onPaid: () => void; onClose: () => void; onCash: () => void }

/** Cobro con QR de MercadoPago: muestra el QR, espera el pago y avisa solo. */
export default function QrCharge({ order, onPaid, onClose, onCash }: Props) {
  const [svg, setSvg] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [paid, setPaid] = useState(false)
  const [left, setLeft] = useState(600)
  const closed = useRef(false)

  async function create() {
    setError(null); setSvg(null)
    try {
      const r = await fetch('/api/estacion/qr', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ orderId: order.id }) })
      const d = await r.json()
      if (d.paid) { setPaid(true); return }
      if (!r.ok) throw new Error(d.error ?? 'No se pudo generar el QR')
      setSvg(d.svg); setLeft(d.expiresInSec ?? 600)
    } catch (e) { setError(e instanceof Error ? e.message : 'Sin conexión') }
  }
  useEffect(() => { create() }, []) // eslint-disable-line react-hooks/exhaustive-deps

  // Espera el pago: consulta el estado cada 2 s (el webhook de MP lo marca como pagado).
  useEffect(() => {
    if (!svg || paid) return
    const t = setInterval(async () => {
      setLeft(l => Math.max(0, l - 2))
      try {
        const r = await fetch(`/api/orders/${order.id}`, { cache: 'no-store' })
        const d = await r.json()
        if (d.status && d.status !== 'pending_payment') {
          setPaid(true); try { navigator.vibrate?.([60, 40, 60]) } catch {}
          setTimeout(() => { if (!closed.current) onPaid() }, 1600)
        }
      } catch {}
    }, 2000)
    return () => clearInterval(t)
  }, [svg, paid, order.id, onPaid])

  async function cancel(then: () => void) {
    closed.current = true
    await fetch('/api/estacion/qr', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ orderId: order.id, cancel: true }) }).catch(() => {})
    then()
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-ink-950 p-4" role="dialog" aria-modal="true" aria-label={`Cobrar pedido ${order.number} con QR`}>
      <div className="w-full max-w-sm text-center">
        <p className="text-sm text-gray-400">Pedido #{order.number}</p>
        <p className="mt-1 text-4xl font-bold tabular-nums">{formatARS(order.totalCents)}</p>
        <div className={`relative mx-auto mt-5 aspect-square w-72 overflow-hidden rounded-card bg-white p-4 transition ${paid ? 'scale-95' : ''}`}>
          {svg && !paid && <div className="h-full w-full [&>svg]:h-full [&>svg]:w-full" dangerouslySetInnerHTML={{ __html: svg }} />}
          {!svg && !error && !paid && <div className="flex h-full items-center justify-center text-sm text-gray-400">Generando QR…</div>}
          {error && <div className="flex h-full items-center justify-center px-4 text-sm text-red-600">{error}</div>}
          {paid && <div className="flex h-full animate-scale-in flex-col items-center justify-center rounded-card bg-live text-ink-950"><span className="text-6xl">✓</span><span className="mt-2 text-xl font-bold">Pagado</span></div>}
        </div>
        {!paid && svg && <p className="mt-4 text-sm text-gray-300">Escaneá con la app de MercadoPago o la de tu banco</p>}
        {!paid && svg && <p className="mt-1 text-xs text-gray-500">Esperando el pago · vence en {Math.floor(left / 60)}:{String(left % 60).padStart(2, '0')}</p>}
        {!paid && (
          <div className="mt-6 grid grid-cols-2 gap-2">
            <button onClick={() => cancel(onClose)} className="btn border border-ink-700 py-3 text-gray-300">Cancelar</button>
            {error ? <button onClick={create} className="btn bg-white py-3 text-ink-950">Reintentar</button>
              : <button onClick={() => cancel(onCash)} className="btn border border-ink-700 py-3 text-gray-300">Pagó en efectivo</button>}
          </div>
        )}
      </div>
    </div>
  )
}
