import { memo, ReactNode } from 'react';
import { isFunction } from 'lodash';

import { DEFAULT_LANG, DEFAULT_LOCASES_TEXTS } from './defaults';
import LocalizationContext from './LocalizationContext';
import { LocaleText } from './types';

export interface ILocalizationProvider {
	localeText?: Partial<LocaleText>;
	lang?: string;
	children: ReactNode;
}

const LocalizationProvider = ({ children, localeText, lang = DEFAULT_LANG }: ILocalizationProvider) => {
	const texts = { ...(DEFAULT_LOCASES_TEXTS[lang] ?? {}), ...(localeText ?? {}) };

	function translate(key: keyof LocaleText, params: any) {
		const text = texts[key];

		if (!text) {
			return key;
		}

		if (isFunction(text)) {
			return text(params);
		}

		return text;
	}

	return (
		<LocalizationContext.Provider value={{ translate: translate as any, lang }}>
			{children}
		</LocalizationContext.Provider>
	);
};

export default memo(LocalizationProvider);
