import {
  useCallback,
  useEffect,
  useState,
} from 'react'

import filter from 'lodash/filter'
import isNull from 'lodash/isNull'
import map from 'lodash/map'

import { useLocalStore } from 'hooks'

import { client } from 'config/clients'

import { getLanguages, ReferenceLanguages } from 'requests/getLanguages'
import { getSortedLangs } from 'helpers/getSortedLangs'

const LANG_KEY = 'lang'
const DEFAULT_LANG = client.defaultLanguage || 'en'

export const useLang = (initialLanguage?: string) => {
  const [lang, setLang] = useLocalStore<string>({
    defaultValue: DEFAULT_LANG,
    initialValue: initialLanguage,
    key: LANG_KEY,
  })
  const [languageList, setLanguageList] = useState<ReferenceLanguages>([])
  const [languageLexics, setLanguageLexics] = useState<Array<number>>([])

  const fetchLanguages = useCallback(async () => {
    const languages = await getLanguages()
    const langsWithLexic = filter(languages, (language) => !isNull(language.lexic))
    const sortedLangs = getSortedLangs(langsWithLexic)
    setLanguageList(sortedLangs)
    setLanguageLexics(map(langsWithLexic, ({ lexic }) => lexic))
  }, [])

  useEffect(() => {
    fetchLanguages()
  }, [fetchLanguages])

  const changeLang = useCallback(
    (newLang: string) => {
      if (newLang === lang) return
      setLang(newLang)
    },
    [lang, setLang],
  )

  return {
    changeLang,
    lang,
    languageLexics,
    languageList,
  }
}
