import { useEffect, useState } from 'react';
import { useTranslation as useI18nTranslation } from 'react-i18next';
import { Language, SUPPORTED_LANGUAGES, Locale } from '../../i18n/types';
import { changeLanguage, getCurrentLanguage, getCurrentLocale, onLanguageChanged } from '../../i18n';

export const useTranslation = (ns?: string) => {
  const { t, i18n, ready } = useI18nTranslation(ns);
  const [currentLanguage, setCurrentLanguage] = useState<Language>(getCurrentLanguage());
  const [currentLocale, setCurrentLocale] = useState<Locale>(getCurrentLocale());

  // 监听语言变化
  useEffect(() => {
    const unsubscribe = onLanguageChanged((language: Language) => {
      setCurrentLanguage(language);
      setCurrentLocale(getCurrentLocale());
    });
    
    return unsubscribe;
  }, []);

  // 切换语言
  const switchLanguage = async (language: Language): Promise<boolean> => {
    const success = await changeLanguage(language);
    if (success) {
      setCurrentLanguage(language);
    }
    return success;
  };

  // 获取支持的语言列表
  const getSupportedLanguages = () => SUPPORTED_LANGUAGES;

  // 获取当前语言配置
  const getCurrentLanguageConfig = () => {
    return SUPPORTED_LANGUAGES.find(lang => lang.code === currentLanguage);
  };

  // 格式化带参数的文字
  const format = (key: string, params?: Record<string, any>) => {
    return t(key, params);
  };

  // 检查是否支持某种语言
  const isLanguageSupported = (language: Language) => {
    return SUPPORTED_LANGUAGES.some(lang => lang.code === language);
  };

  // 重置为设备语言
  const resetToDeviceLanguage = async (): Promise<boolean> => {
    const deviceLocale = getCurrentLocale();
    const deviceLanguage = deviceLocale.languageCode as Language;
    
    if (isLanguageSupported(deviceLanguage)) {
      return await switchLanguage(deviceLanguage);
    }
    return await switchLanguage('zh-TW');
  };

  return {
    t,
    i18n,
    ready,
    currentLanguage,
    currentLocale,
    switchLanguage,
    getSupportedLanguages,
    getCurrentLanguageConfig,
    format,
    isLanguageSupported,
    resetToDeviceLanguage,
  };
};

// 简化的 Hook，用于基本翻译需求
export const useSimpleTranslation = () => {
  const { t } = useI18nTranslation();
  return { t };
};