"use client";

import { X } from "lucide-react";
import { useRouter } from "next/navigation";

import { Badge } from "@/components/ui/badge";
import type { ItemSearchParams } from "@/lib/item-search-params";
import { buildItemSearchUrl } from "@/lib/item-search-params";

interface ChipDef {
  label: string;
  clear: Partial<ItemSearchParams>;
}

function buildChips(params: ItemSearchParams): ChipDef[] {
  const chips: ChipDef[] = [];

  if (params.q) chips.push({ label: `Search: "${params.q}"`, clear: { q: null } });
  if (params.categorySlug) chips.push({ label: params.categorySlug, clear: { categorySlug: null } });
  for (const b of params.brand) chips.push({ label: b, clear: { brand: params.brand.filter((x) => x !== b) } });
  for (const c of params.condition)
    chips.push({ label: c, clear: { condition: params.condition.filter((x) => x !== c) } });
  for (const s of params.size) chips.push({ label: s, clear: { size: params.size.filter((x) => x !== s) } });
  for (const c of params.colors)
    chips.push({ label: c, clear: { colors: params.colors.filter((x) => x !== c) } });
  if (params.minPrice !== null || params.maxPrice !== null) {
    const min = params.minPrice !== null ? `$${(params.minPrice / 100).toFixed(0)}` : "";
    const max = params.maxPrice !== null ? `$${(params.maxPrice / 100).toFixed(0)}` : "";
    chips.push({ label: `${min}–${max}`, clear: { minPrice: null, maxPrice: null } });
  }

  return chips;
}

export function ActiveFilterChips({ params }: { params: ItemSearchParams }) {
  const router = useRouter();
  const chips = buildChips(params);

  if (chips.length === 0) return null;

  return (
    <div className="flex flex-wrap items-center gap-2">
      {chips.map((chip, i) => (
        <Badge
          key={i}
          variant="secondary"
          className="cursor-pointer gap-1"
          onClick={() => router.push(buildItemSearchUrl(params, chip.clear))}
        >
          {chip.label}
          <X className="h-3 w-3" />
        </Badge>
      ))}
      <button
        type="button"
        className="text-sm text-forest-700 hover:underline"
        onClick={() => router.push("/items")}
      >
        Clear all
      </button>
    </div>
  );
}
