'use client'

import { useCallback, useState } from 'react'
import { addCategory, deleteProduct, moveProduct, toggleProduct } from '@/app/actions/panel'
import { formatARS } from '@/lib/money'
import ProductSheet, { type EditableProduct } from './ProductSheet'
import ProductIcon from '@/components/ProductIcon'
import { resolveIcon } from '@/lib/icons'

type Row = EditableProduct & { priceCents: number; available: boolean }

export default function MenuEditor({ eventId, minors, categories, products }: {
  eventId: string; minors: boolean; categories: { id: string; name: string }[]; products: Row[]
}) {
  const [editing, setEditing] = useState<{ product: Row | null; category: string | null } | null>(null)
  const close = useCallback(() => setEditing(null), [])

  const groups = [
    ...categories.map(c => ({ id: c.id as string | null, name: c.name, items: products.filter(p => p.categoryId === c.id) })),
    { id: null, name: 'Sin categoría', items: products.filter(p => !p.categoryId || !categories.some(c => c.id === p.categoryId)) },
  ].filter(g => g.items.length || g.id)

  return (
    <>
      <div className="flex flex-wrap items-center gap-2">
        <button onClick={() => setEditing({ product: null, category: null })} className="btn-primary">+ Agregar producto</button>
        <form action={addCategory.bind(null, eventId)} className="flex gap-2">
          <input name="name" className="input w-48 py-2.5" placeholder="Nueva categoría" aria-label="Nueva categoría" />
          <button className="btn-ghost border border-gray-200 px-3">Crear</button>
        </form>
      </div>

      <div className="space-y-6">
        {groups.map(g => (
          <section key={g.id ?? 'none'}>
            <div className="mb-2 flex items-center justify-between">
              <h3 className="text-xs font-semibold uppercase tracking-widest text-gray-400">{g.name} <span className="font-normal">· {g.items.length}</span></h3>
              {g.id && <button onClick={() => setEditing({ product: null, category: g.id })} className="text-xs font-medium text-gray-500 hover:text-gray-900">+ Agregar acá</button>}
            </div>
            {g.items.length === 0 && <p className="rounded-card border border-dashed border-gray-200 p-4 text-center text-sm text-gray-400">Vacía</p>}
            <ul className="space-y-2">
              {g.items.map(p => {
                const hidden = minors && p.isAlcoholic
                return (
                  <li key={p.id} className={`card group flex items-center gap-3 p-2.5 pr-3 transition hover:shadow-md ${p.available && !hidden ? '' : 'opacity-50'}`}>
                    <button onClick={() => setEditing({ product: p, category: null })} className="flex min-w-0 flex-1 items-center gap-3 text-left" aria-label={`Editar ${p.name}`}>
                      <span className="flex h-14 w-14 shrink-0 items-center justify-center overflow-hidden rounded-control bg-ink-900 text-3xl">
                        {p.imageUrl
                          // eslint-disable-next-line @next/next/no-img-element
                          ? <img src={p.imageUrl} alt="" className="h-full w-full object-cover" loading="lazy" />
                          : <ProductIcon icon={resolveIcon(p.icon, p.name)} size="78%" />}
                      </span>
                      <span className="min-w-0 flex-1">
                        <span className="block truncate font-medium">{p.name}
                          {p.isAlcoholic && <span className="chip ml-1.5 bg-amber-50 py-0.5 text-amber-700">+18</span>}
                        </span>
                        <span className="block truncate text-xs text-gray-400">
                          {hidden ? 'Oculto: evento con menores' : !p.available ? 'Pausado' : p.stock === null ? 'Stock libre' : p.stock === 0 ? 'Agotado' : `Quedan ${p.stock}`}
                          {' · '}{p.routeTag}
                        </span>
                      </span>
                      <span className="font-semibold tabular-nums">{formatARS(p.priceCents)}</span>
                    </button>
                    <div className="flex items-center">
                      <form action={moveProduct.bind(null, eventId, p.id, 'up')}><button className="btn-ghost h-8 w-8 p-0 text-gray-400" aria-label="Subir">↑</button></form>
                      <form action={moveProduct.bind(null, eventId, p.id, 'down')}><button className="btn-ghost h-8 w-8 p-0 text-gray-400" aria-label="Bajar">↓</button></form>
                      <form action={toggleProduct.bind(null, eventId, p.id)}>
                        <button className={`ml-1 rounded-full px-2.5 py-1 text-xs font-medium ${p.available ? 'bg-green-50 text-green-700' : 'bg-gray-100 text-gray-500'}`}>{p.available ? 'A la venta' : 'Pausado'}</button>
                      </form>
                      <form action={deleteProduct.bind(null, eventId, p.id)} onSubmit={e => { if (!confirm(`¿Borrar «${p.name}»?`)) e.preventDefault() }}>
                        <button className="btn-ghost h-8 w-8 p-0 text-gray-300 hover:text-red-600" aria-label="Borrar">✕</button>
                      </form>
                    </div>
                  </li>
                )
              })}
            </ul>
          </section>
        ))}
      </div>

      {editing && (
        <ProductSheet key={editing.product?.id ?? `new-${editing.category}`} eventId={eventId} product={editing.product}
          categories={categories} defaultCategory={editing.category} minors={minors} onClose={close} />
      )}
    </>
  )
}
