import { useConfig, useFilterData } from '@assets/filters/state';
import Reset from '@assets/filters/common/components/Reset';
import { Selection } from '@assets/filters/sections/filterDataSlice';

export function SectionsReset() {
   const config = useConfig();
   const { filterData, setFilterData } = useFilterData();

   return (
      <>
         {(filterData.sectionIDsFilter ?? []).map(sectionId => {
            const section = config.sections?.find(p => p.id === sectionId);

            if (!section) {
               return null;
            }

            return (
               <Reset
                  key={`section-${sectionId}`}
                  onClick={() => setFilterData(removeSection(sectionId))}
               >
                  <span className="value">{section.name}</span>
               </Reset>
            );
         })}
      </>
   );
}

function removeSection<T extends Selection>(sectionId: number) {
   return (previousData: T): T => {
      const newData: T = {
         ...previousData,
         sectionIDsFilter: (previousData.sectionIDsFilter ?? []).filter(p => p !== sectionId),
      };

      if (!newData.sectionIDsFilter?.length) {
         delete newData.sectionIDsFilter;
      }

      return newData;
   };
}
