'use client'

import { useEffect, useMemo, useState } from 'react'
import { formatARS } from '@/lib/money'
import { PoweredBy, PublicHeaderMark } from '@/components/OrgBrand'
import ProductIcon from '@/components/ProductIcon'
import { copy } from '@/config/brand'

type Product = { id: string; name: string; description: string | null; priceCents: number; categoryId: string | null; isAlcoholic: boolean; soldOut: boolean; icon: string | null; imageUrl: string | null; popular: boolean; lowStock: boolean }
type Props = {
  brand: { name: string; logoUrl: string | null; whiteLabel: boolean; custom: boolean }
  event: { id: string; name: string; description: string | null; minors: boolean }
  methods: { mercadopago: boolean; cash: boolean }
  categories: { id: string; name: string }[]
  products: Product[]
}

const vibrate = (ms: number | number[]) => { try { navigator.vibrate?.(ms) } catch {} }

export default function MenuClient({ brand, event, methods, categories, products }: Props) {
  const [cart, setCart] = useState<Record<string, number>>({})
  const [cat, setCat] = useState<string>('all')
  const [open, setOpen] = useState(false)
  const [name, setName] = useState('')
  const [method, setMethod] = useState<'mercadopago' | 'cash'>(methods.mercadopago ? 'mercadopago' : 'cash')
  const [adult, setAdult] = useState(false)
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [tickets, setTickets] = useState<{ id: string; number?: number }[]>([])

  // Tickets anteriores guardados en este celular (sobreviven a cerrar el navegador)
  useEffect(() => {
    try { setTickets(JSON.parse(localStorage.getItem(`tickets:${event.id}`) ?? '[]')) } catch {}
  }, [event.id])

  const byId = useMemo(() => new Map(products.map(p => [p.id, p])), [products])
  const lines = Object.entries(cart).filter(([, q]) => q > 0)
  const count = lines.reduce((s, [, q]) => s + q, 0)
  const total = lines.reduce((s, [id, q]) => s + (byId.get(id)?.priceCents ?? 0) * q, 0)
  const needsAge = lines.some(([id]) => byId.get(id)?.isAlcoholic)
  const visible = cat === 'all' ? products : products.filter(p => p.categoryId === cat)
  const add = (id: string, d: number) => { vibrate(8); setCart(c => ({ ...c, [id]: Math.max(0, Math.min(20, (c[id] ?? 0) + d)) })) }

  async function submit() {
    if (needsAge && !adult) { setError('Confirmá que sos mayor de 18 años'); return }
    setBusy(true); setError(null)
    try {
      const res = await fetch('/api/orders', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          eventId: event.id, method, buyerName: name || undefined, ageConfirmed: adult,
          items: lines.map(([productId, quantity]) => ({ productId, quantity })),
        }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error ?? 'No pudimos crear el pedido')
      const next = [{ id: data.orderId }, ...tickets].slice(0, 20)
      localStorage.setItem(`tickets:${event.id}`, JSON.stringify(next))
      vibrate([30, 40, 30])
      window.location.href = data.redirect
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Error de conexión')
      setBusy(false)
    }
  }

  const noMethods = !methods.mercadopago && !methods.cash

  return (
    <main className="min-h-dvh bg-ink-950 pb-32 text-piedra">
      <header className="px-5 pb-4 pt-8">
        <div className="flex items-center justify-between gap-3">
          <PublicHeaderMark brand={brand} hook={copy.hookShort} />
          {event.minors && <span className="badge-minors">● Evento sin alcohol</span>}
        </div>
        <h1 className="mt-2 text-3xl font-bold">{event.name}</h1>
        {event.description && <p className="mt-1 text-sm text-gray-400">{event.description}</p>}
        {tickets.length > 0 && (
          <a href={`/t/${tickets[0].id}`} className="mt-4 flex items-center justify-between rounded-control bg-ink-800 px-4 py-3 text-sm">
            <span>Ver mi último pedido</span><span className="text-brand-300">→</span>
          </a>
        )}
      </header>

      {categories.length > 0 && (
        <nav className="sticky top-0 z-10 flex gap-2 overflow-x-auto bg-ink-950/90 px-5 py-3 backdrop-blur [scrollbar-width:none]">
          {[{ id: 'all', name: 'Todo' }, ...categories].map(c => (
            <button key={c.id} onClick={() => setCat(c.id)}
              className={`whitespace-nowrap rounded-full px-4 py-2 text-sm transition ${cat === c.id ? 'bg-white font-semibold text-ink-950' : 'bg-ink-800 text-gray-300'}`}>
              {c.name}
            </button>
          ))}
        </nav>
      )}

      <ul className="space-y-2 px-4 pt-2">
        {visible.length === 0 && <li className="py-16 text-center text-gray-500">No hay productos en esta categoría.</li>}
        {visible.map((p, i) => {
          const q = cart[p.id] ?? 0
          return (
            <li key={p.id} style={{ animationDelay: `${Math.min(i, 8) * 35}ms` }}
              className={`flex animate-fade-up items-center gap-3 rounded-card p-2.5 pr-3 transition ${q ? 'bg-ink-700 ring-1 ring-brand-500/60' : 'bg-ink-900'} ${p.soldOut ? 'opacity-40' : ''}`}>
              <button type="button" disabled={p.soldOut} onClick={() => add(p.id, 1)} tabIndex={-1} aria-hidden="true"
                className="relative flex h-[72px] w-[72px] shrink-0 items-center justify-center overflow-hidden rounded-control bg-ink-800 text-4xl transition active:scale-95">
                {p.imageUrl
                  // eslint-disable-next-line @next/next/no-img-element
                  ? <img src={p.imageUrl} alt="" className="h-full w-full object-cover" loading={i < 6 ? 'eager' : 'lazy'} />
                  : <ProductIcon icon={p.icon} size="80%" />}
                {q > 0 && <span key={q} className="absolute right-1 top-1 flex h-6 min-w-6 animate-pop items-center justify-center rounded-full bg-brand-500 px-1.5 text-xs font-bold tabular-nums" style={{ color: 'rgb(var(--brand-ink))' }}>{q}</span>}
              </button>
              <div className="min-w-0 flex-1">
                <p className="font-semibold leading-tight">{p.name} {p.isAlcoholic && <span className="ml-1 text-[10px] text-amber-300">+18</span>}</p>
                {p.description && <p className="mt-0.5 line-clamp-1 text-sm text-gray-400">{p.description}</p>}
                <p className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1">
                  <span className="font-semibold tabular-nums text-brand-200">{p.soldOut ? 'Agotado' : formatARS(p.priceCents)}</span>
                  {p.popular && !p.soldOut && <span className="rounded-full bg-brand-500/15 px-2 py-0.5 text-[11px] font-medium text-brand-300">Lo más pedido</span>}
                  {p.lowStock && !p.soldOut && <span className="text-[11px] text-amber-300">Últimos</span>}
                </p>
              </div>
              {!p.soldOut && (q === 0 ? (
                <button onClick={() => add(p.id, 1)} aria-label={`Agregar ${p.name}`}
                  className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-white text-2xl text-ink-950 transition active:scale-90">+</button>
              ) : (
                <div className="flex shrink-0 items-center gap-1.5">
                  <button onClick={() => add(p.id, -1)} aria-label={`Quitar ${p.name}`} className="flex h-10 w-10 items-center justify-center rounded-full bg-ink-600 text-2xl active:scale-90">−</button>
                  <span key={q} className="w-5 animate-pop text-center text-lg font-bold tabular-nums">{q}</span>
                  <button onClick={() => add(p.id, 1)} aria-label={`Agregar otro ${p.name}`} className="flex h-10 w-10 items-center justify-center rounded-full bg-white text-2xl text-ink-950 active:scale-90">+</button>
                </div>
              ))}
            </li>
          )
        })}
      </ul>
      <div className="mt-10 flex justify-center"><PoweredBy brand={brand} /></div>

      {/* Barra de carrito */}
      <div className={`safe-bottom fixed inset-x-0 bottom-0 z-20 p-4 transition-transform duration-300 ${count ? 'translate-y-0' : 'translate-y-full'}`}>
        <button key={count} onClick={() => setOpen(true)} className="btn-brand w-full animate-bump justify-between px-5 py-4 text-base">
          <span className="rounded-full bg-white/25 px-2.5 py-0.5 text-sm tabular-nums">{count}</span>
          <span>Ver pedido</span>
          <span className="tabular-nums">{formatARS(total)}</span>
        </button>
      </div>

      {/* Hoja de checkout */}
      <div className={`fixed inset-0 z-30 transition ${open ? 'pointer-events-auto' : 'pointer-events-none'}`}>
        <div onClick={() => setOpen(false)} className={`absolute inset-0 bg-black/60 transition-opacity ${open ? 'opacity-100' : 'opacity-0'}`} />
        <section className={`safe-bottom absolute inset-x-0 bottom-0 max-h-[92dvh] overflow-y-auto rounded-t-[1.75rem] bg-ink-900 p-5 transition-transform duration-300 ${open ? 'translate-y-0' : 'translate-y-full'}`}>
          <div className="mx-auto mb-4 h-1 w-10 rounded-full bg-ink-600" />
          <h2 className="mb-4 text-xl font-bold">Tu pedido</h2>
          <ul className="mb-4 space-y-2">
            {lines.map(([id, q]) => (
              <li key={id} className="flex justify-between text-sm"><span>{q} × {byId.get(id)?.name}</span><span className="tabular-nums">{formatARS((byId.get(id)?.priceCents ?? 0) * q)}</span></li>
            ))}
          </ul>
          <div className="mb-5 flex justify-between border-t border-ink-700 pt-3 text-lg font-bold"><span>Total</span><span className="tabular-nums">{formatARS(total)}</span></div>

          <label className="mb-1.5 block text-sm text-gray-400" htmlFor="buyer">Tu nombre (opcional)</label>
          <input id="buyer" value={name} onChange={e => setName(e.target.value)} maxLength={40} placeholder="Para que la barra te reconozca"
            className="mb-4 w-full rounded-control border border-ink-700 bg-ink-800 px-4 py-3 text-white outline-none focus:border-brand-400" />

          {noMethods ? <p className="mb-4 text-sm text-amber-300">Este evento todavía no habilitó medios de pago.</p> : (
            <div className="mb-4 grid gap-2">
              {methods.mercadopago && <Method on={method === 'mercadopago'} onClick={() => setMethod('mercadopago')} title="MercadoPago" hint="Pagás ahora y retirás cuando esté listo" />}
              {methods.cash && <Method on={method === 'cash'} onClick={() => setMethod('cash')} title="Efectivo en caja" hint="Pagás en la caja con tu número" />}
            </div>
          )}

          {needsAge && (
            <label className="mb-4 flex items-start gap-3 rounded-control bg-amber-500/10 p-3 text-sm text-amber-200">
              <input type="checkbox" checked={adult} onChange={e => setAdult(e.target.checked)} className="mt-0.5 h-5 w-5 accent-brand-500" />
              Confirmo que soy mayor de 18 años. La barra puede pedirme DNI.
            </label>
          )}

          {error && <p className="mb-3 rounded-control bg-red-500/15 px-4 py-3 text-sm text-red-300">{error}</p>}
          <button onClick={submit} disabled={busy || noMethods || count === 0} className="btn-brand w-full py-4 text-base">
            {busy ? 'Procesando…' : method === 'mercadopago' ? `Pagar ${formatARS(total)}` : 'Confirmar y pagar en caja'}
          </button>
        </section>
      </div>
    </main>
  )
}

function Method({ on, onClick, title, hint }: { on: boolean; onClick: () => void; title: string; hint: string }) {
  return (
    <button type="button" onClick={onClick}
      className={`flex items-center gap-3 rounded-control border p-3 text-left transition ${on ? 'border-brand-400 bg-brand-500/10' : 'border-ink-700'}`}>
      <span className={`flex h-5 w-5 items-center justify-center rounded-full border-2 ${on ? 'border-brand-400' : 'border-ink-600'}`}>{on && <span className="h-2.5 w-2.5 rounded-full bg-brand-400" />}</span>
      <span><span className="block text-sm font-semibold">{title}</span><span className="text-xs text-gray-400">{hint}</span></span>
    </button>
  )
}
