import Link from "next/link";
import { cn } from "@/lib/cn";
import { DISPLAY_STATUSES, STATUS_LABELS, type DisplayStatus } from "@/lib/status";
import type { DashboardSummary } from "@/server/dashboard/service";

const COUNT_KEY: Record<DisplayStatus, keyof DashboardSummary> = {
  WORKING: "working",
  SLOW: "slow",
  NOT_WORKING: "notWorking",
  PENDING: "pending",
  DISABLED: "disabled",
};

type StatusFilterProps = {
  active: DisplayStatus | null;
  summary: DashboardSummary;
  /** Builds the link for a status tab (null = All); the caller keeps its own search / sort. */
  hrefFor: (status: DisplayStatus | null) => string;
};

/** Filter tabs shared by the Dashboard and the Apps list. */
export function StatusFilter({ active, summary, hrefFor }: StatusFilterProps) {
  const options: Array<{ status: DisplayStatus | null; label: string; count: number }> = [
    { status: null, label: "All", count: summary.total },
  ];
  for (const status of DISPLAY_STATUSES) {
    const count = summary[COUNT_KEY[status]] as number;
    // "Not checked yet" is only worth a tab while some app is still waiting for its first check.
    if (status === "PENDING" && count === 0 && active !== "PENDING") continue;
    options.push({ status, label: STATUS_LABELS[status], count });
  }

  return (
    <nav className="flex flex-wrap items-center gap-1" aria-label="Filter by status">
      {options.map((option) => {
        const isActive = active === option.status;
        return (
          <Link
            key={option.label}
            href={hrefFor(option.status)}
            aria-current={isActive ? "true" : undefined}
            className={cn(
              "inline-flex h-8 items-center gap-1.5 rounded-md px-2.5 text-xs font-medium whitespace-nowrap transition-colors",
              isActive ? "bg-slate-900 text-white" : "text-slate-600 hover:bg-slate-100 hover:text-slate-900",
            )}
          >
            {option.label}
            <span className={cn("tabular-nums", isActive ? "text-slate-300" : "text-slate-400")}>{option.count}</span>
          </Link>
        );
      })}
    </nav>
  );
}
