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

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

   return (
      <>
         {Object.entries(filterData.variationsSizeConvertion ?? {})
            .flatMap(([idConvertor, { value }]) => {
               const convertor = config.convertors?.find(c => +c.id === +idConvertor);

               return convertor?.types.flatMap(({ name: typeName, values }) => {
                  return values.map(({ name, id}) => {
                     if (!value.includes(id)) {
                        return null;
                     }

                     return (
                        <Reset
                           key={`convertor-${name}-${idConvertor}-${id}`}
                           onClick={() => setFilterData(removeConvertorValue(+idConvertor, id))}
                        >
                           <span className="name">{convertor.variationName}: </span><span className="value">{typeName} {name}</span>
                        </Reset>
                     );
                  });
               }) ?? null;
            })}
      </>
   );
}

function removeConvertorValue<T extends Selection>(convertorId: number, conversionIdToDelete: number) {
   return (prev: T): T => {
      const newData = { ...prev };

      const convertor = newData.variationsSizeConvertion?.[convertorId];
      if (!convertor) {
         return newData;
      }

      const newValues = convertor.value.filter(id => id !== conversionIdToDelete);

      if (!newValues.length) {
         delete newData.variationsSizeConvertion![convertorId];

         if (Object.keys(newData.variationsSizeConvertion!).length === 0) {
            delete newData.variationsSizeConvertion;
         }

         return newData;
      }

      return {
         ...newData,
         variationsSizeConvertion: {
            ...newData.variationsSizeConvertion,
            [convertorId]: {
               value: newValues
            }
         }
      };
   };
}
