"use client";

import { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { ChevronDown } from "lucide-react";
import { NAV, type NavItem } from "@/lib/nav";
import { Logo } from "@/components/brand/logo";
import { cn } from "@/lib/utils";

/**
 * Shared nav body used by both the static desktop sidebar column and the
 * mobile slide-in drawer. `onNavigate` lets the drawer close itself when a
 * link is tapped. There is exactly one nav definition.
 */
export function SidebarNav({
  allowed,
  onNavigate,
}: {
  allowed: string[];
  onNavigate?: () => void;
}) {
  const permSet = new Set(allowed);
  const can = (perm?: [string, string]) =>
    !perm || permSet.has("*") || permSet.has(`${perm[0]}.${perm[1]}`);

  const items = NAV.filter((i) => can(i.perm));

  return (
    <>
      <div className="flex h-16 items-center border-b border-sidebar-border px-6">
        <Link href="/dashboard" onClick={onNavigate}>
          <Logo variant="light" />
        </Link>
      </div>
      <nav className="flex-1 space-y-1 overflow-y-auto p-3">
        {items.map((item) => (
          <NavRow
            key={item.href}
            item={item}
            can={can}
            onNavigate={onNavigate}
          />
        ))}
      </nav>
    </>
  );
}

export function Sidebar({ allowed }: { allowed: string[] }) {
  return (
    <aside className="hidden h-full w-64 shrink-0 flex-col bg-sidebar text-sidebar-foreground lg:flex">
      <SidebarNav allowed={allowed} />
    </aside>
  );
}

function NavRow({
  item,
  can,
  onNavigate,
}: {
  item: NavItem;
  can: (perm?: [string, string]) => boolean;
  onNavigate?: () => void;
}) {
  const pathname = usePathname();
  const active = pathname === item.href || pathname.startsWith(item.href + "/");
  const children = item.children?.filter((c) => can(c.perm)) ?? [];
  const [open, setOpen] = useState(active);
  const Icon = item.icon;

  if (children.length === 0) {
    return (
      <Link
        href={item.href}
        onClick={onNavigate}
        className={cn(
          "flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors",
          active
            ? "bg-sidebar-primary text-sidebar-primary-foreground"
            : "text-sidebar-foreground/80 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
        )}
      >
        <Icon className="size-4 shrink-0" />
        {item.label}
      </Link>
    );
  }

  return (
    <div>
      <button
        onClick={() => setOpen((v) => !v)}
        className={cn(
          "flex w-full items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors",
          active
            ? "bg-sidebar-primary text-sidebar-primary-foreground"
            : "text-sidebar-foreground/80 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
        )}
      >
        <Icon className="size-4 shrink-0" />
        <span className="flex-1 text-left">{item.label}</span>
        <ChevronDown
          className={cn("size-4 transition-transform", open && "rotate-180")}
        />
      </button>
      {open && (
        <div className="mt-1 space-y-1 pl-10">
          {children.map((c) => {
            const childActive = pathname === c.href;
            return (
              <Link
                key={c.href}
                href={c.href}
                onClick={onNavigate}
                className={cn(
                  "block rounded-md px-3 py-1.5 text-sm transition-colors",
                  childActive
                    ? "text-sidebar-primary-foreground"
                    : "text-sidebar-foreground/70 hover:text-sidebar-foreground",
                )}
              >
                {c.label}
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
}
