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 { UnsavedWarnProvider } from "@/lib/hooks";
import { i18n } from "@/locales";

import { AuthProvider, createAuthService } from "@erp/auth/client";
import { DataSourceProvider, createAxiosDataSource, createAxiosInstance } from "@erp/core/client";

import "./app.css";
import { clearAccessToken, getAccessToken, setAccessToken } from "./lib";
import { AppRoutes } from "./routes";

export const App = () => {
  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_URL,
    getAccessToken,
    onAuthError: () => {
      clearAccessToken();
      window.location.href = "/login"; // o usar navegación programática
    },
  });

  console.log(axiosInstance.defaults.env);

  const dataSource = createAxiosDataSource(axiosInstance);

  return (
    <I18nextProvider i18n={i18n}>
      <QueryClientProvider client={queryClient}>
        <DataSourceProvider dataSource={dataSource}>
          <AuthProvider
            params={{
              getAccessToken,
              setAccessToken,
              clearAccessToken,
              authService: createAuthService(),
            }}
          >
            <TooltipProvider delayDuration={0}>
              <UnsavedWarnProvider>
                <AppRoutes />
              </UnsavedWarnProvider>
            </TooltipProvider>
            <Toaster />
            {import.meta.env.DEV && <ReactQueryDevtools initialIsOpen={false} />}
          </AuthProvider>
        </DataSourceProvider>
      </QueryClientProvider>
    </I18nextProvider>
  );
};
