import { Box } from '@mui/material';
import { QueryClient, useQueryErrorResetBoundary } from '@tanstack/react-query';
import { createRootRouteWithContext, ErrorRouteComponent, Outlet, redirect, useRouter } from '@tanstack/react-router';
import { TanStackRouterDevtools } from '@tanstack/router-devtools';
import { useEffect } from 'react';
import Api from '../api/Api';
import { ERRORS } from '../components/Error/Errors';
import Header from '../components/Header/Header';
import { ROUTES } from '../types/Routes';

const Root = () => {
  //TODO: REAUTH HERE

  return (
    <>
      <Header />
      <Box sx={{ display: 'flex', justifyContent: 'center' }}>
        <Box sx={{ maxWidth: '800px', flexGrow: 1 }}>
          <Outlet />
        </Box>
      </Box>
      {process.env.NODE_ENV === 'development' && <TanStackRouterDevtools />}
    </>
  );
};

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

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

  if ('code' in error && error.code === ERRORS.UNAUTHORIZED) {
    Api.logOut();
    redirect({ to: ROUTES.INDEX });
  }
  return (
    <div>
      {error.message}
      <button
        onClick={() => {
          router.invalidate();
        }}
      >
        retry
      </button>
    </div>
  );
};

export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()({
  component: Root,
  errorComponent: Error,
});
