import type { ReactNode } from 'react'
import {
  createContext,
  useContext,
  useEffect,
} from 'react'

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

import { useLexics } from './hooks'

import { getLexicFromSport } from './helpers'

type Context = ReturnType<typeof useLexics>
type Props = {
  children: ReactNode,
  initialLanguage?: string,
}

const LexicsContext = createContext({} as Context)

export const LexicsStore = ({ children, initialLanguage }: Props) => {
  const lexics = useLexics(initialLanguage)
  return <LexicsContext.Provider value={lexics}>{children}</LexicsContext.Provider>
}

export const useLexicsStore = () => useContext(LexicsContext)

export const useLexicsConfig = (config: Array<LexicsId> | LexicsConfig) => {
  const { addLexicsConfig } = useLexicsStore()

  useEffect(() => {
    addLexicsConfig(config)
    addLexicsConfig(getLexicFromSport())
  }, [addLexicsConfig, config])
}
