'use client';

import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { X } from 'lucide-react';

export interface FilterChip {
  id: string;
  label: string;
  /** Optional filter name shown before the value, e.g. "Status". */
  name?: string;
}

export function FilterChips({
  chips,
  onRemove,
  onClear,
}: {
  chips: FilterChip[];
  onRemove: (id: string) => void;
  onClear: () => void;
}) {
  const reduce = useReducedMotion();
  return (
    <AnimatePresence initial={false}>
      {chips.length === 0 ? null : (
        <motion.div
          key="chips"
          initial={reduce ? { opacity: 0 } : { opacity: 0, height: 0 }}
          animate={reduce ? { opacity: 1 } : { opacity: 1, height: 'auto' }}
          exit={reduce ? { opacity: 0 } : { opacity: 0, height: 0 }}
          transition={{ duration: 0.18 }}
          className="overflow-hidden"
        >
          <div className="flex flex-wrap items-center gap-2 pt-0.5">
            <AnimatePresence initial={false}>
              {chips.map((chip) => (
                <motion.button
                  key={chip.id}
                  layout={!reduce}
                  type="button"
                  initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.9 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.9 }}
                  transition={{ duration: 0.15 }}
                  className="group inline-flex h-7 items-center gap-1.5 rounded-pill border border-primary/25 bg-primary-soft pl-2.5 pr-1.5 text-caption font-medium text-foreground transition-colors hover:border-primary/50"
                  onClick={() => onRemove(chip.id)}
                >
                  {chip.name === undefined ? null : <span className="text-muted-foreground">{chip.name}:</span>}
                  <span className="max-w-48 truncate">{chip.label}</span>
                  <span className="grid h-4 w-4 place-items-center rounded-full text-muted-foreground transition-colors group-hover:bg-surface group-hover:text-foreground" aria-hidden="true">
                    <X className="h-3 w-3" />
                  </span>
                  <span className="sr-only">Remove filter {chip.name === undefined ? '' : `${chip.name} `}{chip.label}</span>
                </motion.button>
              ))}
            </AnimatePresence>
            <button type="button" className="h-7 rounded-sm px-1 text-caption font-semibold text-primary underline-offset-4 hover:underline" onClick={onClear}>
              Clear all
            </button>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
