import { ReactNode, useCallback, Suspense } from "react";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import { route, navigate, operation } from "@/router";
import { observer } from "mobx-react-lite";
import Loading from "@/views/Loading";
import useMyRouter from "./useMyRouter";

const MyRouter = observer(() => {
  const routes = useMyRouter();

  const setRoutes = useCallback(
    (routes: Array<route | navigate | operation>): ReactNode => {
      return routes.map((item, index) => {
        if (item.type === "page") {
          if (item.children && item.children.length) {
            return (
              <Route
                key={item.path}
                path={item.path}
                element={
                  <Suspense fallback={<Loading></Loading>}>
                    <item.element childrenRoutes={item.children} />
                  </Suspense>
                }
              >
                {setRoutes(item.children)}
              </Route>
            );
          } else {
            return (
              <Route
                key={item.path}
                path={item.path}
                element={
                  <Suspense fallback={<Loading></Loading>}>
                    <item.element />
                  </Suspense>
                }
              ></Route>
            );
          }
        } else if (item.type === "navigate") {
          return (
            <Route
              key={item.from}
              path={item.from}
              element={<Navigate to={item.to}></Navigate>}
            ></Route>
          );
        } else {
          return null;
        }
      });
    },
    []
  );

  return (
    <BrowserRouter basename={"/v3"}>
      <Routes>{setRoutes(routes)}</Routes>
    </BrowserRouter>
  );
});

export default MyRouter;
