import { useTranslation as useReactTranslation } from 'react-i18next';
import { useLayoutEffect, useRef, useState } from 'react';
import { usePrevious } from '../use-previous';
function defaultT(key, params) {
  if (!params) {
    return key;
  }
  const count = typeof params.count === 'number' ? params.count : 0;
  const isDefaultNeeded = count !== 1 && params.plural;
  const translateString = isDefaultNeeded ? String(params.plural) : key;
  return translateString.replace(/\{\{(\w+)\}\}/g, (_match, match) => String(params[match] ?? `{{${match}}}`));
}

// todo replace with design system version
const translationKey = `design-system-${Date.now()}`;
const setDefaultValues = data => {
  return Object.keys(data).reduce((acc, current) => {
    acc[current] = data[current] || current;
    return acc;
  }, {});
};
const LANGUAGE_CODES = {
  ENGLISH: 'en',
  SPANISH_LA: 'es-419',
  FRENCH: 'fr',
  JAPANESE: 'ja',
  KOREAN: 'ko',
  PORTUGUESE_BRAZIL: 'pt-BR'
};
const loadLocales = {
  [LANGUAGE_CODES.SPANISH_LA]: () => import(`../../../locales/es-419/translation.json`),
  [LANGUAGE_CODES.FRENCH]: () => import(`../../../locales/fr/translation.json`),
  [LANGUAGE_CODES.JAPANESE]: () => import(`../../../locales/ja/translation.json`),
  [LANGUAGE_CODES.KOREAN]: () => import(`../../../locales/ko/translation.json`),
  [LANGUAGE_CODES.PORTUGUESE_BRAZIL]: () => import(`../../../locales/pt-BR/translation.json`)
};
let prevLanguage = null;
export function useTranslation() {
  const result = useReactTranslation(translationKey);
  const {
    language,
    hasResourceBundle,
    isInitialized
  } = result.i18n;
  const isLoaded = hasResourceBundle?.(language, translationKey);
  const [isFetched, setIsFetched] = useState(isLoaded);
  const isFirstLocaleLoaded = useRef(isLoaded);
  const isEnglish = language === LANGUAGE_CODES.ENGLISH;
  const prevLanguageRef = usePrevious(language);
  const t = (key, options = {}) => {
    const baseOptions = {
      fallbackLng: isEnglish ? LANGUAGE_CODES.ENGLISH : prevLanguage || language,
      defaultValue_other: options?.plural,
      ...options
    };
    return result.t(key, baseOptions);
  };
  useLayoutEffect(() => {
    prevLanguage = prevLanguageRef;
    if (!isLoaded && loadLocales[language]) {
      setIsFetched(false);
      loadLocales[language]().then(data => {
        const translations = setDefaultValues(data.default);
        result.i18n.addResourceBundle(language, translationKey, translations);
        setIsFetched(true);
        isFirstLocaleLoaded.current = true;
      });
    }
  }, [language]);
  return {
    ...result,
    isLocaleFetched: isFetched || isEnglish,
    isLoaded: isFirstLocaleLoaded.current || isEnglish,
    t: isInitialized ? t : defaultT
  };
}