import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import LanguageComponent from "./LanguageComponent";

const LanguageContainer = () => {
  const [anchorEl, setAnchorEl] = useState(null);

  const { i18n } = useTranslation();
  const [flagCode, setFlagCode] = useState("RO");

  useEffect(() => {
    if (!i18n.language) return;
    setFlagCode(i18n.language === "en" ? "GB" : i18n.language.toUpperCase());
  }, [i18n.language]);

  const handleMenuOpen = event => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleLanguageChange = language => () => {
    if (language !== i18n.language) {
      i18n.changeLanguage(language);
    }
    setAnchorEl(null);
  };

  return (
    <LanguageComponent
      languageIsSet={i18n.language ? true : false}
      anchorEl={anchorEl}
      onMenuOpen={handleMenuOpen}
      onLanguageChange={handleLanguageChange}
      onClose={handleClose}
      flagCode={flagCode}
    />
  );
};

export default LanguageContainer;
