"use client";

import { useEffect, useMemo, useState } from "react";

type EventItem = {
  id: string;
  title: string;
  startAt: string;
  endAt: string;
  status: string;
};

type ViewItem = {
  id: string;
  name: string;
  token: string;
  items: { event: EventItem }[];
};

export default function ViewManager() {
  const [views, setViews] = useState<ViewItem[]>([]);
  const [events, setEvents] = useState<EventItem[]>([]);
  const [selectedView, setSelectedView] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const load = async () => {
    try {
      const [viewsRes, eventsRes] = await Promise.all([
        fetch("/api/views"),
        fetch("/api/events?status=APPROVED")
      ]);

      if (!viewsRes.ok || !eventsRes.ok) {
        throw new Error("Daten konnten nicht geladen werden.");
      }

      const viewsData = await viewsRes.json();
      const eventsData = await eventsRes.json();
      setViews(viewsData);
      setEvents(eventsData);
      if (viewsData.length > 0 && !selectedView) {
        setSelectedView(viewsData[0].id);
      }
    } catch (err) {
      setError((err as Error).message);
    }
  };

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

  const icalBase = typeof window === "undefined" ? "" : window.location.origin;
  const activeView = useMemo(
    () => views.find((view) => view.id === selectedView) || null,
    [views, selectedView]
  );

  const createView = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const formData = new FormData(event.currentTarget);
    const name = formData.get("name");
    const response = await fetch("/api/views", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name })
    });

    if (response.ok) {
      event.currentTarget.reset();
      load();
    }
  };

  const addItem = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!selectedView) return;
    const formData = new FormData(event.currentTarget);
    const eventId = formData.get("eventId");

    await fetch(`/api/views/${selectedView}/items`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ eventId })
    });

    load();
  };

  const removeItem = async (eventId: string) => {
    if (!selectedView) return;
    await fetch(`/api/views/${selectedView}/items`, {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ eventId })
    });
    load();
  };

  return (
    <section className="space-y-6">
      <div>
        <h1 className="text-2xl font-semibold">Meine Kalenderansichten</h1>
        <p className="text-slate-600">
          Stelle dir eine persoenliche Terminansicht zusammen und abonnieren sie als iCal.
        </p>
      </div>

      {error && <p className="text-sm text-red-600">{error}</p>}

      <div className="grid gap-6 md:grid-cols-2">
        <div className="space-y-4 rounded bg-white p-4 shadow-sm">
          <h2 className="text-lg font-semibold">Neue Ansicht</h2>
          <form onSubmit={createView} className="flex gap-2">
            <input
              name="name"
              required
              placeholder="z.B. Jugendtermine"
              className="flex-1 rounded border border-slate-300 px-3 py-2"
            />
            <button className="rounded bg-brand-500 px-3 py-2 text-white" type="submit">
              Anlegen
            </button>
          </form>

          <div className="space-y-2">
            <label className="text-sm font-medium text-slate-700">Ansicht waehlen</label>
            <select
              className="w-full rounded border border-slate-300 px-3 py-2"
              value={selectedView || ""}
              onChange={(event) => setSelectedView(event.target.value)}
            >
              {views.map((view) => (
                <option key={view.id} value={view.id}>
                  {view.name}
                </option>
              ))}
            </select>
          </div>

          {activeView && (
            <div className="rounded border border-slate-200 bg-slate-50 p-3 text-sm">
              <p className="font-medium">iCal URL</p>
              <p className="break-all text-slate-700">
                {icalBase}/api/ical/{activeView.token}
              </p>
            </div>
          )}
        </div>

        <div className="space-y-4 rounded bg-white p-4 shadow-sm">
          <h2 className="text-lg font-semibold">Termine hinzufuegen</h2>
          <form onSubmit={addItem} className="space-y-3">
            <select
              name="eventId"
              className="w-full rounded border border-slate-300 px-3 py-2"
              required
            >
              <option value="" disabled>
                Termin waehlen
              </option>
              {events.map((event) => (
                <option key={event.id} value={event.id}>
                  {event.title} ({new Date(event.startAt).toLocaleDateString()})
                </option>
              ))}
            </select>
            <button className="w-full rounded bg-slate-900 px-3 py-2 text-white" type="submit">
              Zur Ansicht hinzufuegen
            </button>
          </form>

          <div className="space-y-2">
            <h3 className="text-sm font-semibold text-slate-700">Inhalte der Ansicht</h3>
            {activeView?.items.length ? (
              activeView.items.map((item) => (
                <div
                  key={item.event.id}
                  className="flex items-center justify-between rounded border border-slate-200 px-3 py-2"
                >
                  <span className="text-sm">{item.event.title}</span>
                  <button
                    type="button"
                    className="text-xs text-red-600"
                    onClick={() => removeItem(item.event.id)}
                  >
                    Entfernen
                  </button>
                </div>
              ))
            ) : (
              <p className="text-sm text-slate-500">Noch keine Termine.</p>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
