import {
  createRouter,
  RootRoute,
  Route,
  AnyRoute,
} from "@tanstack/react-router";
import { RootLayout } from "./RouteLayout";
import { getRoutes } from "./routeConfigs";
import NotFound from "../Pages/NotFound";
import { Auth } from "../Pages/Auth";

export const rootRoute = new RootRoute({
  component: RootLayout,
});

export function makeRouter(auth: string | null) {
  try {
    const routeConfigs = getRoutes(auth);

    console.log(
      "Creating router with routes:",
      routeConfigs.length,
      "auth:",
      !!auth
    );

    if (routeConfigs.length === 0) {
      console.log("No routes found, adding default Auth route");
      routeConfigs.push({ path: "/", component: Auth });
    }

    const childRoutes: AnyRoute[] = routeConfigs
      .map(({ path, component }) => {
        try {
          return new Route({
            getParentRoute: () => rootRoute,
            path,
            component,
          }) as AnyRoute;
        } catch (error) {
          console.error(`Error creating route for path ${path}:`, error);
          return null;
        }
      })
      .filter((route): route is AnyRoute => route !== null);

    const notFoundRoute = new Route({
      getParentRoute: () => rootRoute,
      path: "*",
      component: auth ? NotFound : Auth,
    });

    const routeTree = rootRoute.addChildren([...childRoutes, notFoundRoute]);

    const router = createRouter({
      routeTree,
      defaultPreload: "intent",
    });

    console.log("Router created successfully");
    return router;
  } catch (error) {
    console.error("Error creating router:", error);
    try {
      const fallbackRoute = new Route({
        getParentRoute: () => rootRoute,
        path: "/",
        component: Auth,
      });
      const notFoundRoute = new Route({
        getParentRoute: () => rootRoute,
        path: "*",
        component: Auth,
      });
      const routeTree = rootRoute.addChildren([fallbackRoute, notFoundRoute]);
      return createRouter({
        routeTree,
        defaultPreload: "intent",
      });
    } catch (fallbackError) {
      console.error("Fallback router creation also failed:", fallbackError);
      throw fallbackError;
    }
  }
}
