import { lazy } from 'react';
import { Navigate, Outlet, createHashRouter, redirect } from 'react-router-dom';
import NProgress from 'nprogress';
import store from '../store';
import { clearQueue } from '../store/cancelReq';
import { routerChangeListener } from '../utils';
import ErrorBoundary from '../components/ErrorBoundary';
NProgress.inc(0.2);
NProgress.configure({ easing: 'ease', speed: 500, showSpinner: false });
NProgress.done();
const Login = lazy(() => import('../views/Login'));
const Home = lazy(() => import('../views/Home'));
const Demo = lazy(() => import('../views/Demo'));

function AuthLoader() {
  if (!store.getState().user.token) {
    return redirect('/login');
  }
  return {};
}

store.dispatch(clearQueue());
routerChangeListener(() => {
  store.dispatch(clearQueue());
  NProgress.start();
  Promise.resolve().then(() => NProgress.done());
});

export default createHashRouter([
  {
    path: '/',
    element: (
      <ErrorBoundary>
        <Outlet />
      </ErrorBoundary>
    ),
    children: [
      {
        index: true,
        element: <Navigate replace to='/home' />,
      },
      {
        path: '/login',
        element: <Login />,
      },
      {
        path: '/home',
        loader: AuthLoader,
        element: <Home />,
      },
      {
        path: '/demo',
        element: <Demo />,
      },
    ],
  },
]);
