"use client";

import { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { FOCUS_RING_CLASSES, cardClasses } from "@/components/ui/styles";
import { cn } from "@/lib/utils";

interface NavItem {
  href: string;
  label: string;
  /** Sub-links rendered indented under this item, e.g. Signature's Tema vs Kelola Event pages. */
  children?: NavItem[];
}

interface NavGroup {
  title: string | null;
  items: NavItem[];
}

const GROUPS: NavGroup[] = [
  { title: null, items: [{ href: "/admin", label: "Overview" }] },
  {
    title: "Manage",
    items: [
      { href: "/admin/users", label: "User" },
      { href: "/admin/events", label: "Event" },
      {
        href: "/admin/signature",
        label: "Signature",
        children: [
          { href: "/admin/signature", label: "Theme & Visibility" },
          { href: "/admin/signature/events", label: "Manage Events" },
        ],
      },
      { href: "/admin/categories", label: "Category" },
    ],
  },
  {
    title: "Monitoring",
    items: [
      { href: "/admin/payments", label: "Payment" },
      { href: "/admin/checkins", label: "Check-in" },
      { href: "/admin/analytics", label: "Analytics" },
    ],
  },
  { title: "Content", items: [{ href: "/admin/cms", label: "CMS" }] },
  {
    title: "System",
    items: [
      { href: "/admin/settings", label: "Settings" },
      { href: "/admin/audit-log", label: "Audit Log" },
      { href: "/admin/error-logs", label: "Error Log" },
      { href: "/admin/trash", label: "Trash" },
    ],
  },
];

function isActive(pathname: string, href: string) {
  // "/admin/signature" is a leaf page (Tema & Visibilitas) that sits
  // alongside the "/admin/signature/events" subtree — without an exact-match
  // carve-out here, prefix matching would highlight both nav items whenever
  // a Signature Event sub-page is open (e.g. /admin/signature/events/3/edit).
  if (href === "/admin" || href === "/admin/signature") return pathname === href;
  return pathname === href || pathname.startsWith(`${href}/`);
}

function NavLink({
  item,
  pathname,
  onNavigate,
  indent,
}: {
  item: NavItem;
  pathname: string;
  onNavigate?: () => void;
  indent?: boolean;
}) {
  const active = isActive(pathname, item.href);
  return (
    <Link
      href={item.href}
      onClick={onNavigate}
      aria-current={active ? "page" : undefined}
      className={cn(
        "rounded-lg px-3 py-2 text-sm font-medium transition-colors",
        FOCUS_RING_CLASSES,
        indent && "ml-2",
        active
          ? "bg-kolabora-primary/10 text-kolabora-primary"
          : "text-kolabora-neutral-dark/70 hover:bg-kolabora-neutral-dark/5 hover:text-kolabora-neutral-dark",
      )}
    >
      {item.label}
    </Link>
  );
}

function NavList({ pathname, onNavigate }: { pathname: string; onNavigate?: () => void }) {
  return (
    <nav className="flex flex-col gap-4">
      {GROUPS.map((group, i) => (
        <div key={i}>
          {group.title && (
            <p className="px-3 text-xs font-semibold uppercase tracking-wide text-kolabora-neutral-dark/50">
              {group.title}
            </p>
          )}
          <div className={`flex flex-col gap-0.5 ${group.title ? "mt-1" : ""}`}>
            {group.items.map((item) =>
              item.children ? (
                <div key={item.href} className="flex flex-col gap-0.5">
                  <p className="px-3 pt-1 text-xs font-semibold uppercase tracking-wide text-kolabora-neutral-dark/50">
                    {item.label}
                  </p>
                  {item.children.map((child) => (
                    <NavLink key={child.href} item={child} pathname={pathname} onNavigate={onNavigate} indent />
                  ))}
                </div>
              ) : (
                <NavLink key={item.href} item={item} pathname={pathname} onNavigate={onNavigate} />
              ),
            )}
          </div>
        </div>
      ))}
    </nav>
  );
}

export function AdminSidebar() {
  const pathname = usePathname();
  const [open, setOpen] = useState(false);

  return (
    <>
      {/* Mobile / narrow viewport: toggle button + collapsible panel */}
      <div className="sm:hidden">
        <button
          type="button"
          onClick={() => setOpen((v) => !v)}
          aria-expanded={open}
          aria-controls="admin-sidebar-mobile"
          className={cn(
            "flex w-full items-center justify-between rounded-lg border border-kolabora-neutral-dark/20 px-4 py-2.5 text-sm font-medium transition-colors hover:border-kolabora-neutral-dark/30",
            FOCUS_RING_CLASSES,
          )}
        >
          Admin Menu
          <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden="true"
            className={`shrink-0 transition-transform duration-150 ${open ? "rotate-180" : ""}`}
          >
            <path d="M6 9l6 6 6-6" />
          </svg>
        </button>
        {open && (
          <div
            id="admin-sidebar-mobile"
            className={cn("mt-2", cardClasses("p-3"))}
          >
            <NavList pathname={pathname} onNavigate={() => setOpen(false)} />
          </div>
        )}
      </div>

      {/* Desktop: persistent sidebar */}
      <aside className="hidden w-56 shrink-0 sm:block">
        <div className={cardClasses("p-3")}>
          <NavList pathname={pathname} />
        </div>
      </aside>
    </>
  );
}
