"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { menuGroups } from "@/lib/menuGroup";
import { menuReport } from "@/lib/menuReport";
import { menuDeepdex } from "@/lib/menuDeepdex";
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn } from "@/lib/utils";

interface SidebarProps {
  isOpen: boolean;
  isReportOpen: boolean;
  isDeepdexOpen: boolean;
  onClose: () => void;
}

interface MenuLeaf {
  label: string;
  href: string;
  icon: any;
}

/**
 * Slide-over navigation, rebuilt on the shadcn `Sheet` primitive.
 *
 * Radix now provides the overlay, slide transition, focus trap, focus restore,
 * Escape handling, scroll lock and `aria-modal` — all of which this component
 * previously either hand-rolled or simply did not have.
 *
 * The behavioural fixes that matter most, though, are in the links themselves:
 *
 * 1. They were plain `<a href>`, so every menu click triggered a **full
 *    document reload** — blank screen, re-fetched bundle, lost client state.
 *    They are `next/link` now, which is what makes navigation feel instant.
 * 2. Nothing indicated where you currently were. The active route is marked
 *    with a tint, a weight change and `aria-current`.
 */
export function Sidebar({ isOpen, isReportOpen, isDeepdexOpen, onClose }: SidebarProps) {
  const pathname = usePathname();
  const isVisible = isOpen || isReportOpen || isDeepdexOpen;
  const title = isOpen ? "Transactions" : isReportOpen ? "Reports" : "Deepdex";

  const isActiveHref = (href: string) => {
    const base = href.split("?")[0];
    return pathname === base || pathname?.startsWith(`${base}/`);
  };

  const renderLink = ({ label, href, icon: Icon }: MenuLeaf) => {
    const active = isActiveHref(href);
    return (
      <li key={label}>
        <Link
          href={href}
          onClick={onClose}
          aria-current={active ? "page" : undefined}
          className={cn(
            // min-h-10 keeps every row a comfortable target on touch screens
            "flex min-h-10 items-center gap-2.5 rounded-md px-2.5 py-2 text-sm transition-colors",
            active
              ? "bg-sidebar-accent font-semibold text-sidebar-accent-foreground"
              : "font-medium text-sidebar-foreground hover:bg-sidebar-accent/60"
          )}
        >
          <Icon
            className={cn(
              "size-4 shrink-0",
              active ? "text-sidebar-primary" : "text-muted-foreground"
            )}
            aria-hidden
          />
          <span className="min-w-0 truncate">{label}</span>
        </Link>
      </li>
    );
  };

  const renderGroup = ({
    label,
    icon: Icon,
    children,
  }: {
    label: string;
    icon: any;
    children: MenuLeaf[];
  }) => (
    <div key={label}>
      <p className="oxy-eyebrow mb-1.5 flex items-center gap-2 px-2.5">
        <Icon className="size-3.5 shrink-0" aria-hidden />
        {label}
      </p>
      <ul className="space-y-0.5">{children.map(renderLink)}</ul>
    </div>
  );

  return (
    <Sheet open={isVisible} onOpenChange={(open) => !open && onClose()}>
      <SheetContent
        side="left"
        className="w-[min(20rem,88vw)] gap-0 bg-sidebar p-0"
      >
        <SheetHeader className="border-b border-sidebar-border px-4 py-3.5">
          <p className="oxy-eyebrow">Menu</p>
          <SheetTitle className="text-base">{title}</SheetTitle>
          <SheetDescription className="sr-only">
            {title} navigation menu
          </SheetDescription>
        </SheetHeader>

        <ScrollArea className="min-h-0 flex-1">
          <nav aria-label={title} className="space-y-5 px-2 py-4">
            {isOpen && (
              <>
                <ul className="space-y-0.5">
                  {menuGroups
                    .filter((item) => "href" in item && !("children" in item))
                    .map((item) => renderLink(item as MenuLeaf))}
                </ul>

                {menuGroups
                  .filter((item) => "children" in item && item.children)
                  .map((item) => renderGroup(item as any))}
              </>
            )}

            {isReportOpen && menuReport.map((item) => renderGroup(item as any))}

            {isDeepdexOpen && menuDeepdex.map((item) => renderGroup(item as any))}
          </nav>
        </ScrollArea>
      </SheetContent>
    </Sheet>
  );
}
