import { App as AntdApp, ConfigProvider } from "antd";
import { ScrollHandlerProvider } from "contexts/ScrollHandlerContext";
import { getDirection, LocalesMap } from "i18n/helper";
import { useEffect, useMemo } from "react";
import { RouterProvider, useLocation } from "react-router-dom";
import { useAppSelector } from "redux/hooks";
import { darkThemeConfig, themeConfig } from "ThemeConstants";
import "./App.css";
import router from "./routes/routes";

export function useQuery() {
  const { search } = useLocation();

  return useMemo(() => new URLSearchParams(search), [search]);
}

function App() {
  const { themeName } = useAppSelector((state) => state.theme);
  const { locale } = useAppSelector((state) => state.locale);

  // Set data-theme attribute on html element for CSS access
  useEffect(() => {
    document.documentElement.setAttribute("data-theme", themeName);
  }, [themeName]);

  // Select theme based on current theme state
  const currentTheme = themeName === "dark" ? darkThemeConfig : themeConfig;

  return (
    <ConfigProvider
      form={{
        validateMessages: {
          number: { min: "msg-validate-min", max: "msg-validate-max" },
        },
      }}
      theme={currentTheme}
      locale={LocalesMap.get(locale)}
      direction={getDirection(locale)}
      componentSize="large"
    >
      <ScrollHandlerProvider>
        <AntdApp>
          <div className={`${themeName}App`}>
            <RouterProvider router={router} />
          </div>
        </AntdApp>
      </ScrollHandlerProvider>
    </ConfigProvider>
  );
}

export default App;
