import { createContext, FC, useContext, useMemo } from 'react'
import { EnrichedEntity } from '../../../src/types'
import { ReactNodeLike } from 'prop-types'
import { factories } from './prepare'
import { useLocale } from '../../../src/hooks/useLocale'
import de from '../../../res/translation-de.json'
import nl from '../../../res/translation-nl.json'
import { Dict } from '../../../src/types'

const factoryNames: Record<'de' | 'nl', Dict<string>> = {
  de,
  nl
}

interface Props {
  children: ReactNodeLike
}

interface FactoryContextType {
  factories: EnrichedEntity[]
  findFactory(uid: string): EnrichedEntity | undefined
}

const defaultValues: FactoryContextType = {
  factories: [],
  findFactory() {
    return undefined
  }
}

const FactoryContext = createContext<FactoryContextType>(defaultValues)
export const useFactories = () => useContext(FactoryContext)

export const FactoryProvider: FC<Props> = ({ children }) => {
  const locale = useLocale()
  const internationalizedFactories = useMemo(() => {
    if (locale !== 'en')
      factories.map(
        factory => (factory.name = factoryNames[locale]?.[factory.href] ?? factory.name)
      )
    return factories
  }, [locale])

  const findFactory = useMemo(() => {
    const detailsMap = Object.fromEntries(
      factories.map((detail: EnrichedEntity) => [detail.href, detail])
    )
    return (uid: string): EnrichedEntity | undefined => {
      return detailsMap[uid]
    }
  }, [])

  const value: FactoryContextType = useMemo(
    () => ({
      factories: internationalizedFactories,
      findFactory
    }),
    [findFactory, internationalizedFactories]
  )
  return <FactoryContext.Provider value={value}>{children}</FactoryContext.Provider>
}
