"use client";

import { useEffect, useState } from "react";

type EventItem = {
  id: string;
  title: string;
  startAt: string;
  endAt: string;
  status: string;
  location?: string | null;
  description?: string | null;
};

export default function AdminPanel() {
  const [events, setEvents] = useState<EventItem[]>([]);
  const [error, setError] = useState<string | null>(null);

  const load = async () => {
    try {
      const response = await fetch("/api/events?status=PENDING");
      if (!response.ok) {
        throw new Error("Vorschlaege konnten nicht geladen werden.");
      }
      setEvents(await response.json());
    } catch (err) {
      setError((err as Error).message);
    }
  };

  useEffect(() => {
    load();
  }, []);

  const updateStatus = async (id: string, status: "APPROVED" | "REJECTED") => {
    await fetch(`/api/events/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status })
    });
    load();
  };

  return (
    <section className="space-y-4">
      <h1 className="text-2xl font-semibold">Adminfreigaben</h1>
      {error && <p className="text-sm text-red-600">{error}</p>}
      {events.length === 0 ? (
        <p className="text-slate-600">Keine offenen Vorschlaege.</p>
      ) : (
        <div className="space-y-3">
          {events.map((event) => (
            <div key={event.id} className="rounded border border-slate-200 bg-white p-4">
              <div className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
                <div>
                  <h2 className="text-lg font-medium">{event.title}</h2>
                  <p className="text-sm text-slate-600">
                    {new Date(event.startAt).toLocaleString()} - {new Date(event.endAt).toLocaleString()}
                  </p>
                  {event.location && (
                    <p className="text-sm text-slate-600">Ort: {event.location}</p>
                  )}
                </div>
                <div className="flex gap-2">
                  <button
                    type="button"
                    onClick={() => updateStatus(event.id, "APPROVED")}
                    className="rounded bg-emerald-600 px-3 py-1.5 text-white"
                  >
                    Freigeben
                  </button>
                  <button
                    type="button"
                    onClick={() => updateStatus(event.id, "REJECTED")}
                    className="rounded bg-red-600 px-3 py-1.5 text-white"
                  >
                    Ablehnen
                  </button>
                </div>
              </div>
              {event.description && (
                <p className="mt-2 text-sm text-slate-700">{event.description}</p>
              )}
            </div>
          ))}
        </div>
      )}
    </section>
  );
}
