"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { MAIN_NAV, SETTINGS_NAV, getActiveNavHref } from "@/config/site";
import type { NavItem } from "@/config/site";
import { useAuth } from "@/hooks";
import { usePermissions } from "@/hooks/usePermissions";
import { isEmployeeRole } from "@/lib/permissions";
import type { UserRole } from "@/types/auth-user";
import { cn } from "@/lib/utils";

interface SidebarProps {
  onNavigate?: () => void;
  collapsed?: boolean;
}

function filterNav(
  items: NavItem[],
  can: (permission: string) => boolean,
  userRole?: UserRole
): NavItem[] {
  return items.filter((item) => {
    if (item.roles?.length) {
      return userRole ? item.roles.includes(userRole) : false;
    }
    if (item.permission && !can(item.permission)) return false;
    return true;
  });
}

function NavSection({
  items,
  pathname,
  collapsed,
  employeeView,
  onNavigate,
  sectionLabel,
}: {
  items: typeof MAIN_NAV;
  pathname: string;
  collapsed: boolean;
  employeeView: boolean;
  onNavigate?: () => void;
  sectionLabel: string;
}) {
  if (items.length === 0) return null;

  const activeHref = getActiveNavHref(pathname, items.map((item) => item.href));

  return (
    <div>
      {!collapsed ? (
        <p className="mb-2 px-3 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
          {sectionLabel}
        </p>
      ) : null}
      <ul className="space-y-1">
        {items.map((item) => {
          const active = item.href === activeHref;
          const Icon = item.icon;
          return (
            <li key={item.href}>
              <Link
                href={item.href}
                onClick={onNavigate}
                title={collapsed ? item.title : undefined}
                className={cn(
                  "flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors",
                  active
                    ? "bg-sidebar-active text-sidebar-active-foreground"
                    : "text-sidebar-foreground hover:bg-muted hover:text-foreground",
                  collapsed && "justify-center px-2"
                )}
              >
                <Icon className={cn("h-[18px] w-[18px] shrink-0", active && "text-brand")} />
                {!collapsed ? (
                  <span>{employeeView && item.employeeTitle ? item.employeeTitle : item.title}</span>
                ) : null}
              </Link>
            </li>
          );
        })}
      </ul>
    </div>
  );
}

export function Sidebar({ onNavigate, collapsed = false }: SidebarProps) {
  const pathname = usePathname();
  const { user } = useAuth();
  const { can } = usePermissions();
  const employeeView = isEmployeeRole(user);

  const moduleNav = filterNav(MAIN_NAV, can, user?.role);
  const settingsNav = filterNav(SETTINGS_NAV, can, user?.role);

  return (
    <aside
      className={cn(
        "flex h-full flex-col border-r border-border bg-sidebar",
        collapsed ? "w-[72px]" : "w-[260px]"
      )}
    >
      <div className={cn("flex h-16 items-center border-b border-border", collapsed ? "justify-center px-2" : "px-5")}>
        <Link href="/" className="flex items-center gap-3" onClick={onNavigate}>
          <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand text-sm font-bold text-brand-foreground">
            N
          </div>
          {!collapsed ? (
            <div>
              <p className="text-sm font-semibold text-foreground">NOOR HR</p>
              <p className="text-[11px] text-muted-foreground">People</p>
            </div>
          ) : null}
        </Link>
      </div>

      <nav className="flex-1 space-y-6 overflow-y-auto px-3 py-4">
        <NavSection
          items={moduleNav}
          pathname={pathname}
          collapsed={collapsed}
          employeeView={employeeView}
          onNavigate={onNavigate}
          sectionLabel="Main"
        />

        <NavSection
          items={settingsNav}
          pathname={pathname}
          collapsed={collapsed}
          employeeView={employeeView}
          onNavigate={onNavigate}
          sectionLabel="Settings"
        />
      </nav>

      {!collapsed ? (
        <div className="border-t border-border p-4">
          <p className="text-xs text-muted-foreground">NOOR HR v0.1</p>
          <p className="text-[11px] text-muted-foreground">Oman &amp; GCC</p>
        </div>
      ) : null}
    </aside>
  );
}
