import { ApolloProvider } from "@apollo/client";
import * as Sentry from "@sentry/react";
import { SplitFactoryProvider, useSplitClient } from "@splitsoftware/splitio-react";
import { ConfigProvider } from "antd";
import enLocale from "antd/es/locale/en_US";
import { useEffect, useMemo } from "react";
import { CookiesProvider } from "react-cookie";
import { useTranslation } from "react-i18next";
import { connect, useSelector } from "react-redux";
import { createStructuredSelector } from "reselect";
import GlobalLoadingBar from "../components/global-loading-bar/global-loading-bar.component";
import { setDarkMode } from "../redux/application/application.actions";
import { selectDarkMode } from "../redux/application/application.selectors";
import { selectCurrentUser } from "../redux/user/user.selectors.js";
import client from "../utils/GraphQLClient";
import App from "./App";
import getTheme from "./themeProvider";

// Base Split configuration
const config = {
  core: {
    authorizationKey: import.meta.env.VITE_APP_SPLIT_API,
    key: "anon" // Default key, overridden dynamically by SplitClientProvider
  }
};

// Custom provider to manage the Split client key based on imexshopid from Redux
function SplitClientProvider({ children }) {
  const imexshopid = useSelector((state) => state.user.imexshopid); // Access imexshopid from Redux store
  const splitClient = useSplitClient({ key: imexshopid || "anon" }); // Use imexshopid or fallback to "anon"
  useEffect(() => {
    if (splitClient && imexshopid) {
      console.log(`Split client initialized with key: ${imexshopid}, isReady: ${splitClient.isReady}`);
    }
  }, [splitClient, imexshopid]);
  return children;
}

const mapDispatchToProps = (dispatch) => ({
  setDarkMode: (isDarkMode) => dispatch(setDarkMode(isDarkMode))
});

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser
});

function AppContainer({ currentUser, setDarkMode }) {
  const { t } = useTranslation();
  const isDarkMode = useSelector(selectDarkMode);
  const theme = useMemo(() => getTheme(isDarkMode), [isDarkMode]);

  // Update data-theme attribute when dark mode changes
  useEffect(() => {
    document.documentElement.setAttribute("data-theme", isDarkMode ? "dark" : "light");
    return () => document.documentElement.removeAttribute("data-theme");
  }, [isDarkMode]);

  // Sync Redux darkMode with localStorage on user change
  useEffect(() => {
    if (currentUser?.uid) {
      const savedMode = localStorage.getItem(`dark-mode-${currentUser.uid}`);
      if (savedMode !== null) {
        setDarkMode(JSON.parse(savedMode));
      } else {
        setDarkMode(false); // default to light mode
      }
    } else {
      setDarkMode(false);
    }
  }, [currentUser?.uid]);

  // Persist darkMode to localStorage when it or user changes
  useEffect(() => {
    if (currentUser?.uid) {
      localStorage.setItem(`dark-mode-${currentUser.uid}`, JSON.stringify(isDarkMode));
    }
  }, [isDarkMode, currentUser?.uid]);

  return (
    <CookiesProvider>
      <ApolloProvider client={client}>
        <ConfigProvider
          input={{ autoComplete: "new-password" }}
          locale={enLocale}
          theme={theme}
          form={{
            validateMessages: {
              required: t("general.validation.required", { label: "${label}" })
            }
          }}
        >
          <GlobalLoadingBar />
          <SplitFactoryProvider config={config}>
            <SplitClientProvider>
              <App />
            </SplitClientProvider>
          </SplitFactoryProvider>
        </ConfigProvider>
      </ApolloProvider>
    </CookiesProvider>
  );
}

export default Sentry.withProfiler(connect(mapStateToProps, mapDispatchToProps)(AppContainer));
