import { useEffect, useMemo } from "react";
import { ConfigProvider, theme, App as AntdApp } from "antd";
import zhCN from "antd/locale/zh_CN";
import enUS from "antd/locale/en_US";
import { useTranslation } from "react-i18next";
import AppRoutes from "./routes";
import { getOpenPlatformConfig } from "./api";
import { useThemeStore } from "./store/themeStore";

export default function App() {
  const { colorPrimary, themeMode, initTheme } = useThemeStore();
  const { i18n } = useTranslation();
  const antdLocale = useMemo(() => (i18n.language === "en-US" ? enUS : zhCN), [i18n.language]);
  const isTechTheme = themeMode === "tech";

  const antdTheme = useMemo(() => ({
    algorithm: theme.defaultAlgorithm,
    token: {
      colorPrimary,
      borderRadius: 4,
      colorBgLayout: isTechTheme ? "#edf6ff" : "#f5f6fa",
      colorBgContainer: isTechTheme ? "#ffffff" : "#ffffff",
      colorBgElevated: isTechTheme ? "#ffffff" : "#ffffff",
      colorBorder: isTechTheme ? "rgba(32, 111, 218, 0.18)" : "#e6e6e6",
      colorText: isTechTheme ? "#102033" : "#333333",
      colorTextSecondary: isTechTheme ? "#5f728f" : "#9095a1",
      colorFillSecondary: isTechTheme ? "rgba(32, 111, 218, 0.08)" : "rgba(0, 0, 0, 0.04)",
    },
    components: {
      Card: {
        borderRadiusLG: 4
      },
      Button: {
        borderRadius: 4
      },
      Input: {
        borderRadius: 4
      },
      Select: {
        borderRadius: 4
      },
      Modal: {
        borderRadiusLG: 4
      },
      Drawer: {
        colorBgElevated: "#ffffff"
      },
      Segmented: {
        itemSelectedBg: isTechTheme ? "#ffffff" : "#ffffff",
        itemSelectedColor: isTechTheme ? colorPrimary : "#333333"
      }
    }
  }), [colorPrimary, isTechTheme]);

  useEffect(() => {
    initTheme();
    const fetchConfig = async () => {
      try {
        const data = await getOpenPlatformConfig();
        if (data.projectName) {
          document.title = data.projectName;
        }
        if (data.iconUrl) {
          let link: HTMLLinkElement | null = document.querySelector("link[rel~='icon']");
          if (!link) {
            link = document.createElement('link');
            link.rel = 'icon';
            document.getElementsByTagName('head')[0].appendChild(link);
          }
          link.href = data.iconUrl;
        }
        // Save to sessionStorage for other components
        sessionStorage.setItem("platformConfig", JSON.stringify(data));
      } catch (e) {
        console.error("Failed to load platform config", e);
      }
    };
    fetchConfig();
  }, [initTheme]);

  return (
      <ConfigProvider
          locale={antdLocale}
          theme={antdTheme}
      >
        <AntdApp>
          <AppRoutes />
        </AntdApp>
      </ConfigProvider>
  );
}
