"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
  BarChart3,
  BriefcaseBusiness,
  CalendarDays,
  ChevronLeft,
  ChevronRight,
  ClipboardList,
  FileText,
  HelpCircle,
  LayoutDashboard,
  Loader2,
  Package,
  Receipt,
  Settings,
  Users,
  Wrench,
} from "lucide-react";
import { useTransition, useState } from "react";
import { Button } from "@/components/ui/button";

const items = [
  { label: "Dashboard", href: "/", icon: LayoutDashboard },
  { label: "Clientes", href: "/clientes", icon: Users },
  { label: "Equipamentos", href: "/equipamentos", icon: Package },
  { label: "Categorias", href: "/categorias", icon: BriefcaseBusiness },
  { label: "Locações", href: "/locacoes", icon: ClipboardList },
  { label: "Reservas", href: "/reservas", icon: CalendarDays },
  { label: "Contratos", href: "/contratos", icon: FileText },
  { label: "Financeiro", href: "/financeiro", icon: Receipt },
  { label: "Agenda", href: "/agenda", icon: CalendarDays },
  { label: "Manutenções", href: "/manutencoes", icon: Wrench },
  { label: "Fornecedores", href: "/fornecedores", icon: BriefcaseBusiness },
  { label: "Relatórios", href: "/relatorios", icon: BarChart3 },
  { label: "Configurações", href: "/configuracoes", icon: Settings },
];

interface SidebarProps {
  isCollapsed: boolean;
  onToggleCollapse: () => void;
}

export function Sidebar({ isCollapsed, onToggleCollapse }: SidebarProps) {
  const pathname = usePathname();
  const router = useRouter();
  const [isPending, startTransition] = useTransition();
  const [pendingHref, setPendingHref] = useState<string | null>(null);

  const handleNav = (href: string) => {
    if (href === pathname) return;
    setPendingHref(href);
    startTransition(() => {
      router.push(href);
    });
  };

  // Pré-aquece a rota ao passar o mouse, reduzindo lag na primeira visita
  const handlePrefetch = (href: string) => {
    router.prefetch(href);
  };

  // Clear pending state when navigation completes
  if (pendingHref && !isPending) {
    // Use setTimeout to avoid state update during render
    setTimeout(() => setPendingHref(null), 0);
  }

  const isActive = (href: string) => {
    if (pendingHref) return pendingHref === href;
    return href === "/" ? pathname === "/" : pathname.startsWith(href);
  };

  return (
    <aside
      className={`hidden shrink-0 border-r bg-card/90 backdrop-blur transition-all duration-300 lg:flex lg:flex-col sticky top-0 h-screen print:hidden ${
        isCollapsed ? "w-16" : "w-64"
      }`}
    >
      {/* Brand Header & Toggle Button */}
      <div
        className={`flex h-16 shrink-0 items-center border-b ${
          isCollapsed ? "justify-center px-2" : "justify-between px-4"
        }`}
      >
        {isCollapsed ? (
          <Button
            variant="ghost"
            onClick={onToggleCollapse}
            className="h-10 w-10 p-0 flex items-center justify-center rounded-lg bg-primary text-sm font-bold text-primary-foreground shadow-xs hover:bg-primary/90 hover:text-primary-foreground relative group"
            title="Expandir menu"
          >
            <span className="group-hover:hidden">BL</span>
            <ChevronRight className="hidden h-5 w-5 group-hover:block text-primary-foreground" />
          </Button>
        ) : (
          <>
            <div className="flex items-center gap-3 overflow-hidden">
              <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-primary text-sm font-bold text-primary-foreground shadow-xs">
                BL
              </div>
              <div className="truncate">
                <p className="text-sm font-bold text-foreground">BlackLoc</p>
                <p className="text-xs text-muted-foreground truncate">Locações industriais</p>
              </div>
            </div>

            <Button
              variant="ghost"
              size="icon"
              onClick={onToggleCollapse}
              className="h-8 w-8 text-muted-foreground hover:text-foreground"
              title="Recolher menu"
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
          </>
        )}
      </div>

      {/* Navigation Menu — flex-1 so it fills available space */}
      <nav className="flex flex-1 flex-col justify-between overflow-y-auto px-2 py-4">
        {/* Main Items */}
        <div className="space-y-1">
          {items.map((item) => {
            const Icon = item.icon;
            const active = isActive(item.href);
            const isPendingItem = pendingHref === item.href;

            return (
              <button
                key={item.label}
                onClick={() => handleNav(item.href)}
                onMouseEnter={() => handlePrefetch(item.href)}
                title={isCollapsed ? item.label : undefined}
                className={`w-full flex h-10 items-center gap-3 rounded-lg px-3 text-sm font-medium transition-all ${
                  isCollapsed ? "justify-center px-0" : ""
                } ${
                  active
                    ? "bg-primary text-primary-foreground shadow-xs font-semibold"
                    : "text-muted-foreground hover:bg-muted hover:text-foreground"
                }`}
              >
                {isPendingItem ? (
                  <Loader2 className="h-4 w-4 shrink-0 animate-spin" />
                ) : (
                  <Icon className={`h-4 w-4 shrink-0 ${active ? "text-primary-foreground" : ""}`} />
                )}
                {!isCollapsed && <span className="truncate">{item.label}</span>}
              </button>
            );
          })}
        </div>

        {/* Ajuda — pinned at bottom */}
        <div className="mt-4 border-t pt-3">
          {!isCollapsed && (
            <p className="mb-1.5 px-3 text-[10px] font-semibold uppercase tracking-widest text-muted-foreground/60">
              Suporte
            </p>
          )}
          <Link
            href="/ajuda"
            title={isCollapsed ? "Ajuda & Manual do Sistema" : undefined}
            className={`flex h-10 items-center gap-3 rounded-lg px-3 text-sm font-medium transition-all ${
              isCollapsed ? "justify-center px-0" : ""
            } ${
              pathname.startsWith("/ajuda")
                ? "bg-primary text-primary-foreground shadow-xs font-semibold"
                : "text-muted-foreground hover:bg-muted hover:text-foreground"
            }`}
          >
            <HelpCircle className={`h-4 w-4 shrink-0 ${pathname.startsWith("/ajuda") ? "text-primary-foreground" : ""}`} />
            {!isCollapsed && <span className="truncate">Ajuda & Manual</span>}
          </Link>
        </div>
      </nav>
    </aside>
  );
}
