import { toTitle } from '../../helpers';

export const isValidDataType = (data) => {
  const isValid = Array.isArray(data);
  if (!isValid) {
    // eslint-disable-next-line no-console
    console.error('data must be an array, received:', data);
  }

  return isValid;
};

export const isPlainObject = (value) => value?.constructor === Object;

const isXml = (str) => /^\s*<[\s\S]*>/.test(str);

const escapeXML = (s) => {
  const dom = document.createElement('div');
  dom.textContent = s;
  return dom.innerHTML;
};

export const getValueType = (value) => {
  if (isPlainObject(value)) return 'object';
  if (Array.isArray(value)) return 'array';
  if (isXml(value)) return 'xml';

  return 'text';
};

export const renderCodeSnippet = (value, lang) =>
  `<descope-code-snippet copy-button="true" lang="${lang}" class="row-details__value code">${escapeXML(value)}</descope-code-snippet>`;

export const renderText = (text) =>
  `<div class="row-details__value text" title="${text}">${escapeXML(text)}</div>`;
const renderJson = (value) => renderCodeSnippet(JSON.stringify(value, null, 2), 'json');
const renderXml = (value) => renderCodeSnippet(value, 'xml');

const defaultRowDetailsValueRenderer = (value) => {
  const valueType = getValueType(value);

  if (valueType === 'object') {
    return renderJson(value);
  }

  if (valueType === 'xml') {
    return renderXml(value);
  }

  if (valueType === 'array') {
    if (value.some((v) => getValueType(v) === 'object')) {
      return renderJson(value);
    }
    return renderText(value.join(',\n'));
  }

  return renderText(value);
};

const isCodeSnippetValue = (value) => {
  const type = getValueType(value);
  return (
    type === 'object' ||
    type === 'xml' ||
    (type === 'array' && value.some((v) => getValueType(v) === 'object'))
  );
};

export const defaultRowDetailsRenderer = (item, itemLabelsMapping) => `
  <div class="row-details">
  ${Object.entries(item)
    .map(([key, value]) => {
      const label = itemLabelsMapping[key] || toTitle(key);
      if (isCodeSnippetValue(value)) {
        return `<details class="row-details__item">
          <summary class="row-details__label">${label}</summary>
          ${defaultRowDetailsValueRenderer(value)}
        </details>`;
      }
      return `<div class="row-details__item">
          <div class="row-details__label">${label}</div>
          ${defaultRowDetailsValueRenderer(value)}
        </div>`;
    })
    .join('\n')}
</div>
  `;
