"use client";

import { useEffect, useMemo, useState } from "react";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import listPlugin from "@fullcalendar/list";
import interactionPlugin from "@fullcalendar/interaction";
import { useSession } from "next-auth/react";

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

export default function CalendarBoard() {
  const { data } = useSession();
  const [events, setEvents] = useState<EventItem[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const fetchEvents = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch("/api/events");
      if (!response.ok) {
        throw new Error("Events konnten nicht geladen werden.");
      }
      const payload = await response.json();
      setEvents(payload);
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (data?.user) {
      fetchEvents();
    }
  }, [data?.user]);

  const calendarEvents = useMemo(
    () =>
      events.map((event) => ({
        id: event.id,
        title: event.title,
        start: event.startAt,
        end: event.endAt,
        extendedProps: {
          status: event.status,
          location: event.location,
          description: event.description
        }
      })),
    [events]
  );

  if (!data?.user) {
    return (
      <div className="rounded border border-dashed border-slate-300 bg-white p-8 text-center">
        <p className="text-slate-700">
          Bitte anmelden, um die Vereinskalender zu sehen.
        </p>
      </div>
    );
  }

  return (
    <section className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-semibold">Kalender</h2>
        <button
          type="button"
          onClick={fetchEvents}
          className="rounded border border-slate-300 px-3 py-1.5 text-sm text-slate-700"
        >
          Aktualisieren
        </button>
      </div>
      {error && <p className="text-sm text-red-600">{error}</p>}
      {loading && <p className="text-sm text-slate-500">Lade Termine...</p>}
      <div className="rounded bg-white p-4 shadow-sm">
        <FullCalendar
          plugins={[dayGridPlugin, timeGridPlugin, listPlugin, interactionPlugin]}
          initialView="dayGridMonth"
          headerToolbar={{
            left: "prev,next today",
            center: "title",
            right: "dayGridMonth,timeGridWeek,listWeek"
          }}
          events={calendarEvents}
          eventContent={(arg) => {
            const status = arg.event.extendedProps.status;
            return (
              <div>
                <div className="text-sm font-medium">{arg.event.title}</div>
                {status !== "APPROVED" && (
                  <div className="text-xs text-amber-600">{status}</div>
                )}
              </div>
            );
          }}
          height="auto"
        />
      </div>
    </section>
  );
}
