import dayjs from 'dayjs';

import { SUPPLY_TAG_PAGE } from '@/modules/marketplace/account/constants';

const HEADERS = ['ID', 'Time', 'User', 'Object', 'Supply ID', 'Demand ID', 'Action', 'Old value', 'New Value'];

const findSupplyId = (type, ids) => {
  if (type === SUPPLY_TAG_PAGE) {
    return ids?.length > 1 ? ids[1] : ids[0];
  }

  return ids[1] ?? 'N/A';
};

const findDemandId = (type, ids) => {
  if (type === SUPPLY_TAG_PAGE) {
    return ids?.length === 1 ? 'N/A' : ids[0];
  }

  return ids[0];
};

export const createHistoryCSV = ({ pageConfig, data, userTimezone }) => {
  let csvContent = 'data:text/csv;charset=utf-8,%EF%BB%BF';
  const fileName = pageConfig.breadcrumbs[pageConfig.breadcrumbs.length - 1]?.label ?? 'file';

  const title = HEADERS.join(',');

  const values = data?.length
    ? data
        .reduce((acc, cur) => {
          if (cur.values?.length) {
            cur.values.forEach((item) => {
              const time = dayjs(cur.created).tz(userTimezone).format('DD/MM/YYYY HH:mm');
              const object = pageConfig.type === SUPPLY_TAG_PAGE ? 'Supply Tag' : 'Demand Tag';
              const supplyId = findSupplyId(pageConfig.type, cur.ids);
              const demandId = findDemandId(pageConfig.type, cur.ids);

              if (item.changes?.length > 1) {
                item.changes.forEach((change) => {
                  const result = [
                    cur.id ?? '',
                    time,
                    cur.user?.email,
                    object,
                    supplyId,
                    demandId,
                    `${item.name}${item.actionWithName ? ` (${change.name})` : ''}`,
                    change.oldValue ?? '',
                    change.newValue ?? '',
                  ]
                    .map((value) => `"${value ? value.toString()?.replace(/"/g, "'") : ''}"`)
                    .join(',');

                  acc.push(result);
                });
                return;
              }
              const change = item.changes?.[0];
              const result = [
                cur.id,
                time,
                cur.user?.email,
                object,
                supplyId,
                demandId,
                `${item.name}${item.actionWithName ? ` (${change?.name ?? ''})` : ''}`,
                change?.oldValue ?? '',
                change?.newValue ?? '',
              ]
                .map((value) => `"${value ? value.toString()?.replace(/"/g, "'") : ''}"`)
                .join(',');

              acc.push(result);
            });
          }
          return acc;
        }, [])
        .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 createHistoryCSV;
