import { ModuleRoutes } from "@/components/module-routes";
import { IModuleClient } from "@erp/core/client";
import { AppLayout, LoadingOverlay, ScrollToTop } from "@repo/rdx-ui/components";
import { JSX, Suspense } from "react";
import { Navigate, Route, BrowserRouter as Router, Routes } from "react-router-dom";
import { ErrorPage } from "../pages";
import { modules } from "../register-modules"; // Aquí ca

function groupModulesByLayout(modules: IModuleClient[]) {
  const groups: Record<string, IModuleClient[]> = {
    auth: [],
    app: [],
  };

  if (modules) {
    for (const module of modules) {
      if (typeof module.layout !== "string") continue;

      const layout = module.layout || "app";
      groups[layout] = groups[layout] || [];
      groups[layout].push(module);
    }
  }

  return groups;
}

export const AppRoutes = (): JSX.Element => {
  const params = {
    ...import.meta.env,
  };

  const grouped = groupModulesByLayout(modules);

  return (
    <Router>
      <ScrollToTop />

      <Suspense fallback={<LoadingOverlay />}>
        <Routes>
          {/* Auth Layout */}
          <Route path='/auth'>
            <Route index element={<Navigate to='login' />} />
            <Route path='*' element={<ModuleRoutes modules={grouped.auth} params={params} />} />
          </Route>

          {/* App Layout */}
          <Route element={<AppLayout />}>
            {/* Dynamic Module Routes */}
            <Route path='*' element={<ModuleRoutes modules={grouped.app} params={params} />} />

            {/* Main Layout */}
            <Route path='/dashboard' element={<ErrorPage />} />
            <Route path='/settings' element={<ErrorPage />} />
            <Route path='/catalog' element={<ErrorPage />} />
            <Route path='/quotes' element={<ErrorPage />} />
            <Route path='*' element={<ErrorPage />} />
          </Route>

          {/* Fallback Route */}
          <Route path='*' element={<ErrorPage />} />
        </Routes>
      </Suspense>
    </Router>
  );
};
