import * as React from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ConfigContext } from "./ConfigContext";
import { getAppConfig } from "../config";
import { initializeApiClients } from "../api/client";
import { AppConfig } from "../types/config";
import { Box, CircularProgress } from "@mui/material";

const defaultQueryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000,
      retry: 1,
      refetchOnWindowFocus: false,
    },
  },
});

interface AppProviderProps {
  children: React.ReactNode;
  resourceOverrides?: Record<string, any>;
  profileConfig?: any;
  queryClient?: QueryClient;
}

export function AppProvider({
  children,
  resourceOverrides = {},
  profileConfig = {},
  queryClient = defaultQueryClient,
}: AppProviderProps) {
  const [config, setConfig] = React.useState<AppConfig | null>(null);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    getAppConfig(resourceOverrides, profileConfig)
      .then((cfg) => {
        initializeApiClients(cfg.baseUrl, cfg.authBaseUrl);
        setConfig(cfg);
        setLoading(false);
      })
      .catch((err) => {
        console.error("Failed to load OpenAPI configuration:", err);
        setLoading(false);
      });
  }, [resourceOverrides, profileConfig]);

  if (loading) {
    return (
      <Box
        sx={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "100vh",
        }}
      >
        <CircularProgress />
      </Box>
    );
  }

  return (
    <QueryClientProvider client={queryClient}>
      <ConfigContext.Provider value={config}>
        {children}
      </ConfigContext.Provider>
    </QueryClientProvider>
  );
}
