import { Route, Routes } from 'react-router-dom';

import { Loadable } from 'src/routes';
import { lazyRetry } from 'src/utils/lazyRetry';
import { ROUTE_PERMISSIONS } from 'src/utils/permissions';

import { articleActionRoutes } from './Layout/articleActionRoutes';

const PermissionsGuard = Loadable(
  lazyRetry(() => import('src/components/guards/PermissionsGuard')),
);

const HuLibrariesLayout = Loadable(lazyRetry(() => import('./Layout')));
const HuLibrariesHome = Loadable(lazyRetry(() => import('./Home')));
const HuLibrariesArticle = Loadable(lazyRetry(() => import('./Article')));
const HuLibrariesRootArticleLayout = Loadable(
  lazyRetry(() => import('./Layout/RootArticleLayout')),
);
const HuLibrariesChildArticleLayout = Loadable(
  lazyRetry(() => import('./Layout/ChildArticleLayout')),
);

const renderArticleActionRoutes = () =>
  articleActionRoutes.map(({ path, element }) => (
    <Route
      key={path}
      path={path}
      element={element}
    />
  ));

const HuLibrariesRoutes = () => (
  <Routes>
    <Route element={<HuLibrariesLayout />}>
      <Route
        index
        element={
          <PermissionsGuard
            requiredPermissions={ROUTE_PERMISSIONS.KNOWLEDGE_LIBRARY}
          >
            <HuLibrariesHome />
          </PermissionsGuard>
        }
      />
      <Route
        path=":rootId"
        element={
          <PermissionsGuard
            requiredPermissions={ROUTE_PERMISSIONS.KNOWLEDGE_LIBRARY}
          >
            <HuLibrariesRootArticleLayout />
          </PermissionsGuard>
        }
      >
        <Route
          index
          element={<HuLibrariesArticle />}
        />
        {renderArticleActionRoutes()}
        <Route
          path="child/:childId"
          element={<HuLibrariesChildArticleLayout />}
        >
          <Route
            index
            element={<HuLibrariesArticle />}
          />
          {renderArticleActionRoutes()}
        </Route>
      </Route>
    </Route>
  </Routes>
);

export default HuLibrariesRoutes;
