import { useState } from 'react';
import { useRouter } from 'next/router';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import IconButton from '@mui/material/IconButton';
import TranslateIcon from '@mui/icons-material/Translate';
import { useTranslations } from 'next-intl';

// using https://next-intl-docs.vercel.app/docs/getting-started/pages-router
const LanguageSwitcher = () => {
    const t = useTranslations('common');
    const router = useRouter();
    const { locale, locales, asPath } = router;

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

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

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

    const changeLanguage = (lng) => {
        router.push(asPath, asPath, { locale: lng });
        handleClose();
    };

    return (
        <div>
            <IconButton onClick={handleClick} color="inherit">
                <TranslateIcon />
            </IconButton>
            <Menu
                id="language-menu"
                anchorEl={anchorEl}
                keepMounted
                open={Boolean(anchorEl)}
                onClose={handleClose}
            >
                {locales?.map((lng) => {
                    if (lng === locale) return null;
                    return (
                        <MenuItem key={lng} onClick={() => changeLanguage(lng)}>
                            {t('changeTo')} {t(lng.toUpperCase())}
                        </MenuItem>
                    );
                })}
            </Menu>
        </div>
    );
};

export default LanguageSwitcher;
