/** @format */
import React, { useEffect, useState } from 'react';
import { TranslationsProvider, useTranslator } from '@eo-locale/react';
const LanguageController = ({ children }) => {
	const [languageState, setLanguageState] = useState(null);
	const [messagesState, setMessagesState] = useState({});
	useEffect(() => {
		setLanguage('ru');
	}, []);

	const locales = () => {
		return Object.entries(messagesState).map(
			([language, messages]) => ({ language, messages }),
			[],
		);
	};

	const getMessage = (key, options) => {
		// let resLang = this.messages[this.language][key] || key;
		let resLang = message[languageState][key] || key;

		if (options && Object.keys(options).length) {
			for (const lk of Object.keys(options)) {
				resLang = resLang.replaceAll(`{${lk}}`, options[lk]);
			}
		}
		return resLang;
	};

	const setLanguage = (lang) => {
		// this.language = lang;
		setLanguageState(lang);
		if (messagesState[lang]) {
			return;
		}
		return getMessages(lang).then((messages) => {
			// this.messages[lang] = messages;
			setMessagesState({ ...messagesState, [lang]: messages });
		});
	};

	const getMessages = (lang) => {
		switch (lang) {
			case 'ru':
				return import('../static/locale/ru.json');
			// case 'en':
			// 	return import('../static/locale/en.json');
			// case 'uz':
			// 	return import('../static/locale/uz.json');
			default:
				throw new Error('Language not supported');
		}
	};

	const onLangError = (e) => {
		console.debug(e.message);
	};

	return (
		<TranslationsProvider
			language={languageState}
			locales={locales()}
			onError={onLangError}>
			{children}
		</TranslationsProvider>
	);
};

export default LanguageController;
