import { type InfiniteData, useMutation } from 'react-query';

import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import { queryClient } from 'src/config/react-query';
import { type RequestError, type RequestSuccess } from 'src/types/services';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { LogEvents, logEvent } from 'src/utils/logging';

import { categoriesKeys } from '../queries';
import { deleteCategory } from '../services';
import { type DeleteCategoryParams } from '../types';

import { type TSuccess as GetCategoriesSuccess } from './useGetCategories';

export type TSuccess = RequestSuccess<typeof deleteCategory>;
export type TError = RequestError;
export type TValues = DeleteCategoryParams;

const useDeleteCategory = () => {
  const { enqueueSnackbar } = useHuSnackbar();
  const { t } = useLokaliseTranslation('learning');

  return useMutation<TSuccess, TError, TValues>({
    mutationFn: params => deleteCategory(params),
    onSuccess: (_, { categoryId }) => {
      logEvent(LogEvents.CATEGORY_DELETED, { categoryId });

      const categoriesQueries = queryClient.getQueriesData<
        InfiniteData<GetCategoriesSuccess>
      >(categoriesKeys.list.all());

      // Optimistically delete the category from the list
      categoriesQueries.forEach(([queryKey, data]) => {
        if (!data) return;

        const newPages = data.pages.map(page => ({
          ...page,
          data: {
            ...page.data,
            items: page.data.items.filter(
              category => category.id !== categoryId,
            ),
          },
        }));

        queryClient.setQueryData(queryKey, { ...data, pages: newPages });
      });

      enqueueSnackbar({
        title: t('categories.delete.success'),
        variant: 'success',
      });

      queryClient.invalidateQueries(categoriesKeys.list.all());
    },
    onError: () => {
      enqueueSnackbar({
        title: t('categories.delete.error'),
        description: t('general:retry_later'),
        variant: 'error',
      });
    },
  });
};

export default useDeleteCategory;
