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

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 (err) {
        if (!isAuthError(err)) {
          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((event) => (
          <div key={event.id} className="flex items-center justify-between p-3">
            <div className="text-sm">
              <div className="font-medium">{renderName(event.name)}</div>
              <div className="text-muted-foreground">Slug: {event.slug} � Datum: {event.date ?? '-'}</div>
            </div>
            <div className="flex items-center gap-2 text-sm underline">
              <Link to={`/admin/events/view?id=${event.id}`}>details</Link>
              <Link to={`/admin/events/edit?id=${event.id}`}>bearbeiten</Link>
              <Link to={`/admin/events/photos?id=${event.id}`}>fotos</Link>
              <a href={`/e/${event.slug}`} target="_blank" rel="noreferrer">
                �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);
}
