import React from 'react';
import { getEvents } from '../api';
import { Button } from '@/components/ui/button';
import { Link, useNavigate } from 'react-router-dom';

export default function EventsPage() {
  const [rows, setRows] = React.useState<any[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const nav = useNavigate();

  React.useEffect(() => {
    (async () => {
      try { setRows(await getEvents()); } catch (e) { setError('Laden fehlgeschlagen'); } finally { setLoading(false); }
    })();
  }, []);

  return (
    <div className="mx-auto max-w-3xl p-4">
      <div className="mb-3 flex items-center justify-between">
        <h1 className="text-lg font-semibold">Meine Events</h1>
        <div className="flex gap-2">
          <Button variant="secondary" onClick={() => nav('/admin/events/new')}>Neues Event</Button>
          <Link to="/admin/settings"><Button variant="secondary">Einstellungen</Button></Link>
        </div>
      </div>
      {loading && <div>Lade…</div>}
      {error && <div className="rounded border border-red-300 bg-red-50 p-2 text-sm text-red-700">{error}</div>}
      <div className="divide-y rounded border">
        {rows.map((e) => (
          <div key={e.id} className="flex items-center justify-between p-3">
            <div className="text-sm">
              <div className="font-medium">{renderName(e.name)}</div>
              <div className="text-muted-foreground">Slug: {e.slug} · Datum: {e.date ?? '-'}</div>
            </div>
            <div className="flex items-center gap-2">
              <Link to={`/admin/events/view?id=${e.id}`} className="text-sm underline">details</Link>
              <Link to={`/admin/events/edit?id=${e.id}`} className="text-sm underline">bearbeiten</Link>
              <Link to={`/admin/events/photos?id=${e.id}`} className="text-sm underline">fotos</Link>
              <a className="text-sm underline" href={`/e/${e.slug}`} target="_blank">öffnen</a>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function renderName(name: any): string {
  if (typeof name === 'string') return name;
  if (name && (name.de || name.en)) return name.de || name.en;
  return JSON.stringify(name);
}
