import React, { createContext, useState, useMemo } from 'react'
import zhCN from '@/locales/zh-CN'
import enUS from '@/locales/en-US'

const translations = {
  zhCN,
  enUS,
}

const YaLocalesContext = createContext({
  selectedLanguage: '',
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  setLanguage: (l: string) => {},
})

const YaLocalesContextProvider = (props: React.PropsWithChildren<any>) => {
  const { children, ...rest } = props
  const defaultLang = window.localStorage.getItem('ya_langs') ?? 'enUS'
  const [language, setLanguage] = useState<string>(defaultLang)
  const changeLanguage = useMemo(
    () => ({
      selectedLanguage: language,
      setLanguage: (l: string) => {
        setLanguage(l)
        window.localStorage.setItem('ya_langs', l)
      },
    }),
    [language],
  )
  return (
    <YaLocalesContext.Provider value={changeLanguage} {...rest}>
      {children}
    </YaLocalesContext.Provider>
  )
}

export function useLanguages() {
  return Object.keys(translations)
}

export function useChangeLang() {
  const { setLanguage } = React.useContext(YaLocalesContext)
  return React.useCallback(setLanguage, [setLanguage])
}

export function useSelectedLanguage() {
  return React.useContext(YaLocalesContext).selectedLanguage
}

export function useTranslate() {
  const language = useSelectedLanguage()
  return useMemo(
    () =>
      function translate(key: string) {
        const wordings = translations[language]
        return wordings[key]
      },
    [language],
  )
}

export default YaLocalesContextProvider
