import { PDF_EXPORT_HIDE_CONTENT, PDF_EXPORT_HIDE_SCROLL } from '@/modules/analytics/common/constants';

export const html2pdf = async (fileName, DOMNode) => {
  const cache = [];

  DOMNode.querySelectorAll('[data-pdf-export]').forEach((node) => {
    const exportAttr = node.getAttribute('data-pdf-export');

    if (exportAttr === PDF_EXPORT_HIDE_SCROLL) {
      cache.push({
        node,
        style: {
          overflow: node.style.overflow ?? '',
        },
      });

      // eslint-disable-next-line no-param-reassign
      node.style.overflow = 'hidden';
    }

    if (exportAttr === PDF_EXPORT_HIDE_CONTENT) {
      cache.push({
        node,
        style: {
          opacity: node.style.opacity ?? '',
          visibility: node.style.visibility ?? '',
        },
      });
      // eslint-disable-next-line no-param-reassign
      node.style.opacity = '0';
      // eslint-disable-next-line no-param-reassign
      node.style.visibility = 'hidden';
    }
  });

  const { jsPDF: JsPDF } = await import('jspdf');

  const { toJpeg } = await import('html-to-image');
  const dataUrl = await toJpeg(DOMNode);

  cache.forEach((item) => {
    Object.entries(item.style).forEach(([key, value]) => {
      // eslint-disable-next-line no-param-reassign
      item.node.style[key] = value;
    });
  });

  const img = new Image();
  img.src = dataUrl;

  await new Promise((resolve) => {
    img.onload = resolve;
  });

  const pdf = new JsPDF({
    orientation: 'landscape',
  });
  const imgProps = pdf.getImageProperties(img);
  const pdfWidth = pdf.internal.pageSize.getWidth();
  const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;

  pdf.addImage(img, 'JPEG', 0, 0, pdfWidth, pdfHeight);
  pdf.save(`${fileName}.pdf`);

  return dataUrl;
};
