"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  BedDouble,
  Bell,
  BookOpenText,
  Building2,
  ClipboardCheck,
  Globe2,
  HeartPulse,
  LayoutDashboard,
  ListChecks,
  LockKeyhole,
  Radio,
  ReceiptText,
  Settings,
  ShieldAlert,
  TabletSmartphone,
  UserRoundCheck,
  Users,
  Wrench,
} from "lucide-react";
import type { LucideIcon } from "lucide-react";

import type { Permission } from "@/modules/core/types";
import { navGroups, type NavIconKey, type NavItem } from "@/modules/shared/lib/navigation";
import { getWorkspaceHref, isWorkspacePathActive } from "@/modules/shared/lib/workspace-routing";
import { cn } from "@/lib/utils";

const iconMap: Record<NavIconKey, LucideIcon> = {
  alerts: Radio,
  audit: ListChecks,
  beds: BedDouble,
  billing: ReceiptText,
  care: ClipboardCheck,
  dashboard: LayoutDashboard,
  devices: TabletSmartphone,
  emergency: ShieldAlert,
  family: UserRoundCheck,
  global: Globe2,
  health: HeartPulse,
  knowledge: BookOpenText,
  notices: Bell,
  organizations: Building2,
  roles: Settings,
  status: Wrench,
  users: Users,
};

type AppSidebarNavProps = {
  organizationSlug?: string;
  permissions: Permission[];
};

type SidebarNavItem = NavItem & {
  canAccess: boolean;
};

function canViewNavItem(item: NavItem, permissions: readonly Permission[]): boolean {
  if (permissions.includes("platform:manage")) {
    return true;
  }

  if (item.permission && !permissions.includes(item.permission)) {
    return false;
  }

  if (item.anyPermissions && !item.anyPermissions.some((permission) => permissions.includes(permission))) {
    return false;
  }

  return true;
}

export function AppSidebarNav({ organizationSlug, permissions }: AppSidebarNavProps): React.ReactElement {
  const pathname = usePathname();
  const visibleNavGroups = navGroups.map((group): { label: string; items: SidebarNavItem[] } => ({
    ...group,
    items: group.items.map((item) => ({
      ...item,
      canAccess: canViewNavItem(item, permissions),
    })),
  }));

  return (
    <nav className="min-h-0 flex-1 overflow-y-auto px-3 py-4" aria-label="主导航">
      <div className="space-y-5">
        {visibleNavGroups.map((group) => (
          <section key={group.label}>
            <p className="px-3 pb-2 text-xs font-semibold text-muted-foreground">{group.label}</p>
            <ul className="space-y-1">
              {group.items.map((item) => {
                const Icon = iconMap[item.icon];
                const href = getWorkspaceHref(organizationSlug, item.path);
                const isActive = item.canAccess && isWorkspacePathActive(pathname, item.path);

                return (
                  <li key={item.path}>
                    {item.canAccess ? (
                      <Link
                        href={href}
                        aria-current={isActive ? "page" : undefined}
                        className={cn(
                          "group flex min-h-11 items-center gap-3 rounded-md px-3 text-sm transition-colors",
                          isActive
                            ? "bg-primary text-primary-foreground shadow-sm"
                            : "text-foreground hover:bg-secondary hover:text-primary",
                        )}
                      >
                        <Icon
                          className={cn(
                            "size-4 shrink-0 transition-colors",
                            isActive ? "text-primary-foreground" : "text-muted-foreground group-hover:text-primary",
                          )}
                          aria-hidden="true"
                        />
                        <span className="min-w-0 truncate font-medium">{item.label}</span>
                      </Link>
                    ) : (
                      <span
                        className="flex min-h-11 cursor-not-allowed items-center gap-3 rounded-md px-3 text-sm text-muted-foreground/70"
                        aria-disabled="true"
                        title="当前角色无权访问"
                      >
                        <Icon className="size-4 shrink-0 text-muted-foreground/60" aria-hidden="true" />
                        <span className="min-w-0 flex-1 truncate font-medium">{item.label}</span>
                        <LockKeyhole className="size-3.5 shrink-0 text-muted-foreground/55" aria-hidden="true" />
                        <span className="sr-only">当前角色无权访问</span>
                      </span>
                    )}
                  </li>
                );
              })}
            </ul>
          </section>
        ))}
      </div>
    </nav>
  );
}
