"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { Menu, UserCircle2, X } from "lucide-react";
import { usePathname } from "next/navigation";
import { Button } from "@/components/ui/button";
import { getVisibleNavItems } from "@/components/layout/navigation";
import { cn } from "@/lib/utils";
import { LogoutButton } from "@/components/auth/logout-button";

type MobileNavDrawerProps = {
  userName?: string | null;
  userRole?: string | null;
};

export function MobileNavDrawer({ userName, userRole }: MobileNavDrawerProps) {
  const [open, setOpen] = useState(false);
  const pathname = usePathname();
  const closeButtonRef = useRef<HTMLButtonElement | null>(null);
  const panelRef = useRef<HTMLDivElement | null>(null);
  const previousFocusRef = useRef<HTMLElement | null>(null);

  useEffect(() => {
    const timer = window.setTimeout(() => setOpen(false), 0);
    return () => window.clearTimeout(timer);
  }, [pathname]);

  useEffect(() => {
    if (!open) return;

    previousFocusRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
    const timer = window.setTimeout(() => closeButtonRef.current?.focus(), 0);
    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.preventDefault();
        setOpen(false);
      }

      if (event.key === "Tab") {
        const focusable = panelRef.current?.querySelectorAll<HTMLElement>(
          'a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])',
        );
        if (!focusable || focusable.length === 0) return;
        const first = focusable[0];
        const last = focusable[focusable.length - 1];

        if (event.shiftKey && document.activeElement === first) {
          event.preventDefault();
          last.focus();
        } else if (!event.shiftKey && document.activeElement === last) {
          event.preventDefault();
          first.focus();
        }
      }
    };

    document.addEventListener("keydown", onKeyDown);
    return () => {
      window.clearTimeout(timer);
      document.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = originalOverflow;
      previousFocusRef.current?.focus();
    };
  }, [open]);

  const drawerClasses = useMemo(
    () => cn("fixed inset-0 z-50 lg:hidden", open ? "pointer-events-auto" : "pointer-events-none"),
    [open],
  );
  const visibleNavItems = useMemo(() => getVisibleNavItems(userRole), [userRole]);

  return (
    <>
      <Button
        type="button"
        variant="outline"
        size="icon"
        className="h-9 w-9 lg:hidden"
        onClick={() => setOpen(true)}
        aria-label="Abrir menú"
      >
        <Menu className="h-4 w-4" />
      </Button>

      <div className={drawerClasses} aria-hidden={!open}>
        <div
          className={cn(
            "absolute inset-0 bg-foreground/40 transition-opacity duration-200",
            open ? "opacity-100" : "opacity-0",
          )}
          onMouseDown={() => setOpen(false)}
        />

        <aside
          ref={panelRef}
          role="dialog"
          aria-modal="true"
          aria-label="Menú de navegación"
          className={cn(
            "absolute left-0 top-0 flex h-dvh w-[85vw] max-w-xs flex-col border-r border-border bg-background shadow-2xl ring-1 ring-border/40 transition-transform duration-200 ease-out",
            open ? "translate-x-0" : "-translate-x-full",
          )}
        >
          <div className="flex shrink-0 items-start justify-between border-b border-border bg-background px-5 py-4">
            <div>
              <p className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">LOTIAPP</p>
              <h2 className="mt-0.5 text-sm font-medium leading-snug text-foreground">Empadronamientos Viñas Fundo El Bosque</h2>
            </div>
            <Button
              ref={closeButtonRef}
              type="button"
              variant="ghost"
              size="icon"
              onClick={() => setOpen(false)}
              aria-label="Cerrar menú"
            >
              <X className="h-4 w-4" />
            </Button>
          </div>

          <div className="shrink-0 border-b border-border bg-background px-5 py-4">
            <p className="text-sm font-medium text-foreground">{userName ?? "Usuario"}</p>
            <p className="text-xs text-muted-foreground">{userRole ?? "-"}</p>
          </div>

          <nav className="min-h-0 flex-1 space-y-1 overflow-y-auto px-4 py-4">
            {visibleNavItems.map((item) => {
              const Icon = item.icon;
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  onClick={() => setOpen(false)}
                  className="flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium text-foreground hover:bg-accent hover:text-accent-foreground"
                >
                  <Icon className="h-4 w-4" aria-hidden="true" />
                  {item.label}
                </Link>
              );
            })}
          </nav>

          <div className="shrink-0 border-t border-border bg-background px-4 py-4">
            <div className="flex flex-col gap-3">
              <Button asChild variant="outline" size="sm" className="justify-start gap-2">
                <Link href="/perfil" onClick={() => setOpen(false)}>
                  <UserCircle2 className="h-4 w-4" />
                  Mi perfil
                </Link>
              </Button>
              <LogoutButton />
            </div>
            <div className="mt-4 border-t border-border pt-4 text-xs leading-5 text-muted-foreground">
              <p>Desarrollado por</p>
              <p className="font-medium text-foreground">Claudio Briones Ogalde</p>
            </div>
          </div>
        </aside>
      </div>
    </>
  );
}
