import { NavLink } from "react-router-dom";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  LayoutDashboard,
  FlaskConical,
  BookOpen,
  BarChart3,
  Settings,
  Users,
  FileText,
  ChevronDown,
  ListChecks,
  CheckCircle,
  Database,
  Crosshair,
  Zap,
  Grid3X3,
  List,
  Gauge,
  ShieldCheck,
  GitCompareArrows,
  ScrollText,
  ClipboardCheck,
} from "lucide-react";
import { useAuth } from "../context/AuthContext";
import { getTechniques } from "../api/techniques";

interface NavItem {
  to: string;
  label: string;
  icon: React.FC<{ className?: string }>;
  /** Roles allowed to see this item. undefined = everyone. */
  roles?: string[];
  children?: NavItem[];
}

const mainLinks: NavItem[] = [
  { to: "/dashboard", label: "Dashboard", icon: LayoutDashboard },
  { to: "/executive-dashboard", label: "Executive Dashboard", icon: Gauge, roles: ["admin", "red_lead", "blue_lead", "viewer"] },
  {
    to: "/matrix",
    label: "ATT&CK",
    icon: Grid3X3,
    children: [
      { to: "/techniques", label: "Techniques", icon: List },
      { to: "/matrix",     label: "Coverage Matrix", icon: Grid3X3 },
      { to: "/techniques/review-queue", label: "Review Queue", icon: ClipboardCheck, roles: ["admin", "red_lead", "blue_lead"] },
    ],
  },
  {
    to: "/tests",
    label: "Tests",
    icon: FlaskConical,
    children: [
      { to: "/tests", label: "All Tests", icon: ListChecks },
      { to: "/tests/validated", label: "Validated Tests", icon: CheckCircle },
      { to: "/test-catalog", label: "Test Catalog", icon: BookOpen },
    ],
  },
  { to: "/campaigns", label: "Campaigns", icon: Zap },
  { to: "/threat-actors", label: "Threat Actors", icon: Crosshair },
  { to: "/compliance", label: "Compliance", icon: ShieldCheck },
  { to: "/comparison", label: "Comparison", icon: GitCompareArrows, roles: ["admin", "red_lead", "blue_lead", "viewer"] },
  { to: "/reports", label: "Reports", icon: BarChart3 },
  { to: "/settings", label: "Settings", icon: Settings },
];

const systemLinks: NavItem[] = [
  { to: "/data-sources", label: "Data Sources", icon: Database },
  { to: "/system", label: "MITRE Sync", icon: ScrollText },
  { to: "/users", label: "Users", icon: Users },
  { to: "/audit", label: "Audit Log", icon: FileText },
];

function SidebarLink({ item, badge }: { item: NavItem; badge?: number }) {
  const [expanded, setExpanded] = useState(false);
  const { user } = useAuth();
  const role = user?.role ?? "";
  const isAdmin = role === "admin";

  const childCanSee = (child: NavItem) => {
    if (!child.roles) return true;
    if (isAdmin) return true;
    return child.roles.includes(role);
  };

  if (item.children) {
    const visibleChildren = item.children.filter(childCanSee);
    return (
      <div>
        <button
          onClick={() => setExpanded(!expanded)}
          className="flex w-full items-center justify-between rounded-lg px-3 py-2.5 text-sm font-medium text-gray-400 transition-colors hover:bg-gray-800 hover:text-gray-200"
        >
          <span className="flex items-center gap-3">
            <item.icon className="h-5 w-5" />
            {item.label}
          </span>
          <span className="flex items-center gap-1.5">
            {badge !== undefined && badge > 0 && (
              <span className="rounded-full bg-amber-500 px-1.5 py-0.5 text-[10px] font-bold text-white leading-none">
                {badge}
              </span>
            )}
            <ChevronDown className={`h-4 w-4 transition-transform ${expanded ? "rotate-180" : ""}`} />
          </span>
        </button>
        {expanded && (
          <div className="ml-4 mt-1 space-y-0.5 border-l border-gray-800 pl-3">
            {visibleChildren.map((child) => (
              <NavLink
                key={child.to + child.label}
                to={child.to}
                end
                className={({ isActive }) =>
                  `flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors ${
                    isActive
                      ? "bg-cyan-500/10 text-cyan-400"
                      : "text-gray-500 hover:bg-gray-800 hover:text-gray-200"
                  }`
                }
              >
                <child.icon className="h-4 w-4" />
                {child.label}
              </NavLink>
            ))}
          </div>
        )}
      </div>
    );
  }

  return (
    <NavLink
      to={item.to}
      end
      className={({ isActive }) =>
        `flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors ${
          isActive
            ? "bg-cyan-500/10 text-cyan-400"
            : "text-gray-400 hover:bg-gray-800 hover:text-gray-200"
        }`
      }
    >
      <item.icon className="h-5 w-5 shrink-0" />
      <span className="flex-1">{item.label}</span>
      {badge !== undefined && badge > 0 && (
        <span className="rounded-full bg-amber-500 px-1.5 py-0.5 text-[10px] font-bold text-white leading-none">
          {badge}
        </span>
      )}
    </NavLink>
  );
}

export default function Sidebar() {
  const { user } = useAuth();
  const role = user?.role ?? "";
  const isAdmin = role === "admin";

  const canSeeReviewQueue =
    isAdmin || role === "red_lead" || role === "blue_lead";

  // Fetch review queue count for the badge (only for roles that can see it)
  const { data: reviewQueue } = useQuery({
    queryKey: ["techniques", "review-queue"],
    queryFn: () => getTechniques({ review_required: true }),
    enabled: canSeeReviewQueue,
    staleTime: 5 * 60 * 1000, // 5 min — don't hammer the API
  });
  const reviewCount = reviewQueue?.length ?? 0;

  /** Returns true when the current user is allowed to see `item`. */
  const canSee = (item: NavItem) => {
    if (!item.roles) return true;
    if (isAdmin) return true;
    return item.roles.includes(role);
  };

  return (
    <aside className="flex h-screen w-60 flex-col border-r border-gray-800 bg-gray-900">
      {/* Logo */}
      <div className="flex h-16 items-center gap-3 px-5">
        <img src="/aegis-logo.svg" alt="Aegis" className="h-8 w-8" />
        <span className="text-lg font-bold tracking-wide text-white">
          Aegis
        </span>
      </div>

      {/* Main nav */}
      <nav className="flex-1 space-y-1 overflow-y-auto px-3 py-4">
        {mainLinks.filter(canSee).map((item) => (
          <SidebarLink
            key={item.to + item.label}
            item={item}
            badge={item.label === "ATT&CK" ? reviewCount : undefined}
          />
        ))}

        {/* System / Administration section — admin only */}
        {isAdmin && (
          <>
            <div className="my-3 border-t border-gray-800" />
            <p className="mb-2 px-3 text-[10px] font-semibold uppercase tracking-widest text-gray-600">
              System
            </p>
            {systemLinks.map((item) => (
              <SidebarLink key={item.to} item={item} />
            ))}
          </>
        )}
      </nav>

      {/* Footer */}
      <div className="border-t border-gray-800 px-5 py-4">
        <p className="truncate text-xs text-gray-500">
          {user?.username ?? "—"} · {role || "—"}
        </p>
      </div>
    </aside>
  );
}
