import React from 'react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { createEvent, updateEvent } from '../api';
import { useNavigate, useSearchParams } from 'react-router-dom';

export default function EventFormPage() {
  const [sp] = useSearchParams();
  const id = sp.get('id');
  const nav = useNavigate();
  const [name, setName] = React.useState('');
  const [slug, setSlug] = React.useState('');
  const [date, setDate] = React.useState('');
  const [active, setActive] = React.useState(true);
  const [saving, setSaving] = React.useState(false);
  const isEdit = !!id;

  async function save() {
    setSaving(true);
    try {
      if (isEdit) {
        await updateEvent(Number(id), { name, slug, date, is_active: active });
      } else {
        await createEvent({ name, slug, date, is_active: active });
      }
      nav('/admin/events');
    } finally { setSaving(false); }
  }

  return (
    <div className="mx-auto max-w-md p-4 space-y-3">
      <h1 className="text-lg font-semibold">{isEdit ? 'Event bearbeiten' : 'Neues Event'}</h1>
      <Input placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} />
      <Input placeholder="Slug" value={slug} onChange={(e) => setSlug(e.target.value)} />
      <Input placeholder="Datum" type="date" value={date} onChange={(e) => setDate(e.target.value)} />
      <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={active} onChange={(e) => setActive(e.target.checked)} /> Aktiv</label>
      <div className="flex gap-2">
        <Button onClick={save} disabled={saving || !name || !slug}>{saving ? 'Speichern…' : 'Speichern'}</Button>
        <Button variant="secondary" onClick={() => nav(-1)}>Abbrechen</Button>
      </div>
    </div>
  );
}

