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

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

   const setSelected = useCallback(createSelectedSetter('producerIds', setFilterData), [setFilterData]);

   const {
      config,
      searchInputRef,
      canDisplayShowAll,
      setShowAllValues,
      loading,
   } = useFilterWithOrderBy('producers',
      cfg => cfg.producers,
      producerIds,
      (previous, allValues, selected) => {
         return {
            ...previous,
            values: [
               ...allValues.values.filter(({ id }) => selected.includes(id)),
               ...previous.values,
            ],
         };
      },
   );

   const loadingStyle = useMultiChoiceLoadingStyle(loading);

   if (!config?.values || !config.values.length) {
      return <></>;
   }

   return (
      <FilterOpener
         title={_('producers')}
         isOpen={!!producerIds?.length}
         activeFilters={producerIds?.length}
         {...theme.openerBehaviour}
         {...openerBehaviour}
      >
         <MultiChoiceFilter
            values={config.values}
            selected={producerIds ?? []}
            setSelected={setSelected}
            withSearch={withSearch}
            searchRef={searchInputRef}
            listProps={{ style: loadingStyle }}
         >
            {canDisplayShowAll && (
               <ShowAllFilterValues
                  count={config.values_count - config.values.length}
                  onClick={() => setShowAllValues(true)}
               />
            )}
         </MultiChoiceFilter>
      </FilterOpener>
   );
}

const MemoizedProducersFilter = memo(ProducersFilter);
export { MemoizedProducersFilter as ProducersFilter };
