import { memo } from 'react';
import { type FilterCommonProps, FilterOpener } from '@assets/filters/common/components/common';
import { useTheme } from '@assets/filters/common/contexts/theme';
import MultiChoiceFilter from '@assets/filters/common/components/MultiChoiceFilter';
import { useVariation } from '@assets/filters/variations/useVariation';
import { useFilterWithOrderBy } from '@assets/filters/common/hooks/useFilterWithOrderBy';
import { useMultiChoiceLoadingStyle } from '@assets/filters/common/hooks/useMultiChoiceLoadingStyle';
import { ShowAllFilterValues } from '@assets/filters/common/components/ShowAllFilterValues';

export type VariationFilterProps = FilterCommonProps<'multi-choice'> & {
   labelId: number;
}

function VariationsFilter({ labelId, withSearch, openerBehaviour = {} }: VariationFilterProps) {
   const { selected, setSelected } = useVariation(+labelId);
   const { multiChoice: theme } = useTheme();

   const {
      config,
      searchInputRef,
      canDisplayShowAll,
      setShowAllValues,
      loading,
   } = useFilterWithOrderBy(
      `variations.${labelId}`,
      cfg => cfg.variations.find(v => v.id === labelId),
      selected,
      (previous, allValues, selected) => {
         const originalVariation = previous.find(l => l.id === labelId);
         const withAllValues = allValues.find(l => l.id === labelId);
         if (!originalVariation || !withAllValues) {
            return previous;
         }

         return [
            ...previous.filter(l => l.id !== labelId),
            {
               ...originalVariation,
               values: [
                  ...withAllValues.values.filter(({ id }) => selected.includes(id)),
                  ...originalVariation.values,
               ],
            }
         ];
      },
   );

   const loadingStyle = useMultiChoiceLoadingStyle(loading);

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

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

const MemoizedVariationFilter = memo(VariationsFilter);
export { MemoizedVariationFilter as VariationsFilter };
