"use client";

import { useEffect, useRef, useState } from "react";
import { signOut, useSession } from "next-auth/react";

export default function SettingsPage() {
  const { data } = useSession();
  const [viewToken, setViewToken] = useState<string | null>(null);
  const [viewId, setViewId] = useState<string | null>(null);
  const [subscribedCategories, setSubscribedCategories] = useState<Set<string>>(new Set());
  const [allCategories, setAllCategories] = useState<{ id: string; name: string }[]>([]);
  const [categoryError, setCategoryError] = useState<string | null>(null);
  const [categoryStatus, setCategoryStatus] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [status, setStatus] = useState<string | null>(null);
  const [profileError, setProfileError] = useState<string | null>(null);
  const [profileStatus, setProfileStatus] = useState<string | null>(null);
  const [theme, setTheme] = useState<"light" | "dark">("light");
  const [copyStatus, setCopyStatus] = useState<"success" | "error" | null>(null);
  const [appName, setAppName] = useState("Vereinskalender");
  const [icalPastDays, setIcalPastDays] = useState(14);
  const icalReadyRef = useRef(false);

  const loadView = async () => {
    try {
      const response = await fetch("/api/views/default");
      if (!response.ok) return;
      const payload = await response.json();
      setViewToken(payload.token);
      setViewId(payload.id);
      setIcalPastDays(
        typeof payload.icalPastDays === "number" ? payload.icalPastDays : 14
      );
      icalReadyRef.current = true;
      const ids = new Set<string>(
        (payload.categories || []).map((item: { categoryId: string }) => item.categoryId)
      );
      setSubscribedCategories(ids);
    } catch {
      // ignore
    }
  };

  const loadCategories = async () => {
    try {
      const response = await fetch("/api/categories");
      if (!response.ok) return;
      setAllCategories(await response.json());
    } catch {
      // ignore
    }
  };

  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(() => {
    if (data?.user) {
      loadView();
      loadCategories();
      loadAppName();
    }
  }, [data?.user]);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const saved = window.localStorage.getItem("theme");
    const next = saved === "dark" ? "dark" : "light";
    setTheme(next);
    document.documentElement.dataset.theme = next;
  }, []);

  const rotateToken = async () => {
    setError(null);
    setStatus(null);
    setCopyStatus(null);
    const response = await fetch("/api/views/default/rotate", { method: "POST" });
    if (!response.ok) {
      const payload = await response.json();
      setError(payload.error || "Token konnte nicht erneuert werden.");
      return;
    }
    const payload = await response.json();
    setViewToken(payload.token);
    setStatus("Neuer iCal-Link erstellt.");
  };

  const updateProfile = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setProfileError(null);
    setProfileStatus(null);
    const formData = new FormData(event.currentTarget);
    const payload = {
      currentPassword: formData.get("currentPassword"),
      newEmail: formData.get("newEmail"),
      newPassword: formData.get("newPassword")
    };

    const response = await fetch("/api/profile", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload)
    });

    if (!response.ok) {
      const data = await response.json();
      setProfileError(data.error || "Profil konnte nicht aktualisiert werden.");
      return;
    }

    const dataRes = await response.json();
    setProfileStatus("Profil aktualisiert.");
    if (dataRes.changedEmail || dataRes.changedPassword) {
      setProfileStatus("Profil aktualisiert. Bitte erneut anmelden.");
      await signOut({ callbackUrl: "/login" });
    }
  };

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

  const icalQuery = icalPastDays > 0 ? `?pastDays=${icalPastDays}` : "";
  const icalUrl = viewToken
    ? `${baseUrl}/api/ical/${viewToken}/${toFilename(appName)}.ical${icalQuery}`
    : "";

  const updateIcalPastDays = async (value: number) => {
    setError(null);
    setStatus(null);
    const response = await fetch("/api/views/default", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ icalPastDays: value })
    });
    if (!response.ok) {
      const data = await response.json();
      setError(data.error || "Einstellung konnte nicht gespeichert werden.");
      return;
    }
    setStatus("iCal-Einstellung gespeichert.");
    window.setTimeout(() => setStatus(null), 2500);
  };

  useEffect(() => {
    if (!icalReadyRef.current || !viewId) return;
    updateIcalPastDays(icalPastDays);
  }, [icalPastDays, viewId]);

  const applyTheme = (next: "light" | "dark") => {
    setTheme(next);
    if (typeof window !== "undefined") {
      window.localStorage.setItem("theme", next);
      document.documentElement.dataset.theme = next;
    }
  };

  const copyIcalUrl = async () => {
    if (!icalUrl) return;
    setCopyStatus(null);
    try {
      if (navigator.clipboard?.writeText) {
        await navigator.clipboard.writeText(icalUrl);
      } else {
        const textarea = document.createElement("textarea");
        textarea.value = icalUrl;
        textarea.setAttribute("readonly", "true");
        textarea.style.position = "absolute";
        textarea.style.left = "-9999px";
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand("copy");
        document.body.removeChild(textarea);
      }
      setCopyStatus("success");
    } catch {
      setCopyStatus("error");
    }
    window.setTimeout(() => setCopyStatus(null), 2500);
  };

  const toggleCategory = async (categoryId: string) => {
    if (!viewId) return;
    setCategoryError(null);
    setCategoryStatus(null);
    const isSubscribed = subscribedCategories.has(categoryId);
    const response = await fetch(`/api/views/${viewId}/categories`, {
      method: isSubscribed ? "DELETE" : "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ categoryId })
    });

    if (!response.ok) {
      const payload = await response.json();
      setCategoryError(payload.error || "Kategorien konnten nicht aktualisiert werden.");
      return;
    }

    const next = new Set(subscribedCategories);
    if (isSubscribed) {
      next.delete(categoryId);
      setCategoryStatus("Kategorie entfernt.");
    } else {
      next.add(categoryId);
      setCategoryStatus("Kategorie abonniert.");
    }
    setSubscribedCategories(next);
  };

  if (!data?.user) {
    return (
      <div className="card-muted text-center">
        <p className="text-slate-700">
          Bitte anmelden, um Einstellungen zu verwalten.
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <section className="card space-y-4">
        <div>
          <p className="text-xs uppercase tracking-[0.2em] text-slate-500">Profil</p>
          <h1 className="text-2xl font-semibold">Einstellungen</h1>
        </div>
        <form onSubmit={updateProfile} className="grid gap-3 md:grid-cols-2">
          <input
            name="newEmail"
            type="email"
            placeholder={`Neue E-Mail (aktuell: ${data?.user?.email || ""})`}
            className="rounded-xl border border-slate-300 px-3 py-2 md:col-span-2"
          />
          <input
            name="newPassword"
            type="password"
            placeholder="Neues Passwort"
            className="rounded-xl border border-slate-300 px-3 py-2"
          />
          <input
            name="currentPassword"
            type="password"
            placeholder="Aktuelles Passwort (Pflicht)"
            required
            className="rounded-xl border border-slate-300 px-3 py-2"
          />
          <button type="submit" className="btn-accent md:col-span-2">
            Speichern
          </button>
        </form>
        {profileStatus && (
          <p className="text-sm text-emerald-600">{profileStatus}</p>
        )}
        {profileError && <p className="text-sm text-red-600">{profileError}</p>}
      </section>

      <section className="card space-y-4">
        <div>
          <p className="text-xs uppercase tracking-[0.2em] text-slate-500">
            Darstellung
          </p>
          <h2 className="text-lg font-semibold">Theme</h2>
        </div>
        <div className="flex flex-wrap gap-2">
          <button
            type="button"
            onClick={() => applyTheme("light")}
            className={`rounded-full border px-4 py-2 text-sm font-semibold transition ${
              theme === "light"
                ? "border-slate-900 bg-slate-900 text-white"
                : "border-slate-200 text-slate-700 hover:bg-slate-100"
            }`}
          >
            Hell
          </button>
          <button
            type="button"
            onClick={() => applyTheme("dark")}
            className={`rounded-full border px-4 py-2 text-sm font-semibold transition ${
              theme === "dark"
                ? "border-slate-900 bg-slate-900 text-white"
                : "border-slate-200 text-slate-700 hover:bg-slate-100"
            }`}
          >
            Dunkel
          </button>
        </div>
      </section>

      <section className="card space-y-3">
        <div>
          <p className="text-xs uppercase tracking-[0.2em] text-slate-500">iCal</p>
          <h2 className="text-lg font-semibold">Persönlicher Kalenderlink</h2>
        </div>
        <p className="text-sm text-slate-600">
          Dein Link kann in externen Kalender-Apps abonniert werden.
        </p>
        {viewToken ? (
          <div className="ical-link flex items-center gap-3 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm">
            <span className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">
              iCal
            </span>
            <span
              className="min-w-0 flex-1 truncate text-slate-700"
              title={icalUrl}
            >
              {icalUrl}
            </span>
            <div className="relative flex items-center">
              <button
                type="button"
                onClick={copyIcalUrl}
                aria-label="iCal-Link kopieren"
                className="rounded-full border border-slate-200 p-2 text-slate-600 transition hover:bg-slate-100"
              >
                <svg
                  viewBox="0 0 24 24"
                  className="h-4 w-4"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                >
                  <rect x="9" y="9" width="13" height="13" rx="2" />
                  <rect x="3" y="3" width="13" height="13" rx="2" />
                </svg>
              </button>
              {copyStatus && (
                <div
                  className={`absolute right-0 top-full mt-2 rounded-full px-3 py-1 text-[11px] font-semibold shadow ${
                    copyStatus === "success"
                      ? "bg-emerald-100 text-emerald-700"
                      : "bg-rose-100 text-rose-700"
                  }`}
                >
                  {copyStatus === "success" ? "Kopiert" : "Fehler"}
                </div>
              )}
            </div>
          </div>
        ) : (
          <p className="text-sm text-slate-600">iCal-Link wird geladen...</p>
        )}
        <div className="flex flex-wrap items-center gap-3">
          <label className="flex items-center gap-3 text-sm text-slate-700">
            <span className="relative inline-flex h-6 w-11 items-center">
              <input
                type="checkbox"
                className="peer sr-only"
                checked={icalPastDays > 0}
                onChange={(event) => setIcalPastDays(event.target.checked ? 14 : 0)}
              />
              <span className="h-6 w-11 rounded-full bg-slate-200 transition peer-checked:bg-emerald-500"></span>
              <span className="absolute left-1 top-1 h-4 w-4 rounded-full bg-white transition peer-checked:translate-x-5"></span>
            </span>
            Rückblick der letzten 14 Tage aktivieren
          </label>
        </div>
        <button type="button" className="hidden" onClick={rotateToken}>
          Link erneuern
        </button>
        {status && (
          <div className="fixed bottom-6 right-6 z-40 rounded-full bg-emerald-600 px-4 py-2 text-sm font-semibold text-white shadow-lg">
            {status}
          </div>
        )}
        {error && <p className="text-sm text-red-600">{error}</p>}
      </section>

      <section className="card space-y-4">
        <div>
          <p className="text-xs uppercase tracking-[0.2em] text-slate-500">
            Kategorien
          </p>
          <h2 className="text-lg font-semibold">Kategorien abonnieren</h2>
        </div>
        {allCategories.length === 0 ? (
          <p className="text-sm text-slate-600">Noch keine Kategorien vorhanden.</p>
        ) : (
          <div className="flex flex-wrap gap-2">
            {allCategories.map((category) => {
              const isSubscribed = subscribedCategories.has(category.id);
              return (
                <button
                  key={category.id}
                  type="button"
                  className={`rounded-full border px-3 py-1 text-xs ${
                    isSubscribed
                      ? "border-emerald-200 bg-emerald-50 text-emerald-700"
                      : "border-slate-200 text-slate-700"
                  }`}
                  onClick={() => toggleCategory(category.id)}
                >
                  {category.name}
                </button>
              );
            })}
          </div>
        )}
        {categoryStatus && (
          <p className="text-sm text-emerald-600">{categoryStatus}</p>
        )}
        {categoryError && <p className="text-sm text-red-600">{categoryError}</p>}
      </section>
    </div>
  );
}
