import { PageID } from "pages";
import LoadingScreen from "components/LoadingScreen";
import useAuth from "hooks/useAuth";
import SimpleLayout from "layouts/simple";
import { ElementType, Suspense, lazy, useMemo } from "react";
import { RouteObject, useRoutes } from "react-router-dom";
import { getRoute } from "./path";
import DashboardRoutes from "./sub/dashboard";

export const Loadable = (Component: ElementType) => (props: any) => {
  return (
    <Suspense fallback={<LoadingScreen />}>
      <Component {...props} />
    </Suspense>
  );
};

const CommonRoutes = (): RouteObject => ({
  element: <SimpleLayout />,
  children: [{}],
});

const AuthRoutes = (): RouteObject => ({
  element: <SimpleLayout />,
  children: [
    {
      path: getRoute(PageID.LOGIN),
      element: <Login />,
    },
    {
      path: getRoute(PageID.LOGOUT),
      element: <Logout />,
    },
    {},
  ],
});

export function Routes() {
  const { initialized } = useAuth();

  return useRoutes([
    CommonRoutes(),
    AuthRoutes(),
    ...DashboardRoutes(),
    {
      path: "403",
      element: <Page403 />,
    },
    {
      path: "*",
      element: initialized ? <Page404 /> : <LoadingScreen />,
    },
  ]);
}

// 認証関連 -------------------------------
const Login = Loadable(lazy(() => import("pages/auth/login")));
const Logout = Loadable(lazy(() => import("pages/auth/logout")));

// その他 ---------------------------------

const Page403 = Loadable(lazy(() => import("pages/common/Page403")));
const Page404 = Loadable(lazy(() => import("pages/common/Page404")));
