import { GlobalOutlined } from "@ant-design/icons";
import { setLocale, setLocalesThunk } from "features/locale/localeSlice";
import i18n from "i18n/i18n";
import { useTransition } from "react";
import { useDispatch } from "react-redux";
import { useAppSelector } from "redux/hooks";
import ProText from "../ProText";
import styles from "./LanguageSwitch.module.css";
import RefershIcon from "components/Icons/RefershIcon";

export function LanguageSwitch() {
  const dispatch = useDispatch();
  const { themeName } = useAppSelector((state) => state.theme);
  const [isPending, startTransition] = useTransition();
  const { isRTL } = useAppSelector((state) => state.locale);

  const changeLanguage = () => {
    startTransition(() => {
      const key: string = isRTL ? "en" : "ar";
      dispatch(setLocale(key));
      // @ts-ignore
      dispatch(setLocalesThunk(key));
      i18n.changeLanguage(key);
    });
  };

  const refreshPage = () => {
    window.location.reload();
  };

  return (
    <div className={styles.languageSwitch}>
      <GlobalOutlined
        style={{
          color: themeName === "dark" ? "#fff" : "#333333",
          fontSize: 15,
          marginRight: 3,
          cursor: isPending ? "wait" : "pointer",
          opacity: isPending ? 0.7 : 1,
        }}
        onClick={changeLanguage}
      />
      <ProText
        style={{
          color: themeName === "dark" ? "#fff" : "#333333",
          fontSize: 14,
          marginRight: 3,
          opacity: isPending ? 0.7 : 1,
          [isRTL ? "marginLeft" : "marginRight"]: 3,
        }}
        onClick={changeLanguage}
      >
        {isPending ? "..." : isRTL ? "English" : "Arabic"}
      </ProText>
      <div onClick={refreshPage}>
        <RefershIcon dimension={18} className={styles.refreshIcon} />
      </div>
    </div>
  );
}
