import React, { useEffect, useMemo, useState } from "react";
import { createRoot } from "react-dom/client";
import { Badge, ChakraProvider, Spinner } from "@chakra-ui/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { KeycloakProvider } from "./keycloak.jsx";
import { PermissionProvider } from "./permission.jsx";
import { UpdateChecker } from "./UpdateChecker.jsx";
import { configureApi } from "./api.js";
import { queryClient } from "./query.js";
import { Fonts, theme as defaultTheme } from "./style.jsx";

const REMOTE_DEPS_KEY = "__UIKIT_REMOTE_DEPS__";
function setupBiRemoteUiDeps({ theme, chakraProviderProps } = {}) {
  if (typeof window === "undefined") return;

  const previousDeps = window[REMOTE_DEPS_KEY] || {};
  window[REMOTE_DEPS_KEY] = {
    ...previousDeps,
    React: previousDeps.React || React,
    createRoot: previousDeps.createRoot || createRoot,
    ChakraProvider: previousDeps.ChakraProvider || ChakraProvider,
    Badge: previousDeps.Badge || Badge,
    theme: theme ?? previousDeps.theme,
    chakraProviderProps: {
      ...(previousDeps.chakraProviderProps || {}),
      ...(chakraProviderProps || {}),
    },
  };
}

export function BiProvider({
  children,

  apiBaseUrl,

  keycloakClientId,
  permissionClientId,

  loading = <Spinner />,

  updateChecker = false,
  updateCheckerProps,

  keycloakUrl = "https://auth.ibagher.ir",
  keycloakRealm = "bi",
  permissionUrl = "https://api.d.aiengines.ir/user_api/v1/permissions/list",

  keycloakEnabled,
  permissionEnabled,

  theme = defaultTheme,
  remoteUiEnabled = true,
  remoteUiChakraProviderProps,
}) {
  const [mounted, setMounted] = useState(false);

  const shouldUseKeycloak = keycloakEnabled ?? Boolean(keycloakClientId);
  const shouldUsePermission = permissionEnabled ?? Boolean(permissionClientId);

  const config = useMemo(
    () => ({
      api: {
        baseUrl: apiBaseUrl || "",
      },

      keycloak: shouldUseKeycloak
        ? {
            url: keycloakUrl,
            realm: keycloakRealm,
            clientId: keycloakClientId,
          }
        : null,

      permission: shouldUsePermission
        ? {
            url: permissionUrl,
            clientId: permissionClientId,
          }
        : null,
    }),
    [
      apiBaseUrl,
      shouldUseKeycloak,
      shouldUsePermission,
      keycloakUrl,
      keycloakRealm,
      keycloakClientId,
      permissionUrl,
      permissionClientId,
    ],
  );

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (mounted) {
      configureApi(config);
    }
  }, [mounted, config]);

  if (!mounted) {
    return null;
  }

  if (remoteUiEnabled) {
    setupBiRemoteUiDeps({
      theme,
      chakraProviderProps: remoteUiChakraProviderProps,
    });
  }

  let content = children;

  if (shouldUsePermission) {
    content = (
      <PermissionProvider config={config.permission} loading={loading}>
        {content}
      </PermissionProvider>
    );
  }

  if (shouldUseKeycloak) {
    content = (
      <KeycloakProvider config={config.keycloak} loading={loading}>
        {content}
      </KeycloakProvider>
    );
  }

  return (
    <ChakraProvider theme={theme}>
      <Fonts />

      <QueryClientProvider client={queryClient}>
        {updateChecker && <UpdateChecker {...updateCheckerProps} />}

        {content}
      </QueryClientProvider>
    </ChakraProvider>
  );
}
