import { createContext, ReactNode, useContext } from 'react';

import labelTranslationEn from './translations/en';
import type { I18N } from './types';

const I18nContext = createContext<I18N | null>(null);

export type SupportedLanguages = 'en';

export { default as labelTranslationEn } from './translations/en';

export function I18nProvider({
  labelTranslations,
  children,
}: {
  language: SupportedLanguages;
  labelTranslations?: I18N;
  children: ReactNode;
}) {
  const translations = labelTranslations || labelTranslationEn;
  // const [translations, setTranslations] = useState<I18N>(labelTranslations || labelTranslationEn);

  // useEffect(() => {
  //   let unmounted = false;
  //   (async function load() {
  //     if (language !== 'en') {
  //       const resource = await import(`./translations/${language}.ts`);
  //       if (!unmounted) {
  //         setTranslations(resource.default);
  //       }
  //     }
  //   })();

  //   return () => {
  //     unmounted = true;
  //   };
  // }, [language, labelTranslations]);

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

export function replaceI18nVariablesInString(str: string, replaceWith: string) {
  return str.replace(/({{[^}]+}})/g, replaceWith);
}

export function useTr() {
  const context = useContext(I18nContext);

  return (key: keyof I18N, units?: number) => {
    const thereAreUnits = typeof units === 'number';
    const keyToUse = thereAreUnits && units > 1 ? `${key}_plural` : key;

    if (context && keyToUse in context) {
      // @ts-expect-error
      const tr: string = context[keyToUse];

      if (thereAreUnits) {
        return replaceI18nVariablesInString(tr, units.toString());
      }
      return tr;
    }

    return '';
  };
}
