import { UghIcon } from './Logo'
import { OrgMark } from './OrgBrand'
import type { PublicBrand } from '@/lib/org-brand'
import { formatARS } from '@/lib/money'
import type { eventClosingReport } from '@/lib/certificate'

type Report = NonNullable<Awaited<ReturnType<typeof eventClosingReport>>>

const fmtDate = (d: Date | string | null) =>
  d ? new Date(d).toLocaleString('es-AR', { day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' }) : '—'

/** Certificado imprimible. `audience="public"` oculta importes (para familias y colegio). */
export default function ClosingCertificate({ r, audience, brand }: { r: Report; audience: 'organizer' | 'public'; brand: PublicBrand }) {
  const showMoney = audience === 'organizer'
  const m = r.minors
  return (
    <article style={brand.style} className="mx-auto max-w-2xl overflow-hidden rounded-card border border-gray-200 bg-white text-ink-950 shadow-card print:max-w-none print:border-0 print:shadow-none">
      <header className="flex items-center justify-between bg-ink-950 px-6 py-5 text-piedra">
        {brand.logoUrl || brand.whiteLabel
          ? <OrgMark brand={brand} height={30} className="text-piedra" />
          : <span className="inline-flex items-center gap-2"><UghIcon size={30} /><span className="font-display text-lg"><b>Ugh</b><span className="font-light text-[#ff5500]">Pass</span></span></span>}
        <span className="font-mono text-xs text-gray-400">{r.code}</span>
      </header>

      <div className="space-y-6 p-6 md:p-8">
        <div>
          <p className="text-xs uppercase tracking-widest text-gray-400">{m.enabled ? 'Certificado de evento sin alcohol' : 'Reporte de cierre'}</p>
          <h1 className="mt-1 text-3xl font-bold">{r.event.name}</h1>
          <p className="text-sm text-gray-500">{r.orgName}{r.event.description ? ` · ${r.event.description}` : ''}</p>
        </div>

        {m.enabled && (
          <section className={`rounded-control border-2 p-4 ${m.clean ? 'border-emerald-500 bg-emerald-50' : 'border-amber-500 bg-amber-50'}`}>
            <p className={`text-lg font-bold ${m.clean ? 'text-emerald-800' : 'text-amber-800'}`}>
              {m.clean ? '✓ Cero bebidas con alcohol vendidas' : '⚠ Revisar: el certificado no es completo'}
            </p>
            <ul className={`mt-2 space-y-1 text-sm ${m.clean ? 'text-emerald-900' : 'text-amber-900'}`}>
              <li>Modo menores activo desde: <b>{fmtDate(m.since)}</b></li>
              <li>{m.coversWholeEvent ? 'Rigió desde antes del primer pedido del evento.' : 'Se activó con pedidos ya realizados o se desactivó en algún momento.'}</li>
              <li>Unidades con alcohol vendidas: <b>{m.alcoholUnits}</b></li>
            </ul>
          </section>
        )}

        <section className="grid grid-cols-2 gap-3 text-sm sm:grid-cols-3">
          <Fact label="Pedidos" value={String(r.totals.orders)} />
          <Fact label="Entregados" value={String(r.totals.delivered)} />
          <Fact label="Primer pedido" value={fmtDate(r.totals.firstAt)} />
          <Fact label="Último pedido" value={fmtDate(r.totals.lastAt)} />
          {showMoney && <Fact label="Total vendido" value={formatARS(r.totals.revenue)} />}
          {showMoney && <Fact label="Efectivo / digital" value={`${formatARS(r.totals.cash)} / ${formatARS(r.totals.digital)}`} />}
        </section>

        <section>
          <p className="mb-2 text-xs uppercase tracking-widest text-gray-400">Productos vendidos</p>
          {r.products.length === 0 ? <p className="text-sm text-gray-400">Sin ventas.</p> : (
            <table className="w-full text-sm">
              <tbody className="divide-y divide-gray-100">
                {r.products.map(p => (
                  <tr key={p.name + String(p.isAlcoholic)}>
                    <td className="py-2">{p.name}{p.isAlcoholic && <span className="ml-2 rounded bg-amber-100 px-1.5 py-0.5 text-xs text-amber-800">alcohol</span>}</td>
                    <td className="py-2 text-right tabular-nums">{p.qty} u.</td>
                    {showMoney && <td className="w-32 py-2 text-right tabular-nums text-gray-500">{formatARS(p.revenue)}</td>}
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </section>

        <footer className="border-t border-gray-100 pt-4 text-xs text-gray-400">
          Generado automáticamente {brand.whiteLabel ? 'por el sistema de pedidos' : 'por UghPass'} a partir de sus registros; no se puede editar a mano. Código de verificación {r.code}.
        </footer>
      </div>
    </article>
  )
}

function Fact({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-control bg-gray-50 p-3">
      <p className="text-xs text-gray-400">{label}</p>
      <p className="mt-0.5 font-semibold tabular-nums">{value}</p>
    </div>
  )
}
