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 { CategoryStatus } from '../constants';
import { categoriesKeys } from '../queries';
import { updateCategoryStatus } from '../services';
import { type UpdateCategoryStatusParams } from '../types';

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

export type TSuccess = RequestSuccess<typeof updateCategoryStatus>;
export type TError = RequestError;
export type TValues = UpdateCategoryStatusParams;

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

  return useMutation<TSuccess, TError, TValues>({
    mutationFn: params => updateCategoryStatus(params),
    onSuccess: (_, { categoryId, status }) => {
      const categoriesQueries = queryClient.getQueriesData<
        InfiniteData<GetCategoriesSuccess>
      >(categoriesKeys.list.all());

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

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

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

      enqueueSnackbar({
        title:
          status === CategoryStatus.ACTIVE
            ? t('categories.activate.success')
            : t('categories.deactivate.success'),
        variant: 'success',
      });

      queryClient.invalidateQueries(categoriesKeys.list.all());
    },
    onError: (_, { status }) => {
      enqueueSnackbar({
        title:
          status === CategoryStatus.ACTIVE
            ? t('categories.activate.error')
            : t('categories.deactivate.error'),
        description: t('general:retry_later'),
        variant: 'error',
      });
    },
  });
};

export default useUpdateCategoryStatus;
