import { useState, useCallback } from 'react'

import type { Translations } from 'requests'

import type { LexicsId, Values } from '../types'

const replaceValues = (translation: string, values: Values) => (
  translation.replace(/{\w+}/g, (regKey) => {
    const key = regKey.slice(1, -1)
    return values[key] ? String(values[key]) : regKey
  })
)

export const useTranslations = () => {
  const [translations, setTranslations] = useState<Translations>({})

  const translate = useCallback(
    (lexicId: LexicsId, values?: Values) => {
      const translation = translations[lexicId]
      if (translation && values) return replaceValues(translation.text, values)
      return translation?.text || ''
    },
    [translations],
  )

  const addTranslations = useCallback(
    (newTranslations: Translations) => {
      setTranslations((state) => ({ ...state, ...newTranslations }))
    },
    [],
  )

  return { addTranslations, translate }
}
