import { BrowserRouter, Route, Routes } from "react-router-dom";
import { routesData } from "./routes";
import { withAuth } from "./routes/withAuth";
import withPermission from "./routes/withPermission";
import { CssBaseline } from "@mui/material";
import FirebaseProvider from "./context/FirebaseProvider";
import { ToastContainer } from "react-toastify";
import ThemeProvider from './theme';
import 'react-toastify/dist/ReactToastify.css';

function App() {
  const renderRoutes = (routes) =>
    routes.map((route) =>
      route.routes ? (
        <Route key={route.path} path={route.path} element={<route.layout />}>
          {route.routes.map((childRoute) => {
            let Component = childRoute.component;

            if (route.isProtected) {
              Component = withAuth(
                childRoute.component,
                childRoute.permission,
                route.isProtected
              );
            }

            if (
              (childRoute.permission && childRoute.withPermission !== false) ||
              childRoute.withPermission === true
            ) {
              Component = withPermission(Component);
            }

            return (
              <Route
                key={childRoute.path}
                path={childRoute.path}
                element={<Component />}
              />
            );
          })}
        </Route>
      ) : (
        <Route
          key={route.path}
          path={route.path}
          element={<route.component />}
        ></Route>
      )
    );

  return (
    <ThemeProvider>
      <BrowserRouter>
        <FirebaseProvider>
          <CssBaseline />
          <Routes>{renderRoutes(routesData)}</Routes>
          <ToastContainer />
        </FirebaseProvider>
      </BrowserRouter>
    </ThemeProvider>
  );
}

export default App;
