import * as React from 'react';
import { useFilterData, useConfig } from '@assets/filters/state';

// Asi to funguje, ale moc hezký to teda není.
// TODO(hauschwitz): Refactor
export function useConvertor(convertorId: number) {
   const { convertors: allConfigConvertors } = useConfig();
   const { filterData: { variationsSizeConvertion }, setFilterData } = useFilterData();

   const [selectedTypeName, setSelectedType] = React.useState<string | undefined>();
   const selectedIds = variationsSizeConvertion?.[convertorId]?.value || [];
   const convertor = allConfigConvertors?.find(c => c.id === convertorId);

   React.useEffect(() => {
      selectedTypeName || setSelectedType(convertor?.types[0].name);
   }, [setSelectedType, selectedTypeName, allConfigConvertors]);

   const selectedType = convertor?.types.find(({ name }) => name === selectedTypeName);

   const setSelected = React.useCallback((newSelected: number[]) => {
      const type = allConfigConvertors
         ?.find(({ id }) => id === convertorId)
         ?.types
         ?.find(({ name }) => name === selectedTypeName);

      const allValidIdsOfCurrentConvertor = type?.values?.map(({ id }) => id) ?? [];

      setFilterData(old => {
         const currentlySelected = old.variationsSizeConvertion?.[convertorId]?.value ?? [];

         let newConvertorValues = currentlySelected.filter(oldId => !allValidIdsOfCurrentConvertor.includes(oldId));
         newConvertorValues = newConvertorValues.concat(newSelected);

         if (!newConvertorValues.length) {
            const convertorFilterData = { ...(old.variationsSizeConvertion ?? {}) };
            delete convertorFilterData[convertorId];

            if (Object.keys(convertorFilterData).length === 0) {
               const newFiltersState = { ...old };
               delete newFiltersState.variationsSizeConvertion;

               return newFiltersState;
            }

            return { ...old, variationsSizeConvertion: convertorFilterData };
         }

         return {
            ...old,
            variationsSizeConvertion: { ...(old.variationsSizeConvertion ?? {}), [convertorId]: { value: newConvertorValues } },
         };
      });
   }, [convertor, selectedType, convertorId, allConfigConvertors]);

   if (!convertor || !convertor.types.length) {
      return {};
   }

   return { convertor, setSelectedType, selectedType, selectedIds, setSelected };
}
