import { PropsWithChildren, createContext, useContext, useMemo } from 'react';

import { I18n } from './types';

/** Value of {@link TranslationContext} */
export interface TranslationContextValue {
  /** Current i18n engine that should be used in UI Kit */
  i18n: I18n;
}

/** Context that provide i18n engine that should be used in UI Kit */
const TranslationContext = createContext<TranslationContextValue | undefined>(undefined);

/** Provider that inject i18n engine that should be used in UI Kit */
export function TranslationContextProvider({ i18n, children }: PropsWithChildren<TranslationContextValue>) {
  const value: TranslationContextValue = useMemo(() => ({ i18n }), [i18n]);

  return <TranslationContext.Provider value={value}>{children}</TranslationContext.Provider>;
}

/** Return data for i18n engine that should be used in UI Kit */
export function useTranslationContext(): TranslationContextValue {
  const value = useContext(TranslationContext);
  if (!value) {
    throw new Error('useTranslationContext should be used only inside TranslationContextProvider');
  }

  return value;
}
