import React, { createContext, useState, useContext, useEffect } from 'react';
import { useTranslation } from 'react-i18next';

type LanguageContextType = {
  currentLanguage: string;
  changeLanguage: (lang: string) => void;
};

const LanguageContext = createContext<LanguageContextType | undefined>(undefined);

export const LanguageProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { i18n } = useTranslation();
  // 从localStorage获取保存的语言设置，如果没有则使用当前语言或默认为'en'
  const savedLanguage = localStorage.getItem('i18nextLng') || i18n.language || 'en';
  const [currentLanguage, setCurrentLanguage] = useState(savedLanguage);

  const changeLanguage = (lang: string) => {
    i18n.changeLanguage(lang);
    // 将语言设置保存到localStorage
    localStorage.setItem('i18nextLng', lang);
  };

  useEffect(() => {
    // 确保初始化时使用正确的语言
    if (savedLanguage && i18n.language !== savedLanguage) {
      i18n.changeLanguage(savedLanguage);
    }

    const handleLanguageChanged = () => {
      setCurrentLanguage(i18n.language);
      // 将更改后的语言保存到localStorage
      localStorage.setItem('i18nextLng', i18n.language);
    };

    i18n.on('languageChanged', handleLanguageChanged);

    return () => {
      i18n.off('languageChanged', handleLanguageChanged);
    };
  }, [i18n, savedLanguage]);

  return (
    <LanguageContext.Provider value={{ currentLanguage, changeLanguage }}>
      {children}
    </LanguageContext.Provider>
  );
};

export const useLanguage = (): LanguageContextType => {
  const context = useContext(LanguageContext);
  if (context === undefined) {
    throw new Error('useLanguage must be used within a LanguageProvider');
  }
  return context;
};
