import { useState } from 'react';
import { Chip, HStack } from '@cdx-ui/components';
import { Check } from '@cdx-ui/icons';
import { FILTER_CATEGORIES, type FilterCategory } from './data';

export function CategorySelectionChips() {
  const [selected, setSelected] = useState<Set<FilterCategory>>(
    () => new Set<FilterCategory>(['Groceries', 'Home', 'Health']),
  );

  const toggleCategory = (category: FilterCategory) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(category)) {
        next.delete(category);
      } else {
        next.add(category);
      }
      return next;
    });
  };

  return (
    <HStack className="flex-wrap gap-2">
      {FILTER_CATEGORIES.map((lbl) => {
        const isSelected = selected.has(lbl);
        return (
          <Chip
            key={lbl}
            variant="subtle"
            color={isSelected ? 'action' : 'neutral'}
            accessibilityLabel={
              isSelected ? ['Category:', lbl, '(selected)'].join(' ') : ['Category:', lbl].join(' ')
            }
            onPress={() => toggleCategory(lbl)}
          >
            {isSelected ? <Chip.Icon as={Check} position="leading" /> : null}
            <Chip.Label>{lbl}</Chip.Label>
          </Chip>
        );
      })}
    </HStack>
  );
}
