export const resolveObjectPath = (obj, path) => {
  if (obj && path) {
    if (Array.isArray(path)) {
      return path.reduce(
        (acc, key) => ({
          ...acc,
          [key]: key.split('.').reduce((prev, curr) => prev?.[curr] ?? null, obj),
        }),
        {},
      );
    }
    return path.split('.').reduce((prev, curr) => prev?.[curr] ?? null, obj);
  }

  return null;
};

export const parseNumberWithRound = (number, fractionDigits = 10) => parseFloat(number.toFixed(fractionDigits));

export const getNextId = (rows) => {
  if (!rows?.length) return 1;
  const max = Math.max(...rows.map((row) => row.id));
  return max + 1;
};

export const downloadTableToCSV = ({ headers, cells, data, fileName }) => {
  if (headers?.length && cells?.length && data?.length) {
    let csvContent = 'data:text/csv;charset=utf-8,%EF%BB%BF';

    const title = headers
      .map(({ label, withGap }) => {
        if (withGap) {
          return `${label},`;
        }
        return label;
      })
      .join(',');

    const values = data
      .map((row) => {
        const textRow = cells
          .map(
            ({ key, prefix: prefixConfig, postfix: postfixConfig, needMultiply: needMultiplyConfig, withPercent }) => {
              const cell = resolveObjectPath(row, key);
              let needMultiply = needMultiplyConfig;
              let prefix = prefixConfig;
              let postfix = postfixConfig;

              if (key === 'pricing' && cell?.model === 'REV_SHARE') {
                prefix = '';
                postfix = '%';
                needMultiply = true;
              }

              if (cell === undefined || cell === null) {
                if (withPercent) {
                  return ',';
                }
                return '';
              }

              const cellValue = needMultiply ? (cell?.value ?? 0) * 100 : cell?.value;

              const value = cellValue?.toLocaleString(undefined, {
                minimumFractionDigits: prefix?.length || postfix?.length ? 2 : 0,
                maximumFractionDigits: 2,
              });

              if (withPercent) {
                const percent = cell?.change;
                const roundedPercent = percent ? Math.round(percent * 100) : 0;
                const percentFormatted = roundedPercent > 0 ? `+${roundedPercent}%` : `${roundedPercent}%`;

                return `${prefix ?? ''}${value.replace(/,/g, '') ?? ''}${postfix ?? ''},${percentFormatted}`;
              }

              return `${prefix ?? ''}${
                value ??
                cell?.toLocaleString(undefined, {
                  minimumFractionDigits: 0,
                  maximumFractionDigits: 2,
                })
              }${postfix ?? ''}`.replace(/,/g, '');
            },
          )
          .join(',');

        return textRow;
      })
      .join('\r\n');

    csvContent += encodeURIComponent(`${title}\r\n${values}`);

    const link = document.createElement('a');
    link.setAttribute('href', csvContent);
    link.setAttribute('download', fileName.replace(/\./g, '%2E'));
    link.style.visibility = 'hidden';
    document.body.appendChild(link);

    link.click();
    document.body.removeChild(link);
  }
};

export default resolveObjectPath;
