import React from 'react';
import { defaultTranslate, useTranslation } from '@digigov/ui/i18n';

const isObject = (value) => {
  return !!(value && typeof value === 'object' && !Array.isArray(value));
};

const resultTranslate = (translation, children) => {
  if (typeof DOMParser !== 'undefined') {
    const parser = new DOMParser();
    const childrenCloned = [...children];
    const doc1 = parser.parseFromString(
      `<div>${translation
        .replace(/<([0-9])>/g, '<t$1>')
        .replace(/<\/([0-9])>/g, '</t$1>')}</div>`,
      'application/xml'
    );

    return recursiveReplace(childrenCloned, doc1.children[0].childNodes);
  }
};

const recursiveReplace = (original: any, translation: any) => {
  if (!Array.isArray(original)) {
    original = [original];
  }
  original.forEach((element, i) => {
    if (typeof element === 'string' || typeof element === 'number') {
      const text: any = [];
      const regex = /{([^}]+)}/;
      if (regex.test(translation[i].textContent)) {
        const textArray = translation[i].textContent.split(' ');
        if (textArray.length === 1) {
          return false;
        } else {
          textArray.forEach((txt) => {
            if (!regex.test(txt)) {
              text.push(txt);
            } else {
              text.push(original[i]);
            }
          });
          return (original[i] = text.join(' '));
        }
      } else {
        return (original[i] = translation[i].textContent);
      }
    }
    if (isObject(element)) {
      original[i] = React.cloneElement(original[i], {
        ...original[i].props,
        key: i,
        children: recursiveReplace(
          original[i].props.children,
          translation[i].childNodes
        ),
      });
    }
  });
  return original;
};

export interface I18nTextProps {
  children?: React.ReactNode;
  i18nKey?: string;
}

export const I18nText = ({ i18nKey, children }) => {
  const translation = defaultTranslate(i18nKey);
  const result = resultTranslate(translation, children);
  const { Trans } = useTranslation();
  if (Trans) {
    return <Trans i18nKey={i18nKey}>{children}</Trans>;
  }

  return <>{result}</>;
};

export default I18nText;
