"use client";

import { useEffect, useState } from "react";

export default function ViewManager() {
  const [view, setView] = useState<{
    id: string;
    name: string;
    token: string;
    icalPastDays?: number;
  } | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [appName, setAppName] = useState("Vereinskalender");

  const load = async () => {
    try {
      const viewRes = await fetch("/api/views/default");
      if (!viewRes.ok) {
        throw new Error("Daten konnten nicht geladen werden.");
      }
      setView(await viewRes.json());
    } catch (err) {
      setError((err as Error).message);
    }
  };

  const loadAppName = async () => {
    try {
      const nameResponse = await fetch("/api/settings/app-name");
      if (nameResponse.ok) {
        const payload = await nameResponse.json();
        setAppName(payload.name || "Vereinskalender");
      }
    } catch {
      // ignore
    }
  };

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

  useEffect(() => {
    const handler = () => load();
    window.addEventListener("views-updated", handler);
    return () => window.removeEventListener("views-updated", handler);
  }, []);

  const toFilename = (value: string) =>
    value
      .trim()
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/(^-|-$)/g, "") || "kalender";

  const icalBase = typeof window === "undefined" ? "" : window.location.origin;

  return (
    <section className="space-y-6 fade-up">
      <div>
        <p className="text-xs uppercase tracking-[0.2em] text-slate-500">Persönlich</p>
        <h1 className="text-2xl font-semibold">Meine Terminansicht</h1>
        <p className="text-slate-600">
          Stelle dir eine persönliche Terminansicht zusammen und abonniere sie als iCal.
        </p>
      </div>

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

      <div className="card space-y-4">
        <h2 className="text-lg font-semibold">Deine Standardansicht</h2>
        <p className="text-sm text-slate-600">
          Diese Ansicht kannst du im Kalender oder in der Listenansicht direkt befüllen.
        </p>
        {view && (
          <div className="rounded-xl 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/{view.token}/{toFilename(appName)}.ical{
                view.icalPastDays && view.icalPastDays > 0
                  ? `?pastDays=${view.icalPastDays}`
                  : ""
              }
            </p>
          </div>
        )}
      </div>
    </section>
  );
}
