import type { ShopFilterLabels } from '@/lib/shop/filterLabels'
import type { ParsedShopSearchParams } from '@/utilities/shopParams'

import {
  emptyShopFilterLabels,
  getShopClearFiltersHref,
  getShopFilterChips,
} from './shopActiveFilters'

type ShopActiveFiltersControlProps = {
  clearLabel?: null | string
  emptyLabel?: null | string
  filterLabels?: ShopFilterLabels
  filters?: ParsedShopSearchParams
  showWhenEmpty?: boolean | null
  title?: null | string
}

export function ShopActiveFiltersControl({
  clearLabel,
  emptyLabel,
  filterLabels = emptyShopFilterLabels,
  filters,
  showWhenEmpty,
  title,
}: ShopActiveFiltersControlProps) {
  if (!filters) {
    return null
  }

  const chips = getShopFilterChips({
    filterLabels,
    filters,
  })

  if (chips.length === 0 && !showWhenEmpty) {
    return null
  }

  return (
    <section className="border-t border-[#dbe8d7] pt-4 first:border-t-0 first:pt-0">
      <div className="flex items-center justify-between gap-3">
        <h3 className="text-[11px] font-semibold uppercase tracking-[0.18em] text-[#607668]">
          {title || 'Active filters'}
        </h3>
        {chips.length > 0 ? (
          <a
            className="text-[11px] font-semibold text-[#063f2b] underline underline-offset-4 transition hover:text-[#125238]"
            href={getShopClearFiltersHref(filters)}
          >
            {clearLabel || 'Clear all'}
          </a>
        ) : null}
      </div>

      {chips.length > 0 ? (
        <div className="mt-3 flex flex-wrap gap-2">
          {chips.map((chip) => (
            <a
              aria-label={`Remove ${chip.label}`}
              className="inline-flex items-center rounded-full border border-[#b9d8c2] bg-[#edf5e8] px-3 py-1 text-[11px] font-semibold text-[#063f2b] transition hover:border-[#14422d] hover:bg-white"
              href={chip.href}
              key={`${chip.label}-${chip.href}`}
            >
              {chip.label}
              <span aria-hidden="true" className="ml-2">
                x
              </span>
            </a>
          ))}
        </div>
      ) : (
        <p className="mt-3 rounded-lg border border-dashed border-[#dbe8d7] bg-white px-3 py-2 text-xs text-[#607668]">
          {emptyLabel || 'No active filters.'}
        </p>
      )}
    </section>
  )
}
