import { useQueryClient, useQueryErrorResetBoundary } from '@tanstack/react-query';
import { createRouter, ErrorRouteComponent, RouterProvider, useRouter } from '@tanstack/react-router';
import { useEffect } from 'react';
import { useApi } from './api/Api';

import { routeTree } from './routeTree.gen';

//TODO: REAUTH HERE

//TODO: Make nice
export const Error: ErrorRouteComponent = ({ error }) => {
  const router = useRouter();
  const queryErrorResetBoundary = useQueryErrorResetBoundary();
  const _queryClient = useQueryClient();
  const Api = useApi();

  useEffect(() => {
    // Reset the query error boundary
    queryErrorResetBoundary.reset();
  }, [queryErrorResetBoundary]);

  //TODO: Split display, show something went wrong with retry on all, show session expired and back to main on auth
  return (
    <div>
      {error.message}
      <button
        onClick={async () => {
          _queryClient.clear();
          if (Api.hasAuth) await Api.logOut();
          router.invalidate();
        }}
      >
        retry
      </button>
    </div>
  );
};

// Create a new router instance
const router = createRouter({
  routeTree,
  context: {
    //eslint-disable-next-line @typescript-eslint/no-explicit-any
    queryClient: undefined as any,
    //eslint-disable-next-line @typescript-eslint/no-explicit-any
    Api: undefined as any,
  },
  defaultPreload: 'intent',
  // Since we're using React Query, we don't want loader calls to ever be stale
  // This will ensure that the loader is always called when the route is preloaded or visited
  defaultPreloadStaleTime: 0,
  basepath: process.env.NODE_ENV === 'development' ? 'phpCourse/exam/dist' : '/phpCourse/exam',
  //defaultErrorComponent: Error,
});

// Register the router instance for type safety
declare module '@tanstack/react-router' {
  interface Register {
    router: typeof router;
  }
}

const Router = () => {
  const Api = useApi();
  const queryClient = useQueryClient();

  return <RouterProvider router={router} context={{ queryClient, Api }} />;
};

export default Router;
