import { createAxiosDataSource, createAxiosInstance } from "@erp/core/client";
import { DataSourceProvider } from "@erp/core/hooks";
import {
  IdentityAuthSessionProvider,
  activeCompanyStorage,
  authTokenStorage,
  getIdentityAuthSessionRuntimeHandlers,
} from "@erp/identity/client";
import { i18n } from "@repo/i18next";
import { LoadingOverlay } from "@repo/rdx-ui/components";
import { Toaster, TooltipProvider } from "@repo/shadcn-ui/components";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import DineroFactory from "dinero.js";
import { Suspense } from "react";
import { I18nextProvider } from "react-i18next";
import { RouterProvider } from "react-router-dom";

import { getAppRouter } from "./routes";

export const App = () => {
  DineroFactory.globalLocale = "es-ES";

  const queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        retry: false,
        staleTime: 10000, // Specify a staleTime to only fetch when the data is older than a certain amount of time
      },
    },
  });

  console.log("import.meta.env.VITE_API_SERVER_URL => ", import.meta.env.VITE_API_SERVER_URL);

  const axiosInstance = createAxiosInstance({
    baseURL: import.meta.env.VITE_API_SERVER_URL,
    getAccessToken: () => authTokenStorage.getAccessToken(),
    getActiveCompanyId: () => activeCompanyStorage.getActiveCompanyId(),
    onRefreshSession: () => getIdentityAuthSessionRuntimeHandlers().refreshAccessToken(),
    onAuthError: () => {
      getIdentityAuthSessionRuntimeHandlers().clearSession();

      if (window.location.pathname !== "/login") {
        window.location.replace("/login");
      }
    },
  });

  const dataSource = createAxiosDataSource(axiosInstance);
  const appRouter = getAppRouter();

  return (
    <I18nextProvider i18n={i18n}>
      <QueryClientProvider client={queryClient}>
        <DataSourceProvider dataSource={dataSource}>
          <IdentityAuthSessionProvider>
            <TooltipProvider>
              {/* Fallback Route */}
              <Suspense fallback={<LoadingOverlay />}>
                <RouterProvider router={appRouter} />
              </Suspense>
            </TooltipProvider>
            <Toaster expand={true} position="top-center" richColors />
            {import.meta.env.DEV && <ReactQueryDevtools initialIsOpen={false} />}
          </IdentityAuthSessionProvider>
        </DataSourceProvider>
      </QueryClientProvider>
    </I18nextProvider>
  );
};
