/* eslint-disable array-callback-return */
/* eslint-disable no-nested-ternary */
import React from 'react';
import { prettyTracker, translate } from 'gatsby-core-theme/src/helpers/getters';
import Tooltip from '../components/atoms/tooltip';

export function getObjectValue(obj, path) {
  if (!obj) return null;
  if (!path) return obj;

  const properties = path.split('.');
  const objKey = properties.shift();

  if (obj[objKey] === undefined) return null;
  return getObjectValue(obj[objKey], properties.join('.'));
}

export const getKeyValues = (relation, data, market) => {
  const obj = Object.keys(data).reduce((acc, key) => {
    const dataKey = data[key][0];

    if (dataKey.includes('||')) {
      // if it has || operator AND market
      if (dataKey.includes('[market]')) {
        const path = dataKey.replace('[market]', `.${market}`);
        acc[key] =
          getObjectValue(relation, path.split(' || ')[0]) ||
          getObjectValue(relation, path.split(' || ')[1]);
      } else {
        acc[key] =
          getObjectValue(relation, dataKey.split(' || ')[0]) ||
          getObjectValue(relation, dataKey.split(' || ')[1]);
      }
    } else if (dataKey.includes('[market]')) {
      // contains market data
      acc[key] = getObjectValue(relation, dataKey.replace('[market]', `.${market}`));
    } else {
      acc[key] = getObjectValue(relation, dataKey);
    }
    return acc;
  }, {});

  return obj;
};

export const generateLabel = (key, value, fnc, props) => {
  if (fnc) {
    return fnc(value, props);
  }

  if (typeof value === 'string') {
    return value;
  }

  if (Array.isArray(value)) {
    return value?.reduce((acc, current, index) => {
      const prefix = index === 0 ? ' ' : ', ';
      return acc + prefix + current.name;
    }, '');
  }

  return value;
};

export const getInfoGridColumnValues = (relation, data, market) => {
  let items = {};
  Object.entries(data).map(([key, item]) => {
    items = {
      ...items,
      [key]: getKeyValues(relation, item, market),
    };
  });

  return items;
};

export const formatGameDate = (value) => {
  const arr = value?.split('-');
  return arr?.reduce((acc, current, index) => {
    const prefix = index === 0 ? '' : '.';
    return acc.replace(/^/, current + prefix);
  }, '');
};
export const generateVolatility = (value, props) => {
  const translations = props?.translations || null;
  if (value === null) return translate(translations, 'low', 'Low');
  return value === 0
    ? translate(translations, 'low', 'Low')
    : value === 1
    ? translate(translations, 'medium', 'Medium')
    : translate(translations, 'high', 'High');
};
export const formatDate = (value) => value?.slice(0, 4);
export const generateYesorNo = (value, props) => {
  const translations = props?.translations || null;
  return value ? translate(translations, 'yes', 'Yes') : translate(translations, 'no', 'No');
};
export const generateRtp = (value) => (value ? `${value}%` : null);
export const latestItems = (items, props, limit = null) => {
  if (items === null) return null;
  const translations = props?.translations || null;
  const showMore = props?.showMore || false;
  const customValue = props?.customValue || null;
  const showTooltip = props?.tooltip || false;
  const showAll = props?.showAll || false;
  const setShowMore = props?.setShowMore || null;

  const list = [];
  const tooltipList = [];
  const { length } = Object.values(items);
  const hasCustomValue = customValue;

  if (showAll) {
    limit = Object.values(items).length;
  }

  // show initial values
  Object.values(items)
    ?.slice(0, limit || Object.values(items).length)
    ?.map((res) => {
      list.push(res.name);
    });
  // show see more values
  Object.values(items)
    ?.slice(limit)
    ?.map((res) => {
      tooltipList.push(res.name);
    });

  const itemsString = list.toString().replace(/,/gi, ', ');

  return showMore && length > limit ? (
    <>
      {itemsString}
      {` `}
      {showTooltip ? (
        <Tooltip
          content={tooltipList.toString().replace(/,/gi, ', ')}
          direction="bottom"
          minWidth={20}
        >
          {` ${
            hasCustomValue
              ? translate(translations, customValue.translationKey, customValue.label)
              : ` ${length - limit} ${translate(translations, 'more', 'more')}`
          }`}
        </Tooltip>
      ) : (
        <button type="button" onClick={() => setShowMore(true)}>
          {hasCustomValue
            ? translate(translations, customValue.translationKey, customValue.label)
            : `${length - limit} ${translate(translations, 'more', 'more')}`}
        </button>
      )}
    </>
  ) : (
    itemsString
  );
};
export const generateLicenseAndSupportTypes = (value, props, limit) => {
  if (value === null) return null;
  const arr = value?.split(',');
  return arr?.slice(0, limit).reduce((acc, current, index) => {
    if (!current) {
      return '';
    }

    const prefix = index === 0 ? ' ' : ',';
    return acc + prefix + current;
  }, '');
};
export const isLiveCasino = (value, props) => {
  const translations = props?.translations || null;
  if (value === null) return translate(translations, 'no', 'No');

  return generateYesorNo(
    Object.values(value)?.find((name) => name === 'livecasino'),
    translations
  );
};
export const getCurrencies = (value) => {
  if (value === null) return null;

  return Object.values(value)
    ?.slice(0, 5)
    ?.map((elm) => elm?.iso_code);
};
export const generateLink = (value, props, addRel = false) => {
  if (value === null) return null;

  const template = props?.template || null;
  let link;
  let text;

  if (/\b[a-z0-9-_.]+@[a-z0-9-_.]+/i.test(value)) {
    link = `mailto:${value}`;
    text = value;
  } else {
    link = prettyTracker(value, 'main', false, template);
    text = value.url;
  }

  const attributes = { href: link };

  if (addRel) {
    attributes.rel = 'nofollow sponsored';
  }

  return React.createElement('a', attributes, text);
};
export const getMaxWin = (value) => (value ? `${value}x innsatsen` : null);
export const getMaxStake = (value) => (value ? `${value} kroner` : null);
export const removeEmojis = (text) => text?.replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '');
export const getExperience = (value, props) => {
  if (value === null) return null;

  const text = props?.text || '';
  const translations = props?.translations || null;

  return (
    <>
      {value.match(/\d+/)}
      <small>{translate(translations, 'years', text)}</small>
    </>
  );
};
