import * as React from 'react';
import Paper from '@mui/material/Paper';
import MenuList from '@mui/material/MenuList';
import MenuItem from '@mui/material/MenuItem';
import ListItemText from '@mui/material/ListItemText';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemButton from '@mui/material/ListItemButton';
import { LANGUAGES } from '../locales'
import { Icon } from "@iconify/react";
import { useTranslation } from 'react-i18next';
import Menu from '@mui/material/Menu';


export default function LanguageMenu( {closeAction} ) {
  const { t, i18n } = useTranslation();

  const handleLanguageChange = (lang: any) => {
    try {
      i18n.changeLanguage(lang.code);
    } catch (error) {
      console.error(`Error changing language to ${lang.code}:`, error);
    }
  };

  const [anchorElUser, setAnchorElUser] = React.useState<null | HTMLElement>(null);
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const [selectedIndex, setSelectedIndex] = React.useState(1);
  const open = Boolean(anchorEl);
  const handleClickListItem = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };


  const handleLanguageSelect = (
    event: React.MouseEvent<HTMLElement>,
    index: number,
  ) => {
    setSelectedIndex(index);
    handleLanguageChange(LANGUAGES[index]);
    closeAction;
    setAnchorEl(null);
    setAnchorElUser(null);
  };


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


  return (
    <Paper sx={{ minWidth: 320, maxWidth: '100%' }}>
      <ListItemButton
        id="language-button"
        aria-haspopup="listbox"
        aria-controls="language-menu"
        aria-label="Language"
        aria-expanded={open ? 'true' : undefined}
        onClick={handleClickListItem}
      >
        <ListItemText
          primary={t ('language')}
          secondary={i18n.resolvedLanguage}
        />
      </ListItemButton>
      <Menu
        id="language-menu"
	anchorEl={anchorEl}
	open={open}
	onClose={handleClose}
	slotProps={{
          list: {
            'aria-labelledby': 'language-button',
            role: 'listbox',
	  },
	}}
	>
        {LANGUAGES.map((lang, index) =>
	  <MenuItem key={index} onClick={() => handleLanguageSelect(event, index)}>
	    <ListItemIcon>
	      <Icon icon={"circle-flags:" + lang.code} />
	    </ListItemIcon>
	    <ListItemText>{lang.label}</ListItemText>
	  </MenuItem>
        )}
      </Menu>
    </Paper>
  )
}
