import { memo } from 'react';
import { type FilterCommonProps, FilterOpener } from '@assets/filters/common/components/common';
import { useTheme } from '@assets/filters/common/contexts/theme';
import { useConfig, useFilterData } from '@assets/filters/state';
import { createSelectedSetter } from '@assets/filters/utils';
import { translate as _ } from '@assets/js-shop/ShopUtils';
import MultiChoiceFilter from '@assets/filters/common/components/MultiChoiceFilter';
import { trackLabelsChange } from '@assets/filters/labels/trackLabelsChange';

function LabelsFilter({ withSearch, openerBehaviour = {} }: FilterCommonProps<'multi-choice'>) {
   const { multiChoice: theme } = useTheme();
   const { filterData: { labels }, setFilterData } = useFilterData();
   const { labels: config } = useConfig();

   function setSelected(newIds: number[]) {
      trackLabelsChange(
         config,
         labels ?? [],
         newIds,
      );

      const setState = createSelectedSetter('labels', setFilterData);
      setState(newIds);
   }

   if (!config) {
      return <></>;
   }

   return (
      <FilterOpener
         title={_('labels')}
         isOpen={!!labels?.length}
         activeFilters={labels?.length}
         {...theme.openerBehaviour}
         {...openerBehaviour}
      >
         <MultiChoiceFilter
            values={config ?? []}
            selected={labels ?? []}
            setSelected={setSelected}
            withSearch={withSearch}
         />
      </FilterOpener>
   );
}

const MemoizedLabelsFilter = memo(LabelsFilter);
export { MemoizedLabelsFilter as LabelsFilter };
