import { useMemo } from 'react'

import find from 'lodash/find'

import { useToggle } from 'hooks/useToggle'

import { useLexicsStore } from 'features/LexicsStore'

export const useLanguageSelect = () => {
  const {
    changeLang,
    lang,
    languageList,
  } = useLexicsStore()
  const {
    close,
    isOpen,
    open,
  } = useToggle()

  const handleLangChange = (locale: string) => () => {
    changeLang(locale)
    close()
  }

  const selectedLang = useMemo(() => find(languageList, { iso_639_1: lang }), [lang, languageList])

  return {
    close,
    handleLangChange,
    isOpen,
    open,
    selectedLang,
  }
}
