import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

import { AppLoading } from "../components";
import { DashboardLayout } from "../components/layouts";
import { useAuth } from "../hooks";
import { dashboardRoutes } from "./routes";

const routeMapper = (route, index) =>
  route?.routes?.length > 0 ? (
    route?.routes
      ?.map((r) => ({ ...r, path: route.path + r.path, layout: route.layout }))
      .map(routeMapper)
  ) : (
    <Route
      key={route.path + (index + 1).toString()}
      exact={Boolean(route.layout === "dashboard")}
      path={route.path}
      render={(props) => <route.component {...props} route={route} />}
    />
  );

const PrivateRouter = () => {
  const { userDoc, user, userLoading } = useAuth();
  const esAdmin = userDoc?.rol === "admin";
  let finalDashboardRoutes = dashboardRoutes;

  if( !esAdmin ) {
    finalDashboardRoutes = finalDashboardRoutes.filter( f => !f?.path.includes("administracion") );
  }
  
  if (!user && userLoading) {
    return <AppLoading />;
  }

  return (
    <Router>
      <DashboardLayout>
        <Switch>{finalDashboardRoutes.map(routeMapper)}</Switch>
      </DashboardLayout>
    </Router>
  );
};

export default PrivateRouter;