import { asc, eq } from 'drizzle-orm'
import { db, schema } from '@/db'
import { requireEvent } from '@/lib/auth'
import { resetStationPin, toggleStation } from '@/app/actions/panel'
import StationForm from './StationForm'

export default async function StationsPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  await requireEvent(id)
  const stations = await db.select().from(schema.stations).where(eq(schema.stations.eventId, id)).orderBy(asc(schema.stations.createdAt))
  const appUrl = process.env.APP_URL ?? ''

  return (
    <div className="grid gap-6 lg:grid-cols-[1fr_340px]">
      <section className="space-y-3">
        <p className="text-sm text-gray-500">Cada barra o caja abre su link en un celular o tablet e ingresa el PIN. Funciona aunque se corte internet.</p>
        {stations.map(s => (
          <div key={s.id} className={`card space-y-3 p-4 ${s.active ? '' : 'opacity-50'}`}>
            <div className="flex items-center justify-between gap-3">
              <div>
                <p className="font-semibold">{s.name} <span className="chip ml-1 bg-gray-100 text-gray-600">{s.kind === 'bar' ? 'Barra' : 'Caja'}</span></p>
                {s.kind === 'bar' && <p className="text-xs text-gray-400">Prepara: {s.routeTags.join(', ') || 'todo'}</p>}
              </div>
              <form action={toggleStation.bind(null, id, s.id)}><button className="btn-ghost px-3 py-2 text-xs">{s.active ? 'Desactivar' : 'Activar'}</button></form>
            </div>
            <p className="break-all rounded-control bg-gray-50 px-3 py-2 font-mono text-xs">{appUrl}/estacion/{s.id}</p>
            <form action={resetStationPin.bind(null, id, s.id)} className="flex gap-2">
              <input name="pin" inputMode="numeric" pattern="\d{4,8}" className="input py-2" placeholder="Nuevo PIN" />
              <button className="btn-ghost border border-gray-200 py-2 text-xs">Cambiar PIN</button>
            </form>
          </div>
        ))}
      </section>
      <StationForm eventId={id} />
    </div>
  )
}
