import Link from "next/link";
import { cn } from "@/lib/utils";
import { withParams, type QueryParams } from "./query";

export type TabItem = {
  /** Value written to the `status` (or `type`) searchParam; empty string = All. */
  value: string;
  label: string;
  count?: number;
};

/**
 * Link-based tab strip (server rendered, no client JS). Selecting a tab resets
 * pagination and keeps every other searchParam.
 */
export function TabLinks({
  pathname,
  params,
  paramKey = "status",
  active,
  tabs,
  className,
}: {
  pathname: string;
  params: QueryParams;
  paramKey?: string;
  active: string;
  tabs: TabItem[];
  className?: string;
}) {
  return (
    <div className={cn("-mx-1 overflow-x-auto px-1 pb-1", className)}>
      <nav
        aria-label="Filter by status"
        className="inline-flex min-w-full items-center gap-1 rounded-xl bg-muted/60 p-1"
      >
        {tabs.map((tab) => {
          const isActive = tab.value === active;
          return (
            <Link
              key={tab.value || "all"}
              href={withParams(pathname, params, {
                [paramKey]: tab.value || null,
                page: null,
              })}
              aria-current={isActive ? "page" : undefined}
              className={cn(
                "inline-flex shrink-0 items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium whitespace-nowrap transition-colors",
                isActive
                  ? "bg-background text-foreground shadow-sm"
                  : "text-muted-foreground hover:text-foreground",
              )}
            >
              {tab.label}
              {typeof tab.count === "number" ? (
                <span
                  className={cn(
                    "font-mono text-[11px] tabular-nums",
                    isActive ? "text-muted-foreground" : "text-muted-foreground/70",
                  )}
                >
                  {tab.count}
                </span>
              ) : null}
            </Link>
          );
        })}
      </nav>
    </div>
  );
}

export default TabLinks;
