import dayjs from 'dayjs';

export const parseHistogram = (histogram, timezone, customKey, allowableFields) =>
  histogram?.buckets?.map((bucket) => {
    const keyWithPercent = [
      'REQUESTS_FILL',
      'SUPPLY_REQUESTS_FILL',
      'OVERALL_FILL',
      'OPPORTUNITIES_FILL',
      'MEDIA_MARGIN',
      'REQUESTS_VIEWABILITY',
      'SUPPLY_REQUESTS_VIEWABILITY',
      'IMPRESSIONS_VIEWABILITY',
      'MEDIA_MARGIN_PERCENT',
    ];

    const fields = Object.keys(bucket.fields).reduce((acc, key) => {
      if (allowableFields?.length && !allowableFields.includes(key)) {
        return acc;
      }

      if (bucket.fields[key]) {
        return {
          ...acc,
          [customKey || key]: keyWithPercent.includes(key)
            ? Math.round(bucket.fields[key].value * 10000) / 100
            : bucket.fields[key].value,
        };
      }

      return acc;
    }, {});

    // Remove the data of the next hours for today comparison graphs
    if (customKey === 'today' && bucket.time > dayjs().valueOf()) {
      return {
        name: dayjs(bucket.time).tz(timezone).format('DD/MM/YYYY HH:mm|HH:mm|DD/MM'),
        time: bucket.time,
        ...fields,
        today: null,
      };
    }

    return {
      name: dayjs(bucket.time).tz(timezone).format('DD/MM/YYYY HH:mm|HH:mm|DD/MM'),
      ...fields,
      time: bucket.time,
    };
  }) ?? [];

export const parseComparisonHistograms = ({ histograms, timezone, allowableFields }) => {
  const config = {
    0: 'today',
    1: 'yesterday',
    2: 'week',
  };

  if (!histograms?.length) {
    return [];
  }

  return histograms
    .map((histogram, index) => parseHistogram(histogram, timezone, config[index], allowableFields))
    .reduce((a, b) =>
      a.map((item, i) => {
        const { name, ...rest } = b[i];
        return {
          ...item,
          ...rest,
        };
      }),
    );
};

export const tooltipValueFormatter = (name, value) => {
  const withPercent = [
    'REQUESTS_FILL',
    'OVERALL_FILL',
    'OPPORTUNITIES_FILL',
    'SUPPLY_REQUESTS_FILL',
    'MEDIA_MARGIN_PERCENT',
  ];
  const withDollar = ['REVENUE', 'GROSS_REVENUE', 'MEDIA_COST', 'RPM', 'CPM', 'ERPM', 'PLAYER_ERPM', 'PUB_PLAYER_ERPM'];

  if (withPercent.includes(name)) {
    return `${value.toLocaleString(undefined, {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    })}%`;
  }
  if (withDollar.includes(name)) {
    return `$${value.toLocaleString(undefined, {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    })}`;
  }

  return value.toLocaleString(undefined, {
    minimumFractionDigits: 0,
    maximumFractionDigits: 2,
  });
};
