/**
 * 语言切换组件
 */

import { useState } from 'react';
import { useI18n } from '../../hooks/useI18n';
import { Language } from '../../i18n';
import { i18nManager } from '../../i18n/manager';
import './index.css';

interface LanguageSwitcherProps {
  className?: string;
}

const LanguageSwitcher: React.FC<LanguageSwitcherProps> = ({ className = '' }) => {
  const { currentLanguage, changeLanguage, supportedLanguages, languageNames, t } = useI18n();
  const [switching, setSwitching] = useState(false);

  const handleLanguageSwitch = async () => {
    if (switching) return;

    try {
      setSwitching(true);

      // 显示语言选择菜单
      const languageOptions = supportedLanguages.map(lang => languageNames[lang]);
      const currentIndex = supportedLanguages.indexOf(currentLanguage);

      const result = await Taro.showActionSheet({
        itemList: languageOptions,
      });

      const selectedLanguage = supportedLanguages[result.tapIndex];

      if (selectedLanguage && selectedLanguage !== currentLanguage) {
        // 显示切换中的提示
        Taro.showLoading({
          title: t('common.loading'),
          mask: true,
        });

        // 切换语言
        await changeLanguage(selectedLanguage);

        // 更新应用级别的i18n设置
        await i18nManager.onLanguageChange();

        Taro.hideLoading();

        // 显示成功提示
        Taro.showToast({
          title: t('common.operationSuccess'),
          icon: 'success',
          duration: 1500,
        });
      }
    } catch (error: any) {
      Taro.hideLoading();

      // 用户取消选择不显示错误
      if (error.errMsg && error.errMsg.includes('cancel')) {
        return;
      }

      console.error('Language switch failed:', error);
      Taro.showToast({
        title: t('common.operationFailed'),
        icon: 'error',
        duration: 2000,
      });
    } finally {
      setSwitching(false);
    }
  };

  return (
    <View className={`language-switcher ${className}`} onClick={handleLanguageSwitch}>
      <View className="language-switcher-content">
        <Text className="language-icon">🌐</Text>
        <Text className="language-text">{languageNames[currentLanguage]}</Text>
        <Text className="language-arrow">▼</Text>
      </View>
    </View>
  );
};

export default LanguageSwitcher;
