import { type FC, type PropsWithChildren } from 'react';
import {
  MutationCache,
  QueryCache,
  QueryClient,
  QueryClientProvider,
  setLogger,
} from 'react-query';

import useGeneralError from 'src/hooks/useGeneralError';
import { isLibraryNotFoundError } from 'src/pages/dashboard/HuLibraries/utils/errorHandler';

setLogger({
  log: () => {},
  warn: () => {},
  error: () => {},
});

type LibraryErrorHandler = () => void;

let libraryErrorHandlerRef: LibraryErrorHandler | null = null;

export const setLibraryErrorHandler = (
  handler: LibraryErrorHandler | null,
): void => {
  libraryErrorHandlerRef = handler;
};

const queryCache = new QueryCache({
  onError: (error, query) => {
    if (
      isLibraryNotFoundError(error, query.queryKey) &&
      libraryErrorHandlerRef
    ) {
      libraryErrorHandlerRef();
    }
  },
});

const mutationCache = new MutationCache({
  onError: error => {
    if (isLibraryNotFoundError(error) && libraryErrorHandlerRef) {
      libraryErrorHandlerRef();
    }
  },
});

export const queryClient = new QueryClient({
  queryCache,
  mutationCache,
});

export const ReactQueryClientProvider: FC<PropsWithChildren> = ({
  children,
}) => {
  const showGeneralError = useGeneralError();

  queryClient.setDefaultOptions({
    queries: {
      retry: false,
      refetchOnWindowFocus: false,
      onError: err => showGeneralError(err),
    },
    mutations: {
      onError: err => showGeneralError(err),
    },
  });

  return (
    <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
  );
};
