"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState, type ReactNode } from "react";

function isActive(pathname: string, href: string) {
  if (href === "/admin") return pathname === href;
  return pathname === href || pathname.startsWith(`${href}/`);
}

export function SidebarActiveLink({
  href,
  className = "admin-sidebar-link",
  children,
}: {
  href: string;
  className?: string;
  children: ReactNode;
}) {
  const pathname = usePathname();
  const active = isActive(pathname, href);
  return (
    <Link href={href} data-active={active} className={className}>
      {children}
    </Link>
  );
}

export function SidebarTaxonomiesAccordion({
  items,
  initialOpen,
}: {
  items: ReadonlyArray<{ href: string; label: string }>;
  initialOpen?: boolean;
}) {
  const pathname = usePathname();
  const taxonomiesActive = pathname.startsWith("/admin/sifrarnici");
  const [open, setOpen] = useState(initialOpen ?? taxonomiesActive);

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        data-active={taxonomiesActive}
        aria-expanded={open}
        className="admin-sidebar-link justify-between"
      >
        <span className="flex min-w-0 items-center gap-2">
          <span className="admin-sidebar-link-dot" aria-hidden="true" />
          <span className="truncate">Šifrarnici</span>
        </span>
        <svg
          width="12"
          height="12"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2.5"
          strokeLinecap="round"
          strokeLinejoin="round"
          className={`shrink-0 transition ${open ? "rotate-180" : ""}`}
          aria-hidden="true"
        >
          <path d="M6 9l6 6 6-6" />
        </svg>
      </button>
      {open && (
        <div className="ml-3 mt-1 flex flex-col gap-1 border-l border-border pl-3">
          {items.map((sub) => (
            <SidebarActiveLink
              key={sub.href}
              href={sub.href}
              className="admin-sidebar-link !py-1.5 !text-[0.85rem]"
            >
              <span className="min-w-0 truncate">{sub.label}</span>
            </SidebarActiveLink>
          ))}
        </div>
      )}
    </>
  );
}
