import React from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Menu, MenuItem } from '@mui/material';
import { LanguageAbbreviation } from '../locales';
import type { LanguageAbbreviationType } from '../locales';

interface LanguageSwitcherProps {
  textColor?: string;
}

const LanguageSwitcher: React.FC<LanguageSwitcherProps> = ({ textColor = '#fff' }) => {
  const { t, i18n } = useTranslation();
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);

  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    setAnchorEl(event.currentTarget);
  };

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

  const handleLanguageChange = (language: LanguageAbbreviationType) => {
    i18n.changeLanguage(language);
    handleClose();
  };

  const getCurrentLanguageLabel = () => {
    return i18n.language === LanguageAbbreviation.Zh ? '中文' : 'English';
  };

  return (
    <div>
      <Button
        onClick={handleClick}
        variant="outlined"
        sx={{
          color: textColor,
          borderColor: '#fff',
        }}
      >
        {getCurrentLanguageLabel()}
      </Button>
      <Menu
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
      >
        <MenuItem 
          onClick={() => handleLanguageChange(LanguageAbbreviation.Zh)}
          selected={i18n.language === LanguageAbbreviation.Zh}
        >
          中文
        </MenuItem>
        <MenuItem 
          onClick={() => handleLanguageChange(LanguageAbbreviation.En)}
          selected={i18n.language === LanguageAbbreviation.En}
        >
          English
        </MenuItem>
      </Menu>
    </div>
  );
};

export default LanguageSwitcher;