import { useQuery } from 'react-query';

import { useAuth } from 'src/contexts/JWTContext';
import useGeneralError from 'src/hooks/useGeneralError';
import useNetworkStatus from 'src/hooks/useNetworkStatus';
import { PaginatedQueryStates } from 'src/hooks/usePaginatedQueryState';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { acknowledgementsKeys } from '../queries';
import { getUserExchanges } from '../services';

export const useGetExchanges = () => {
  const { user } = useAuth();
  const userId = user?.id;
  const showGeneralError = useGeneralError();
  const { isOnline } = useNetworkStatus();
  const { t } = useLokaliseTranslation('acknowledgements');

  const {
    data: exchanges = [],
    isLoading,
    isError,
    refetch,
  } = useQuery({
    queryKey: acknowledgementsKeys.exchanges(userId),
    queryFn: () => {
      if (!userId) throw new Error('[useGetExchanges] userId required');
      return getUserExchanges(userId);
    },
    enabled: Boolean(userId),
    select: response => response.data ?? [],
    onError: err => showGeneralError(err, t('error_get_acknowledgements')),
  });

  const isEmpty = !isLoading && !isError && exchanges.length === 0;

  const getState = () => {
    if (isError) {
      return isOnline
        ? PaginatedQueryStates.ERROR
        : PaginatedQueryStates.NETWORK_ERROR;
    }

    if (isEmpty) {
      return PaginatedQueryStates.EMPTY;
    }

    return PaginatedQueryStates.SUCCESS;
  };

  return {
    exchanges,
    isLoading,
    isError,
    isEmpty,
    state: getState(),
    refetch,
  };
};
