'use client'

import { useActionState } from 'react'
import { createEvent } from '@/app/actions/panel'

export default function NewEventForm() {
  const [state, action, pending] = useActionState(createEvent, undefined)
  return (
    <form action={action} className="card space-y-5 p-6">
      <div>
        <label className="label" htmlFor="name">Nombre del evento</label>
        <input id="name" name="name" required className="input" placeholder="Fiesta de Egresados 2026" />
      </div>
      <div>
        <label className="label" htmlFor="description">Descripción (opcional)</label>
        <input id="description" name="description" className="input" placeholder="Salón Los Álamos · 22 hs" />
      </div>
      <div className="grid gap-4 sm:grid-cols-2">
        <div><label className="label" htmlFor="startsAt">Empieza</label><input id="startsAt" name="startsAt" type="datetime-local" className="input" /></div>
        <div><label className="label" htmlFor="endsAt">Termina</label><input id="endsAt" name="endsAt" type="datetime-local" className="input" /></div>
      </div>
      <fieldset className="space-y-3">
        <legend className="label">Cómo se cobra</legend>
        <Toggle name="allowMercadoPago" defaultChecked title="MercadoPago" hint="El público paga desde el celular" />
        <Toggle name="allowCash" defaultChecked title="Efectivo en caja" hint="Para quien no quiere pagar digital" />
      </fieldset>
      <Toggle name="minors" title="Modo menores (egresados, eventos familiares)" hint="Bloquea todo producto con alcohol, muestra el sello «Evento sin alcohol» y habilita el certificado de cierre para el colegio y las familias" />
      {state?.error && <p className="rounded-control bg-red-50 px-4 py-3 text-sm text-red-700">{state.error}</p>}
      <button className="btn-primary w-full" disabled={pending}>{pending ? 'Creando…' : 'Crear evento y cargar el menú'}</button>
    </form>
  )
}

function Toggle({ name, title, hint, defaultChecked }: { name: string; title: string; hint: string; defaultChecked?: boolean }) {
  return (
    <label className="flex cursor-pointer items-start gap-3 rounded-control border border-gray-200 p-3 has-[:checked]:border-brand-400 has-[:checked]:bg-brand-50/40">
      <input type="checkbox" name={name} defaultChecked={defaultChecked} className="mt-0.5 h-5 w-5 accent-brand-500" />
      <span><span className="block text-sm font-medium">{title}</span><span className="text-xs text-gray-500">{hint}</span></span>
    </label>
  )
}
