"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useMemo, useRef, useState } from "react";

import {
  SidebarActiveLink,
  SidebarTaxonomiesAccordion,
} from "@/components/admin/layout/SidebarActiveLink";
import { SidebarGroup } from "@/components/admin/layout/SidebarGroup";
import { LiveChatNavBadge } from "@/components/admin/layout/LiveChatNavBadge";
import {
  ADMIN_NAV_GROUPS,
  SIFRARNICI_LINKS,
  TAXONOMY_GROUP_LABEL,
} from "@/components/admin/layout/admin-nav";
import { hasAdminPermission, type AdminPermission } from "@/lib/admin-rbac";
import type { SessionUser } from "@/lib/session";

const OPEN_EVENT = "admin:open-sidebar";

/**
 * Mobilni drawer — puni-visine slide-in. Koristi ISTI izvor navigacije
 * (`ADMIN_NAV_GROUPS`) i iste grupe/ikone kao desktop sidebar pa nema
 * raskoraka. Auto-zatvara se kad se ruta promeni.
 */
export function AdminMobileSidebar({ user }: { user: SessionUser }) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  const pathname = usePathname();
  const lastPath = useRef(pathname);

  const canTaxonomies = hasAdminPermission(user, "taxonomy:manage");

  const visibleGroups = useMemo(
    () =>
      ADMIN_NAV_GROUPS.map((group) => ({
        ...group,
        links: group.links.filter((link) =>
          hasAdminPermission(user, link.permission as AdminPermission),
        ),
      })).filter((group) => group.links.length > 0),
    [user],
  );

  // Filter po search query — case-insensitive substring match na link label
  // ili group label. Ako se query unese, prikazuje SAMO matching links iz svih
  // grupa (flat result list), inače grupe ostaju u svom layout-u.
  const filteredGroups = useMemo(() => {
    const q = query.trim().toLocaleLowerCase("sr");
    if (!q) return visibleGroups;
    return visibleGroups
      .map((g) => ({
        ...g,
        links: g.links.filter(
          (l) =>
            l.label.toLocaleLowerCase("sr").includes(q) ||
            g.label.toLocaleLowerCase("sr").includes(q),
        ),
      }))
      .filter((g) => g.links.length > 0);
  }, [query, visibleGroups]);

  useEffect(() => {
    const handler = () => setOpen(true);
    window.addEventListener(OPEN_EVENT, handler);
    return () => window.removeEventListener(OPEN_EVENT, handler);
  }, []);

  // Zatvori drawer kada se ruta zaista promeni (klik na link), ne na mount.
  useEffect(() => {
    if (lastPath.current !== pathname) {
      lastPath.current = pathname;
      const timeoutId = window.setTimeout(() => {
        setOpen(false);
        setQuery("");
      }, 0);
      return () => window.clearTimeout(timeoutId);
    }
  }, [pathname]);

  useEffect(() => {
    if (typeof document === "undefined") return;
    document.body.style.overflow = open ? "hidden" : "";
    return () => {
      document.body.style.overflow = "";
    };
  }, [open]);

  function closeSidebar() {
    setOpen(false);
    setQuery("");
  }

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-[100] lg:hidden" role="dialog" aria-modal="true">
      <button
        type="button"
        aria-label="Zatvori navigaciju"
        onClick={closeSidebar}
        className="absolute inset-0 bg-[rgba(12,24,40,0.55)] backdrop-blur-sm"
      />

      <aside className="absolute left-0 top-0 flex h-full w-[90%] max-w-[348px] flex-col bg-[linear-gradient(180deg,#ffffff,#faf6f2)] shadow-[0_0_70px_rgba(12,24,40,0.32)]">
        <div className="admin-sidebar-brand flex items-center justify-between">
          <Link
            href="/admin"
            className="admin-sidebar-mark"
            aria-label="BiznisPortal admin"
            onClick={closeSidebar}
          >
            <span className="admin-sidebar-mark-glyph">
              <Image src="/icons/app-icon.png" alt="" width={42} height={42} />
            </span>
            <span className="admin-sidebar-mark-text">
              <span className="admin-sidebar-mark-name">BiznisPortal</span>
              <span className="admin-sidebar-mark-sub">Kontrolni centar</span>
            </span>
          </Link>
          <button
            type="button"
            aria-label="Zatvori"
            onClick={closeSidebar}
            className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-border text-muted-foreground transition hover:bg-black/5"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <line x1="18" y1="6" x2="6" y2="18" />
              <line x1="6" y1="6" x2="18" y2="18" />
            </svg>
          </button>
        </div>

        {/* Search input — sticky pri vrhu drawer-a. Brzo filtruje sve linkove
            po imenu (npr. „komp" → Kompanije / Komercijala). Eskejp brza ostala
            slova → drawer ostaje kao da nema filtera. */}
        <div className="px-4 pt-3 pb-2">
          <div className="relative">
            <span className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <circle cx="11" cy="11" r="8" />
                <path d="m21 21-4.3-4.3" />
              </svg>
            </span>
            <input
              type="search"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Pretraži stranice..."
              autoComplete="off"
              spellCheck={false}
              className="h-10 w-full rounded-xl border border-border bg-white pl-9 pr-3 text-sm text-foreground placeholder:text-muted-foreground outline-none focus:border-primary/40 focus:ring-2 focus:ring-primary/15"
            />
          </div>
        </div>

        <div className="admin-sidebar-scroll">
          {filteredGroups.length === 0 ? (
            <div className="px-4 py-8 text-center text-sm text-muted-foreground">
              Nema rezultata za <strong className="text-foreground">„{query}"</strong>.
            </div>
          ) : (
            filteredGroups.map((group) => (
              <SidebarGroup
                key={group.label}
                label={group.label}
                icon={group.icon}
                hrefs={group.links.map((link) => link.href)}
              >
                {group.links.map((link) => (
                  <SidebarActiveLink key={link.href} href={link.href}>
                    <span className="admin-sidebar-link-dot" aria-hidden="true" />
                    <span className="min-w-0 truncate">{link.label}</span>
                    {link.href === "/admin/live-chat" ? <LiveChatNavBadge /> : null}
                  </SidebarActiveLink>
                ))}

                {/* Taxonomies sub-accordion samo kad nema search filtera
                    (filter ne razume njihovu strukturu, neka korisnik koristi
                    Cmd+K paletu za duboku pretragu) */}
                {!query && group.label === TAXONOMY_GROUP_LABEL && canTaxonomies ? (
                  <SidebarTaxonomiesAccordion items={SIFRARNICI_LINKS} />
                ) : null}
              </SidebarGroup>
            ))
          )}
        </div>
      </aside>
    </div>
  );
}
