"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useSession } from "next-auth/react";
import { Menu, X } from "lucide-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 MobileNav() {
  const pathname = usePathname();
  const { data: session } = useSession();
  const [isOpen, setIsOpen] = useState(false);
  const closeButtonRef = useRef<HTMLButtonElement>(null);
  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);

  useEffect(() => {
    setIsOpen(false);
  }, [pathname]);

  useEffect(() => {
    if (!isOpen) {
      return;
    }

    closeButtonRef.current?.focus();

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setIsOpen(false);
      }
    };

    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", handleKeyDown);

    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [isOpen]);

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

  return (
    <div className="border-b border-benell-stroke bg-benell-surface px-4 py-2 md:hidden">
      <button
        type="button"
        onClick={() => setIsOpen(true)}
        className="inline-flex items-center gap-2 rounded-pill border border-benell-stroke bg-white px-3 py-1.5 text-sm font-semibold outline-none focus-visible:ring-2 focus-visible:ring-benell-brown"
        aria-label="Abrir menú principal"
        aria-expanded={isOpen}
        aria-controls="mobile-drawer"
      >
        <Menu className="size-4" aria-hidden />
        Menú
      </button>

      {isOpen ? (
        <div className="fixed inset-0 z-40" role="presentation">
          <button
            type="button"
            className="absolute inset-0 bg-black/30"
            onClick={() => setIsOpen(false)}
            aria-label="Cerrar menú"
          />
          <aside
            id="mobile-drawer"
            role="dialog"
            aria-modal="true"
            aria-label="Navegación principal"
            className="absolute inset-y-0 left-0 flex w-[84vw] max-w-[320px] flex-col border-r border-benell-stroke bg-benell-sidebar shadow-xl"
          >
            <div className="flex items-center justify-between border-b border-benell-stroke px-4 py-4">
              <Link href={homeHref} className="inline-flex rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-benell-brown">
                <Image
                  src="/brand/logo.webp"
                  alt="Casa Benell"
                  width={84}
                  height={52}
                  className="h-12 w-auto rounded-md border border-benell-stroke object-contain object-left"
                  priority
                />
              </Link>
              <button
                ref={closeButtonRef}
                type="button"
                onClick={() => setIsOpen(false)}
                className="inline-flex items-center justify-center rounded-full p-2 outline-none focus-visible:ring-2 focus-visible:ring-benell-brown"
                aria-label="Cerrar menú"
              >
                <X className="size-5" aria-hidden />
              </button>
            </div>

            <nav className="min-h-0 flex-1 overflow-y-auto px-3 py-4">
              <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(
                          "flex items-center gap-3 rounded-xl px-3 py-2.5 text-base font-medium outline-none transition",
                          "focus-visible:ring-2 focus-visible:ring-benell-brown",
                          isActive ? "bg-benell-brown text-white" : "text-benell-text hover:bg-benell-surface-muted"
                        )}
                      >
                        <Icon className="size-4" aria-hidden />
                        <span className="truncate">{item.label}</span>
                      </Link>
                    </li>
                  );
                })}
              </ul>
            </nav>
          </aside>
        </div>
      ) : null}
    </div>
  );
}
