import { notFound } from 'next/navigation'
import { and, asc, eq, gt, inArray, sql } from 'drizzle-orm'
import { db, schema } from '@/db'
import { brandMetadata, getPublicBrand } from '@/lib/org-brand'
import MenuClient from './MenuClient'
import { resolveIcon } from '@/lib/icons'

export const dynamic = 'force-dynamic'

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const [e] = await db.select({ name: schema.events.name, orgId: schema.events.orgId }).from(schema.events).where(eq(schema.events.slug, slug))
  return brandMetadata(e?.orgId, e?.name ?? 'Menú')
}

export default async function MenuPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const [event] = await db.select().from(schema.events).where(eq(schema.events.slug, slug))
  if (!event) notFound()
  const brand = (await getPublicBrand(event.orgId))!

  if (event.status !== 'active' || brand.suspended) {
    return (
      <main style={brand.style} className="flex min-h-dvh items-center justify-center bg-ink-950 px-6 text-center text-white">
        <div>
          <p className="text-2xl font-bold">{event.name}</p>
          <p className="mt-2 text-gray-400">{event.status === 'paused' ? 'Los pedidos están pausados un momento.' : 'Este evento no está recibiendo pedidos.'}</p>
        </div>
      </main>
    )
  }

  const [org] = await db.select({ mp: schema.organizations.mpUserId }).from(schema.organizations).where(eq(schema.organizations.id, event.orgId))
  const cats = await db.select().from(schema.categories).where(eq(schema.categories.eventId, event.id)).orderBy(asc(schema.categories.position))
  let prods = await db.select().from(schema.products)
    .where(and(eq(schema.products.eventId, event.id), eq(schema.products.available, true)))
    .orderBy(asc(schema.products.position), asc(schema.products.createdAt))
  if (!event.alcoholAllowed) prods = prods.filter(p => !p.isAlcoholic)

  // «Lo más pedido»: los 3 productos con más unidades en la última hora y media (si hay movimiento real).
  const top = await db.select({ productId: schema.orderItems.productId, qty: sql<number>`sum(${schema.orderItems.quantity})::int` })
    .from(schema.orderItems).innerJoin(schema.orders, eq(schema.orders.id, schema.orderItems.orderId))
    .where(and(eq(schema.orders.eventId, event.id), inArray(schema.orders.status, ['paid', 'preparing', 'ready', 'delivered']),
      gt(schema.orders.paidAt, new Date(Date.now() - 90 * 60_000))))
    .groupBy(schema.orderItems.productId).orderBy(sql`2 desc`).limit(3)
  const popular = new Set(top.filter(t => t.qty >= 3).map(t => t.productId))

  return (
    <div style={brand.style}>
    <MenuClient
      brand={{ name: brand.name, logoUrl: brand.logoUrl, whiteLabel: brand.whiteLabel, custom: brand.custom }}
      event={{ id: event.id, name: event.name, description: event.description, minors: !event.alcoholAllowed }}
      methods={{ mercadopago: event.allowMercadoPago && Boolean(org?.mp), cash: event.allowCash }}
      categories={cats.map(c => ({ id: c.id, name: c.name }))}
      products={prods.map(p => ({
        id: p.id, name: p.name, description: p.description, priceCents: p.priceCents,
        categoryId: p.categoryId, isAlcoholic: p.isAlcoholic, soldOut: p.stock !== null && p.stock <= 0,
        icon: resolveIcon(p.icon, p.name), imageUrl: p.imageUpdatedAt ? `/api/productos/${p.id}/imagen?v=${p.imageUpdatedAt.getTime()}` : null,
        popular: popular.has(p.id), lowStock: p.stock !== null && p.stock > 0 && p.stock <= 10,
      }))}
    />
    </div>
  )
}
