"use client";

import { useMemo, useState } from "react";
import { AdminEmptyState } from "@/components/admin/AdminEmptyState";
import { IntranetArticleRow } from "@/components/admin/IntranetArticleRow";

type Article = {
  id: string;
  title: string;
  content: string;
  category: string;
  visible: boolean;
  pinned: boolean;
  lastEditedByName: string;
  updatedAt: string;
  departmentIds: string[];
};
type Department = { id: string; name: string; color: string };

export function IntranetBrowser({
  items,
  departments,
  canEdit,
  canDelete,
  highlightId,
}: {
  items: Article[];
  departments: Department[];
  canEdit: boolean;
  canDelete: boolean;
  highlightId: string | null;
}) {
  const [query, setQuery] = useState("");

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return items;
    return items.filter(
      (i) => i.title.toLowerCase().includes(q) || i.content.toLowerCase().includes(q) || i.category.toLowerCase().includes(q)
    );
  }, [items, query]);

  const pinned = filtered.filter((i) => i.pinned);
  const rest = filtered.filter((i) => !i.pinned);

  const groups: { name: string; items: Article[] }[] = [];
  for (const item of rest) {
    let group = groups.find((g) => g.name === item.category);
    if (!group) {
      group = { name: item.category || "Ohne Kategorie", items: [] };
      groups.push(group);
    }
    group.items.push(item);
  }

  return (
    <>
      {items.length > 0 && (
        <input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Im Intranet suchen…"
          className="w-full bg-transparent border border-white/15 rounded-lg px-3.5 py-2.5 text-sm mb-6 focus:outline-none focus:border-white/50"
        />
      )}

      {filtered.length === 0 ? (
        <AdminEmptyState
          message={items.length === 0 ? "Noch keine internen Abläufe hinterlegt." : "Keine Treffer für diese Suche."}
        />
      ) : (
        <div className="flex flex-col gap-8">
          {pinned.length > 0 && (
            <div>
              <div className="flex items-center gap-2 mb-3">
                <h2 className="text-xs uppercase tracking-[0.15em] text-[var(--rk-ink-muted)]">📌 Angepinnt</h2>
                <div className="h-px flex-1 bg-white/10" />
              </div>
              <div className="flex flex-col gap-3">
                {pinned.map((item) => (
                  <IntranetArticleRow
                    key={item.id}
                    item={item}
                    departments={departments}
                    canEdit={canEdit}
                    canDelete={canDelete}
                    highlighted={item.id === highlightId}
                  />
                ))}
              </div>
            </div>
          )}
          {groups.map((group) => (
            <div key={group.name}>
              <div className="flex items-center gap-2 mb-3">
                <h2 className="text-xs uppercase tracking-[0.15em] text-[var(--rk-ink-muted)]">{group.name}</h2>
                <span className="text-[0.65rem] text-[var(--rk-ink-muted)]/70">({group.items.length})</span>
                <div className="h-px flex-1 bg-white/10" />
              </div>
              <div className="flex flex-col gap-3">
                {group.items.map((item) => (
                  <IntranetArticleRow
                    key={item.id}
                    item={item}
                    departments={departments}
                    canEdit={canEdit}
                    canDelete={canDelete}
                    highlighted={item.id === highlightId}
                  />
                ))}
              </div>
            </div>
          ))}
        </div>
      )}
    </>
  );
}
