"use client";

import { useTranslations } from "next-intl";
import { X } from "lucide-react";

import { cn } from "@/lib/utils";
import {
  TEMPLATE_COLORS,
  type TemplateCategoryFilter,
  type TemplateColorId,
  type TemplateStyle,
} from "@/lib/templates-catalog";

export interface ActiveFilterChip {
  id: string;
  label: string;
  onRemove: () => void;
}

interface TemplatesActiveFiltersProps {
  chips: ActiveFilterChip[];
  className?: string;
}

export function TemplatesActiveFilters({
  chips,
  className,
}: TemplatesActiveFiltersProps) {
  const t = useTranslations("auto.componentsTemplatesTemplatesActiveFilters");

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

  return (
    <div className={cn("flex flex-wrap gap-2", className)}>
      {chips.map((chip) => (
        <button
          key={chip.id}
          type="button"
          onClick={chip.onRemove}
          aria-label={t("removeFilter", { label: chip.label })}
          className="inline-flex items-center gap-1.5 rounded-full border border-gray-100 bg-white px-3 py-1.5 text-sm text-neutral-700 shadow-sm transition-colors hover:bg-neutral-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 focus-visible:ring-offset-2"
        >
          {chip.label}
          <X className="h-3.5 w-3.5 text-neutral-400" aria-hidden />
        </button>
      ))}
    </div>
  );
}

export function buildActiveFilterChips(options: {
  category: TemplateCategoryFilter;
  style: TemplateStyle | null;
  color: TemplateColorId | null;
  search: string;
  onCategoryChange: (category: TemplateCategoryFilter) => void;
  onStyleChange: (style: TemplateStyle | null) => void;
  onColorChange: (color: TemplateColorId | null) => void;
  onSearchChange: (search: string) => void;
  searchLabel?: (query: string) => string;
}): ActiveFilterChip[] {
  const chips: ActiveFilterChip[] = [];

  if (options.category !== "All") {
    chips.push({
      id: "category",
      label: options.category,
      onRemove: () => options.onCategoryChange("All"),
    });
  }

  if (options.style) {
    chips.push({
      id: "style",
      label: options.style,
      onRemove: () => options.onStyleChange(null),
    });
  }

  if (options.color) {
    const swatch = TEMPLATE_COLORS.find((item) => item.id === options.color);
    chips.push({
      id: "color",
      label: swatch?.label ?? options.color,
      onRemove: () => options.onColorChange(null),
    });
  }

  if (options.search.trim()) {
    const query = options.search.trim();
    chips.push({
      id: "search",
      label: options.searchLabel
        ? options.searchLabel(query)
        : `Search: "${query}"`,
      onRemove: () => options.onSearchChange(""),
    });
  }

  return chips;
}
