import React from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Menu, MenuItem } from '@mui/material';
import { useLanguageSetting } from '@/hooks/setting-hooks';
import logger from '@/utils/logger';
import { changeChildLanguage } from '@/iframe/bridgeManager';
import { LanguageAbbreviation, LanguageAbbreviationMap } from '@/constants/common';

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 { changeLanguage } = useLanguageSetting();

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

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

  const handleLanguageChange = async (language: LanguageAbbreviation) => {
    try {
      await changeLanguage(language);
      i18n.changeLanguage(language);
      // 同步通知 iframe 子应用切换语言（如果存在）
      changeChildLanguage(language);
      handleClose();
    } catch (error) {
      logger.error('更新语言设置失败:', error);
    }
  };

  const supportedLangs: LanguageAbbreviation[] = [LanguageAbbreviation.Zh, LanguageAbbreviation.En];

  const getCurrentLanguageLabel = () => {
    const curLang = supportedLangs.includes(i18n.language as LanguageAbbreviation)
      ? (i18n.language as LanguageAbbreviation)
      : LanguageAbbreviation.En;
    return LanguageAbbreviationMap[curLang] || 'English';
  };

  return (
    <div>
      <Button
        onClick={handleClick}
        variant="outlined"
        sx={{
          color: textColor,
          borderColor: '#fff',
        }}
      >
        {getCurrentLanguageLabel()}
      </Button>
      <Menu anchorEl={anchorEl} open={open} onClose={handleClose}>
        {supportedLangs.map((lang) => (
          <MenuItem
            key={lang}
            onClick={() => handleLanguageChange(lang)}
            selected={i18n.language === lang}
          >
            {LanguageAbbreviationMap[lang]}
          </MenuItem>
        ))}
      </Menu>
    </div>
  );
};

export default LanguageSwitcher;