import { createContext, FC, PropsWithChildren, useContext } from 'react';
import { UseQueryResult, useQuery } from 'react-query';

import { AxiosError } from 'axios';

import { getModuleConfiguration } from 'src/pages/dashboard/serviceManagement/services';
import { ModuleConfiguration } from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import useSnackbar from '../hooks/useSnackbar';
import { serviceManagementKeys } from '../queries';

type ModuleConfigurationContextType = {
  moduleQuery: UseQueryResult<ModuleConfiguration, AxiosError>;
};

const ModuleConfigurationContext =
  createContext<ModuleConfigurationContextType | null>(null);

export const useModuleConfiguration = () => {
  return useContext(
    ModuleConfigurationContext,
  ) as ModuleConfigurationContextType;
};

export const ModuleConfigurationProvider: FC<PropsWithChildren> = ({
  children,
}) => {
  const { t } = useLokaliseTranslation('service_management');
  const { showSnackbar } = useSnackbar();

  const moduleQuery = useQuery(
    serviceManagementKeys.configuration(),
    () => getModuleConfiguration(),
    {
      select: response => response.data,
      onError: (error: AxiosError) => {
        if (error?.response?.status !== 404) {
          showSnackbar({
            title: t('ERROR_LOADING_CONFIGURATION'),
            variant: 'error',
          });
        }
      },
      refetchOnMount: false,
    },
  );

  return (
    <ModuleConfigurationContext.Provider
      value={{
        moduleQuery,
      }}
    >
      {children}
    </ModuleConfigurationContext.Provider>
  );
};
