"use client";

import { useRouter, useSearchParams } from "next/navigation";

/**
 * Filter chips for the v2 Products list.
 *
 * The plan's filter vocabulary was "all" | "in-stock" | "low" | "out" | "hidden".
 * The real `products` schema has no `stock` or `hidden` columns — stock is
 * stored in `inventory` and visibility in `active` (no separate "hidden" flag).
 * The mapping is:
 *   - "all"      → no filter
 *   - "in-stock" → inventory >= 10
 *   - "low"      → inventory > 0 AND inventory < 10
 *   - "out"      → inventory = 0
 *   - "hidden"   → active = false (treating "hidden" as "not visible to customers")
 *
 * Filter state is encoded in the `?filter=` query param so the server
 * component can re-render with the filter applied (no client-side state).
 */
const FILTERS = [
  { value: "all", label: "All" },
  { value: "in-stock", label: "In stock" },
  { value: "low", label: "Low" },
  { value: "out", label: "Out" },
  { value: "hidden", label: "Hidden" },
] as const;

export function ProductsFilterChips({ active }: { active: string }) {
  const router = useRouter();
  const searchParams = useSearchParams();

  function apply(value: string) {
    const params = new URLSearchParams(searchParams.toString());
    if (value === "all") params.delete("filter");
    else params.set("filter", value);
    router.push(`/admin/v2/products?${params.toString()}`);
  }

  return (
    <div className="px-4 pb-3 flex gap-2 overflow-x-auto" role="tablist" aria-label="Filter products">
      {FILTERS.map((f) => {
        const isActive = active === f.value;
        return (
          <button
            key={f.value}
            type="button"
            role="tab"
            aria-selected={isActive}
            onClick={() => apply(f.value)}
            className="rounded-full text-label font-semibold whitespace-nowrap"
            style={{
              minHeight: "40px",
              padding: "0 16px",
              backgroundColor: isActive ? "var(--color-accent)" : "var(--color-surface-2)",
              color: isActive ? "white" : "var(--color-text)",
              letterSpacing: "0.02em",
            }}
          >
            {f.label}
          </button>
        );
      })}
    </div>
  );
}

export default ProductsFilterChips;
