/* eslint-disable react-refresh/only-export-components */
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { render, RenderOptions } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { FC, ReactElement, useEffect } from 'react';
import { MemoryRouter, Route, Routes } from 'react-router';

import { RecoilRoot } from 'recoil';
import { SubLayout } from '@/widgets/sub-layout';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: false,
      throwOnError: true,
      refetchOnWindowFocus: false,
    },
  },
});

interface RouterParams {
  path?: string;
  entry?: string;
  state?: any;
}

const AllTheProviders: FC<{ children: React.ReactNode; routerParams?: RouterParams }> = ({
  children,
  routerParams,
}) => {
  const { path = '/', entry = '/', state } = routerParams ?? {};
  const initialEntry = { pathname: entry, state };
  useEffect(() => {
    return () => queryClient.clear();
  }, []);
  return (
    <RecoilRoot>
      <QueryClientProvider client={queryClient}>
        <MemoryRouter initialEntries={[initialEntry]}>
          <Routes>
            <Route element={<SubLayout />}>
              <Route path={path} element={<>{children}</>} />
            </Route>
          </Routes>
        </MemoryRouter>
      </QueryClientProvider>
    </RecoilRoot>
  );
};
const user = userEvent.setup();
const customRender = (ui: ReactElement, routerParams?: RouterParams, options?: Omit<RenderOptions, 'wrapper'>) => {
  return render(ui, { wrapper: (props) => <AllTheProviders {...props} routerParams={routerParams} />, ...options });
};

export * from '@testing-library/react';
export { customRender as render, user };
