"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { ComponentType, SVGProps, SyntheticEvent, useState } from "react";
import { DashboardIcon, MonitoringIcon, RulesIcon, SettingsIcon, TargetIcon } from "./icons";
import { useRoles } from "./RolesProvider";
import { canAccess } from "@/lib/roles";

type NavItem = {
  href: string;
  label: string;
  icon: ComponentType<SVGProps<SVGSVGElement>>;
  exact?: boolean;
};

// Primary navigation. The merged pages each carry their own in-page tabs:
//   Monitoring → Product Queue / Processed / Log
//   Enrichment Rules → Manipulation Rules / Per-Category Rules / Trusted Sources
//   Admin Settings → Credentials / Runtime / Services / Cost & Quality / Actions / Audit Log
// Services (pipeline services + runners) and the kill-switch now live under Admin
// Settings and the header respectively. The User Guide lives in the header (book icon).
export const NAV_ITEMS: NavItem[] = [
  { href: "/", label: "Dashboard", icon: DashboardIcon, exact: true },
  { href: "/monitoring", label: "Monitoring", icon: MonitoringIcon },
  { href: "/targeted", label: "Targeted Enrichment", icon: TargetIcon },
  { href: "/enrichment", label: "Enrichment Rules", icon: RulesIcon },
  { href: "/admin-settings", label: "Admin Settings", icon: SettingsIcon },
];

export default function Nav({ collapsed = false }: { collapsed?: boolean }) {
  const pathname = usePathname();
  const roles = useRoles();
  const items = NAV_ITEMS.filter((item) => canAccess(item.href, roles));

  // When collapsed (icons only), show a styled label tooltip on hover/focus.
  // Rendered position:fixed so it isn't clipped by the sidebar's overflow.
  const [tip, setTip] = useState<{ label: string; x: number; y: number } | null>(null);
  const showTip = (label: string) => (e: SyntheticEvent<HTMLAnchorElement>) => {
    if (!collapsed) return;
    const r = e.currentTarget.getBoundingClientRect();
    setTip({ label, x: r.right, y: r.top + r.height / 2 });
  };
  const hideTip = () => setTip(null);

  return (
    <nav aria-label="Primary" className="space-y-1 p-2">
      {items.map((item) => {
        const active = item.exact ? pathname === item.href : pathname.startsWith(item.href);
        const Icon = item.icon;
        return (
          <Link
            key={item.href}
            href={item.href}
            aria-current={active ? "page" : undefined}
            onMouseEnter={showTip(item.label)}
            onMouseLeave={hideTip}
            onFocus={showTip(item.label)}
            onBlur={hideTip}
            className={`flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium ${
              collapsed ? "justify-center" : ""
            } ${active ? "bg-brand text-white" : "text-slate-700 hover:bg-slate-100"}`}
          >
            <Icon className="h-5 w-5 shrink-0" />
            {!collapsed && <span className="truncate">{item.label}</span>}
          </Link>
        );
      })}

      {tip && (
        <div
          role="tooltip"
          style={{ position: "fixed", left: tip.x + 8, top: tip.y }}
          className="pointer-events-none z-60 -translate-y-1/2 whitespace-nowrap rounded-md bg-slate-900 px-2.5 py-1.5 text-xs font-medium text-white shadow-lg ring-1 ring-black/5"
        >
          {tip.label}
        </div>
      )}
    </nav>
  );
}
