import { useCallback } from 'react'

import { useLocalStore } from 'hooks'

import type { Languages } from 'config/languages'
import { client } from 'config/clients'

import { isSupportedLang } from 'helpers/isSupportedLang'

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

export const useLang = (initialLanguage?: Languages) => {
  const [lang, setLang] = useLocalStore<Languages>({
    defaultValue: DEFAULT_LANG,
    initialValue: initialLanguage,
    key: LANG_KEY,
    validator: isSupportedLang,
  })

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

  return { changeLang, lang }
}
