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 { clearAccessToken, getAccessToken } from "@erp/auth/client";
import { DataSourceProvider, createAxiosDataSource, createAxiosInstance } from "@erp/core/client";
import { AppRoutes } from "./app-routes";
import "./app.css";

/**
 * Clave utilizada en el almacenamiento local para el token JWT.
 */
const TOKEN_STORAGE_KEY = "factuges.auth";

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 dataSource = createAxiosDataSource(createAxiosInstance({
    baseURL: import.meta.env.VITE_API_URL,
    getAccessToken: () => getAccessToken(TOKEN_STORAGE_KEY),
    onAuthError: () => {
      clearAccessToken(TOKEN_STORAGE_KEY);
      window.location.href = "/login"; // o usar navegación programática
    },
  }););

  return (
    <I18nextProvider i18n={i18n}>
      <QueryClientProvider client={queryClient}>
        <DataSourceProvider dataSource={dataSource}>
          <TooltipProvider delayDuration={0}>
            <UnsavedWarnProvider>
              <AppRoutes />
            </UnsavedWarnProvider>
          </TooltipProvider>
          <Toaster />
          {import.meta.env.DEV && <ReactQueryDevtools initialIsOpen={false} />}
        </DataSourceProvider>
      </QueryClientProvider>
    </I18nextProvider>
  );
};
