import React, { useState, useEffect, createContext } from 'react'
import AsyncStorage from '@react-native-async-storage/async-storage';
import { i18n } from '@/app/i18n/i18n';


export const LanguageContext = createContext({ userChangeLanguage: async (lang: string) => { } })

interface LanguageProviderProps {
  children: React.ReactNode;
}

const LanguageProviderComponent: React.FC<LanguageProviderProps> = ({ children }) => {
  const [_language, setLanguage] = useState('fr')

  // In the beginning of App, check if user has selected language before.
  // If not, use system default language
  useEffect(() => {
    i18n.localI18n.locale = 'fr'
    AsyncStorage.getItem('storedLanguage').then(data => {
      if (data === null) {
        i18n.localI18n.locale = 'fr'
      }
      else {
        i18n.localI18n.locale = data
        setLanguage(data)
      }
    }).catch((error) => console.log(error))
  }, [])


  const userChangeLanguage = async (language: string) => {
    i18n.localI18n.locale = language
    await AsyncStorage.setItem('storedLanguage', language)
    setLanguage(language)
  }

  return (
    <LanguageContext.Provider value={{ userChangeLanguage }}>
      {children}
    </LanguageContext.Provider>)
}

export const LanguageProvider = LanguageProviderComponent;
