"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useSession } from "next-auth/react";
import { cn } from "@/lib/utils";
import { getAppNavItems } from "@/components/layout/nav-items";
import { getDepartmentHomeRoute } from "@/lib/access-control";
import type { DepartmentKey, UserRole } from "@/lib/types";

export default function Sidebar() {
  const pathname = usePathname();
  const { data: session } = useSession();
  const role = session?.user?.role as UserRole | undefined;
  const department = (session?.user?.department as DepartmentKey | null | undefined) ?? null;
  const appNavItems = getAppNavItems(role, department);
  const homeHref = role === "owner" ? "/dashboard" : getDepartmentHomeRoute(department);

  if (pathname.startsWith("/dashboard/print")) {
    return null;
  }

  return (
    <aside className="hidden w-[270px] shrink-0 border-r border-benell-stroke bg-benell-sidebar md:flex md:flex-col">
      <div className="border-b border-benell-stroke px-5 py-6">
        <Link
          href={homeHref}
          className="inline-flex rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-benell-brown focus-visible:ring-offset-2"
        >
          <Image
            src="/brand/logo.webp"
            alt="Casa Benell"
            width={92}
            height={54}
            className="h-14 w-auto rounded-lg border border-benell-stroke object-contain object-left"
            priority
          />
        </Link>
      </div>

      <nav className="flex-1 px-4 py-5" aria-label="Navegación principal">
        <ul className="space-y-1.5">
          {appNavItems.map((item) => {
            const baseHref = item.href.split("?")[0];
            const isActive = pathname === baseHref || pathname.startsWith(`${baseHref}/`);
            const Icon = item.icon;

            return (
              <li key={item.href}>
                <Link
                  href={item.href}
                  className={cn(
                    "group flex items-center gap-3 rounded-pill px-4 py-2.5 text-base font-medium outline-none transition",
                    "focus-visible:ring-2 focus-visible:ring-benell-brown focus-visible:ring-offset-2",
                    isActive ? "bg-benell-brown text-white" : "text-benell-text hover:bg-benell-surface-muted"
                  )}
                >
                  <Icon className="size-5" aria-hidden />
                  <span>{item.label}</span>
                </Link>
              </li>
            );
          })}
        </ul>
      </nav>
    </aside>
  );
}
