import { useEffect, useCallback } from 'react'

import isEmpty from 'lodash/isEmpty'

import { getLexics } from 'requests'

import {
  getLexicIds,
  mapTranslationsToLocalKeys,
  getSuffix,
  getShortSuffix,
} from 'features/LexicsStore/helpers'

import { useLang } from './useLang'
import { useLexicsConfig } from './useLexicsConfig'
import { useTranslations } from './useTranslations'

export const useLexics = (initialLanguage?: string) => {
  const {
    changeLang,
    lang,
    languageLexics,
    languageList,
  } = useLang(initialLanguage)
  const { addLexicsConfig, lexicsConfig } = useLexicsConfig()
  const { addTranslations, translate } = useTranslations()

  const fetchLexics = useCallback(
    async () => {
      const lexicIds = getLexicIds(lexicsConfig)
      if (isEmpty(lexicIds)) return

      const newTranslations = await getLexics(lang, lexicIds)
      addTranslations(mapTranslationsToLocalKeys(newTranslations, lexicsConfig))
    },
    [
      lang,
      lexicsConfig,
      addTranslations,
    ],
  )

  useEffect(() => {
    addLexicsConfig(languageLexics)
  }, [addLexicsConfig, languageLexics])

  useEffect(() => {
    fetchLexics()
  }, [
    lang,
    languageList,
    lexicsConfig,
    fetchLexics,
  ])

  return {
    addLexicsConfig,
    changeLang,
    lang,
    languageList,
    shortSuffix: getShortSuffix(lang),
    suffix: getSuffix(lang),
    translate,
  } as const
}
