import { lazy, Suspense } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import { RequireExternalAuth, RequireExternalCapability, RequirePasswordChanged } from "./auth/RouteGuards.jsx";
import { ExternalAdminLayout } from "./layout/ExternalAdminLayout.jsx";
import { ExternalPageState } from "./shared/PageComponents.jsx";

const LoginPage = lazy(() => import("./pages/LoginPage.jsx"));
const OverviewPage = lazy(() => import("./pages/OverviewPage.jsx"));
const UsersPage = lazy(() => import("./pages/UsersPage.jsx"));
const BansPage = lazy(() => import("./pages/BansPage.jsx"));
const OrganizationPage = lazy(() => import("./pages/OrganizationPage.jsx"));
const RoomsPage = lazy(() => import("./pages/RoomsPage.jsx"));
const GrantsPage = lazy(() => import("./pages/GrantsPage.jsx"));
const BannersPage = lazy(() => import("./pages/BannersPage.jsx"));
const ChangePasswordPage = lazy(() => import("./pages/ChangePasswordPage.jsx"));

export function ExternalAdminApp() {
  return (
    <Suspense fallback={<ExternalPageState loading />}>
      <Routes>
        <Route element={<LoginPage />} path="/login" />
        <Route element={<RequireExternalAuth />}>
          <Route element={<ChangePasswordPage />} path="/change-password" />
          <Route element={<RequirePasswordChanged />}>
            <Route element={<ExternalAdminLayout />}>
              <Route element={<Navigate replace to="/overview" />} index />
              <Route element={<OverviewPage />} path="/overview" />
              <Route element={<RequireExternalCapability anyOf={["user:list", "user:update", "user:ban", "user-level:grant"]} />}>
                <Route element={<UsersPage />} path="/users" />
              </Route>
              <Route element={<RequireExternalCapability anyOf={["user-ban:list", "user:unban"]} />}>
                <Route element={<BansPage />} path="/bans" />
              </Route>
              <Route element={<RequireExternalCapability anyOf={["host:list", "agency:list", "bd:list", "bd-manager:list", "super-admin:list", "team:view"]} />}>
                <Route element={<OrganizationPage />} path="/organization/:kind" />
              </Route>
              <Route element={<RequireExternalCapability anyOf={["room:list", "room:update"]} />}>
                <Route element={<RoomsPage />} path="/rooms" />
              </Route>
              <Route element={<RequireExternalCapability anyOf={["privilege:list", "privilege:grant", "pretty-id:grant", "user-title:grant", "room-background:grant"]} />}>
                <Route element={<GrantsPage />} path="/grants" />
              </Route>
              <Route element={<RequireExternalCapability anyOf={["banner:create"]} />}>
                <Route element={<BannersPage />} path="/banners" />
              </Route>
              <Route element={<Navigate replace to="/overview" />} path="*" />
            </Route>
          </Route>
        </Route>
      </Routes>
    </Suspense>
  );
}
