"use client";

import { useEffect, useState } from "react";
import { Icon } from "@/components/ui/Icon";

type Module = { href: string; label: string; icon: string };

const DESC: Record<string, string> = {
  "/chat": "Nachrichten & Kanäle",
  "/kanban": "Aufgaben auf Boards",
  "/projects": "Laufende Projekte",
  "/creators": "Creator & ihre Zahlen",
  "/time": "Kommen, gehen & Stunden",
  "/absences": "Urlaub & Krankmeldungen",
  "/calendar": "Termine & Besprechungen",
  "/meetings": "Besprechungen planen",
  "/positions": "Offene Stellen der Website",
  "/applications": "Eingegangene Bewerbungen",
  "/contact": "Anfragen über die Website",
  "/vault": "Passwörter & Zugangsdaten",
  "/cloud": "Dateien & gemeinsame Ordner",
  "/changelog": "Protokolle & Changelogs",
  "/personnel": "Team, Zeiten & Freigaben",
  "/admin": "Nutzer, Rollen & System",
};

// Individuelle Akzentfarbe je Modul für farblich unterscheidbare Icon-Kacheln.
const ACCENT: Record<string, string> = {
  "/chat": "#9ed7ff",
  "/kanban": "#c8bcff",
  "/projects": "#7ee787",
  "/creators": "#ff9fd7",
  "/positions": "#9ee6b8",
  "/applications": "#ffb27a",
  "/contact": "#7fe3d4",
  "/time": "#ffc36b",
  "/absences": "#38bdf8",
  "/calendar": "#ff7a9c",
  "/meetings": "#a0f0e0",
  "/vault": "#f7c948",
  "/cloud": "#8fd3ff",
  "/changelog": "#b8a6ff",
  "/personnel": "#a0f0e0",
  "/admin": "#bec6ff",
};
const accentOf = (href: string) => ACCENT[href] ?? "#9ed7ff";

/**
 * Personalisierbarer Schnellzugriff — nur freigegebene Module; Auswahl wird
 * pro Nutzer lokal gespeichert.
 */
export function QuickAccess({ modules, userId }: { modules: Module[]; userId: string }) {
  const storageKey = `avaria:quickaccess:${userId}`;
  const [selected, setSelected] = useState<string[]>([]);
  const [editing, setEditing] = useState(false);
  const [ready, setReady] = useState(false);

  useEffect(() => {
    let initial: string[] | null = null;
    try {
      const raw = localStorage.getItem(storageKey);
      if (raw) initial = JSON.parse(raw);
    } catch {
      /* ignore */
    }
    const valid = new Set(modules.map((m) => m.href));
    setSelected((initial ?? modules.map((m) => m.href)).filter((h) => valid.has(h)));
    setReady(true);
  }, [storageKey, modules]);

  const persist = (next: string[]) => {
    setSelected(next);
    try {
      localStorage.setItem(storageKey, JSON.stringify(next));
    } catch {
      /* ignore */
    }
  };
  const toggle = (href: string) =>
    persist(selected.includes(href) ? selected.filter((h) => h !== href) : [...selected, href]);

  const shown = modules.filter((m) => selected.includes(m.href));

  return (
    <div className="card self-start lg:col-span-2" data-reveal>
      <div className="mb-4 flex items-center justify-between">
        <div>
          <h2>Schnellzugriff</h2>
          {editing ? (
            <p className="text-muted mt-0.5 text-xs">
              {selected.length} von {modules.length} Modulen aktiv
            </p>
          ) : null}
        </div>
        <button className="pill" data-active={editing} onClick={() => setEditing((v) => !v)}>
          <Icon name={editing ? "check" : "settings"} size={15} />
          {editing ? "Fertig" : "Anpassen"}
        </button>
      </div>

      {!ready ? (
        <div className="text-muted text-sm">Lädt …</div>
      ) : editing ? (
        <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
          {modules.map((m) => {
            const active = selected.includes(m.href);
            return (
              <button
                key={m.href}
                onClick={() => toggle(m.href)}
                className="flex items-center gap-3 rounded-2xl border px-3 py-2.5 text-left transition-all"
                style={{
                  borderColor: active ? "rgba(190,203,255,.34)" : "var(--line)",
                  background: active
                    ? "linear-gradient(135deg, rgba(158,215,255,.14), rgba(255,159,215,.09))"
                    : "rgba(13,19,42,.4)",
                }}
              >
                <span
                  className="grid h-9 w-9 shrink-0 place-items-center rounded-xl"
                  style={{
                    background: active ? accentOf(m.href) : "rgba(13,19,42,.6)",
                    color: active ? "#0a0e22" : "var(--muted)",
                    border: active ? "none" : "1px solid var(--line)",
                    boxShadow: active ? `0 6px 18px ${accentOf(m.href)}44` : "none",
                  }}
                >
                  <Icon name={m.icon} size={17} />
                </span>
                <span className="min-w-0 flex-1">
                  <span className="block font-bold">{m.label}</span>
                  <span className="block truncate text-xs text-muted">{DESC[m.href] ?? ""}</span>
                </span>
                <span
                  className="grid h-5 w-5 place-items-center rounded-full"
                  style={{
                    background: active ? "var(--grad-brand)" : "transparent",
                    border: active ? "none" : "1px solid var(--line-strong)",
                    color: "#0a0e22",
                  }}
                >
                  {active ? <Icon name="check" size={13} /> : null}
                </span>
              </button>
            );
          })}
        </div>
      ) : shown.length === 0 ? (
        <p className="text-muted text-sm">
          Kein Schnellzugriff ausgewählt. Klicke auf „Anpassen“, um Module hinzuzufügen.
        </p>
      ) : (
        <div className="qa-grid" data-count={shown.length}>
          {shown.map((m) => {
            const accent = accentOf(m.href);
            return (
              <a key={m.href} href={m.href} className="qa-tile" style={{ ["--accent" as string]: accent }}>
                <span className="qa-icon">
                  <Icon name={m.icon} size={22} />
                </span>
                <span className="min-w-0 flex-1">
                  <span className="block truncate font-bold">{m.label}</span>
                  <span className="block truncate text-xs text-muted">{DESC[m.href] ?? "Öffnen"}</span>
                </span>
                <span className="qa-go">
                  <Icon name="chevron" size={16} />
                </span>
              </a>
            );
          })}
        </div>
      )}
    </div>
  );
}
