import * as SecureStore from 'expo-secure-store';
import { Platform } from 'react-native';
import React, { createContext, useContext, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';

type LanguageContextType = {
  currentLanguage: string;
  changeLanguage: (lang: string) => void;
};
// 保存语言设置
async function save(key: string, value: string) {
  if (Platform.OS === 'web') {
    localStorage.setItem(key, value);
  } else {
    await SecureStore.setItemAsync(key, value);
  }
}

// 获取语言设置
async function load(key: string): Promise<string | null> {
  if (Platform.OS === 'web') {
    return localStorage.getItem(key);
  } else {
    return await SecureStore.getItemAsync(key);
  }
}
const LanguageContext = createContext<LanguageContextType | undefined>(undefined);

export const LanguageProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { i18n } = useTranslation();
  const [currentLanguage, setCurrentLanguage] = useState(i18n.language || 'en');
  
  // 初始化时加载保存的语言设置
  useEffect(() => {
    const loadSavedLanguage = async () => {
      try {
        const savedLang = await load('i18nextLng');
        if (savedLang) {
          setCurrentLanguage(savedLang);
          i18n.changeLanguage(savedLang);
        }
      } catch (error) {
        console.error('Failed to load language setting:', error);
      }
    };
    
    loadSavedLanguage();
  }, [i18n]);

  const changeLanguage = (lang: string) => {
    i18n.changeLanguage(lang);
    // 保存语言设置
    save('i18nextLng', lang).catch(error => {
      console.error('Failed to save language setting:', error);
    });
  };

  useEffect(() => {
    const handleLanguageChanged = () => {
      const newLanguage = i18n.language;
      setCurrentLanguage(newLanguage);
      // 将更改后的语言保存到存储
      save('i18nextLng', newLanguage).catch(error => {
        console.error('Failed to save language setting:', error);
      });
    };

    i18n.on('languageChanged', handleLanguageChanged);

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

  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;
};
