import { Toaster, TooltipProvider } from "@repo/shadcn-ui/components";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";

import { I18nextProvider } from "react-i18next";

import { i18n } from "@/locales";

import { AuthProvider, createAuthService } from "@erp/auth/client";
import { createAxiosDataSource, createAxiosInstance } from "@erp/core/client";
import { DataSourceProvider } from "@erp/core/hooks";
import DineroFactory from "dinero.js";
import { RouterProvider } from "react-router-dom";
import { clearAccessToken, getAccessToken, setAccessToken } from "./lib";
import { getAppRouter } from "./routes";

import { LoadingOverlay } from "@repo/rdx-ui/components";
import { Suspense } from "react";
import "./app.css";

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
      },
    },
  });

  const axiosInstance = createAxiosInstance({
    baseURL: import.meta.env.VITE_API_SERVER_URL,
    getAccessToken: () => null, //getAccessToken,
    onAuthError: () => {
      //console.error("APP, Error de autenticación");
      //clearAccessToken();
      //window.location.href = "/login"; // o usar navegación programática
    },
  });

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

  return (
    <I18nextProvider i18n={i18n}>
      <QueryClientProvider client={queryClient}>
        <DataSourceProvider dataSource={dataSource}>
          <AuthProvider
            params={{
              getAccessToken,
              setAccessToken,
              clearAccessToken,
              authService: createAuthService(),
            }}
          >
            <TooltipProvider delayDuration={0}>
              {/* Fallback Route */}
              <Suspense fallback={<LoadingOverlay />}>
                <RouterProvider router={appRouter} />
              </Suspense>
            </TooltipProvider>
            <Toaster
              toastOptions={
                {
                  //unstyled: true,
                  /*classNames: {
                  error: "bg-red-400",
                  success: "text-green-400",
                  warning: "text-yellow-400",
                  info: "bg-blue-400",
                },*/
                }
              }
              position='bottom-center'
            />
            {import.meta.env.DEV && <ReactQueryDevtools initialIsOpen={false} />}
          </AuthProvider>
        </DataSourceProvider>
      </QueryClientProvider>
    </I18nextProvider>
  );
};
