import { useMemo } from 'react';
import { useFilterData } from '@assets/filters/state';
import { Logger } from '@assets/filters/common/utils/logger';
import { useBaseFilter } from '@assets/filters/common/contexts/sharedStatics';

const logger = new Logger('useActiveFiltersCount');

export function useActiveFiltersCount() {
   const { filterData } = useFilterData();
   const baseFilter = useBaseFilter();

   return useMemo(() => {
      let count = 0;

      for (const [filterName_, filter] of Object.entries(filterData)) {
         const filterName = filterName_ as keyof typeof filterData;

         if ((filterName === 'producerIds' && typeof baseFilter.producerId !== 'undefined')
            || (filterName === 'search' && typeof baseFilter.search !== 'undefined')
            || (filterName === 'sectionIDsFilter' && typeof baseFilter.categoryId !== 'undefined')
         ) {
            continue;
         }

         if (Array.isArray(filter)) {
            count += filter.length;

            continue;
         }

         if (isIdMap(filter)) {
            for (const filterValue of Object.values(filter)) {
               if (Array.isArray(filterValue)) {
                  count += filterValue.length;

                  continue;
               }

               if (typeof filterValue === 'object'
                  && 'value' in filterValue
                  && Array.isArray(filterValue.value)
               ) {
                  // skip the parameterValueId in baseFilter
                  if (filterName === 'parameters'
                     && typeof baseFilter.parameterValueId !== 'undefined'
                     && filterValue.value.includes(baseFilter.parameterValueId)
                  ) {
                     continue;
                  }

                  count += filterValue.value.length;

                  continue;
               }

               if ('type' in filterValue && filterValue.type === 'float') {
                  count += 1;

                  continue;
               }

               logUnknownFilter(filterName);
            }

            continue;
         }

         if (typeof filter === 'string' || (typeof filter === 'object' && 'from' in filter)) {
            count += 1;

            continue;
         }

         if ('value' in filter && Array.isArray(filter.value)) {
            count += filter.value.length;

            continue;
         }

         logUnknownFilter(filterName);
      }

      return count;
   }, [filterData]);
}

function logUnknownFilter(filterName: string) {
   logger.error(`Could not find the count of unknown filter ${filterName}.`);
}

function isIdMap(value: unknown) {
   if (typeof value !== 'object') {
      return false;
   }

   for (const key in value) {
      if (!Number.isInteger(Number(key))) {
         return false;
      }
   }

   return true;
}

