import React from 'react';
import el from '@digigov/ui/i18n/locales/el';
export interface I18NContextProps {
  Trans?: any;
  t: (str: string, context?: any) => string;
  children?: React.ReactNode;
  i18n?: any;
}
export const defaultTranslate = (
  key: string,
  context?: Record<string, any>
): string => {
  if (typeof key !== 'string') {
    return key;
  }
  try {
    if (key.split('.').length > 0) {
      return key.split('.').reduce((locale, path) => {
        if (locale[path]) {
          if (typeof locale[path] === 'string' && context) {
            let nextLocale = locale[path];
            const matches = locale[path].match(/\{{(\w+)\}}/g) || [];
            matches.forEach((match: string) => {
              const variable = match.replace(/{|}/g, '');
              nextLocale = nextLocale.replace(match, context[variable]);
            });
            return nextLocale;
          }
          return locale[path];
        } else {
          return key;
        }
      }, el);
    } else if (el[key]) {
      return el[key];
    } else {
      return key;
    }
  } catch {
    console.error(`Translation key \`${key}\` not found`);
    return key;
  }
};
export const I18NContext = React.createContext<I18NContextProps>({
  t: defaultTranslate,
});

export const I18NProvider: React.FC<I18NContextProps> = ({
  t = defaultTranslate,
  children,
  ...props
}: I18NContextProps) => {
  return (
    <I18NContext.Provider
      value={{
        t: (...args) => {
          if (typeof args[0] !== 'string') {
            return args[0];
          }
          return t(...args);
        },
        ...props,
      }}
    >
      {children}
    </I18NContext.Provider>
  );
};

export const useTranslation = (): I18NContextProps => {
  return React.useContext(I18NContext);
};

export default I18NProvider;
