import { AxiosError } from 'axios';
import ErrorBoundary from 'components/error-boundary';
import { NotFound } from 'components/results';
import { MainLayout } from 'layouts/main-layout';
import * as React from 'react';
import { createBrowserRouter, Navigate, Outlet } from 'react-router-dom';
import { useGlobalState } from 'utils/hooks';
import { PrivateRoute, PublicRoute } from './guard-route';

const LoginPage = React.lazy(() => import('pages/login'));
const DashboardPage = React.lazy(() => import('pages/dashboard'));
const InferencePage = React.lazy(() => import('pages/inference'));

const ReviewsPage = React.lazy(() => import('pages/reviews'));
const ReportsPage = React.lazy(() => import('pages/reports'));
const ReportDetailPage = React.lazy(
  () => import('pages/reports/report_detail'),
);

const UsersPage = React.lazy(() => import('pages/users'));

export function useAppRouter() {
  const { data: imperativeError, setData: setImperativeError } =
    useGlobalState<AxiosError | null>(['imperativeError'], null);

  const router = createBrowserRouter([
    {
      path: '/auth/login',
      element: <PublicRoute element={<LoginPage />} />,
    },
    {
      path: '/',
      element: <Navigate to='/dashboard' />,
    },
    {
      path: '/',
      element: (
        <MainLayout>
          <ErrorBoundary
            imperativeError={imperativeError}
            resetImperativeError={() => setImperativeError(null)}
          >
            <Outlet />
          </ErrorBoundary>
        </MainLayout>
      ),
      children: [
        {
          path: '/dashboard',
          element: <PrivateRoute element={<DashboardPage />} />,
        },
        {
          path: '/reports',
          element: <PrivateRoute element={<ReportsPage />} />,
        },
        {
          path: '/reports/:id/detail',
          element: <PrivateRoute element={<ReportDetailPage />} />,
        },
        {
          path: '/inference',
          element: <PrivateRoute element={<InferencePage />} />,
        },
        {
          path: '/reviews',
          element: <PrivateRoute element={<ReviewsPage />} />,
        },
        {
          path: '/users',
          element: <PrivateRoute element={<UsersPage />} />,
        },
      ],
    },
    {
      path: '*',
      element: <NotFound />,
    },
  ]);

  return router;
}
