import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';

function downloadBlob(blob, filename) {
  const url = window.URL.createObjectURL(blob);
  const anchor = document.createElement('a');
  anchor.href = url;
  anchor.download = filename;
  anchor.style.display = 'none';
  document.body.appendChild(anchor);
  anchor.click();
  document.body.removeChild(anchor);
  window.URL.revokeObjectURL(url);
}

function escapeCsvCell(value) {
  return `"${String(value ?? '').replace(/"/g, '""').replace(/\r?\n/g, ' ')}"`;
}

export function downloadCsvReport(filename, sections = []) {
  const lines = [];

  sections.forEach((section, sectionIndex) => {
    if (sectionIndex > 0) {
      lines.push('');
    }
    if (section.title) {
      lines.push(escapeCsvCell(section.title));
    }
    if (Array.isArray(section.headers) && section.headers.length > 0) {
      lines.push(section.headers.map((header) => escapeCsvCell(header)).join(','));
    }
    (Array.isArray(section.rows) ? section.rows : []).forEach((row) => {
      lines.push(row.map((value) => escapeCsvCell(value)).join(','));
    });
  });

  const blob = new Blob([`${lines.join('\n')}\n`], { type: 'text/csv;charset=utf-8;' });
  downloadBlob(blob, filename);
}

export function exportReportPdf({
  filename,
  title,
  subtitle = '',
  sections = [],
}) {
  const doc = new jsPDF({ unit: 'pt', format: 'a4' });
  const pageWidth = doc.internal.pageSize.getWidth();
  const marginX = 40;
  let cursorY = 48;

  doc.setFont('helvetica', 'bold');
  doc.setFontSize(18);
  doc.text(title, marginX, cursorY);
  cursorY += 18;

  if (subtitle) {
    doc.setFont('helvetica', 'normal');
    doc.setFontSize(10.5);
    doc.setTextColor(90, 90, 90);
    const wrapped = doc.splitTextToSize(subtitle, pageWidth - marginX * 2);
    doc.text(wrapped, marginX, cursorY);
    cursorY += wrapped.length * 12 + 4;
    doc.setTextColor(0, 0, 0);
  }

  doc.setFontSize(9);
  doc.setFont('helvetica', 'normal');
  doc.text(`Erstellt am ${new Intl.DateTimeFormat('de-DE', { dateStyle: 'medium', timeStyle: 'short' }).format(new Date())}`, marginX, cursorY);
  cursorY += 18;

  sections.forEach((section) => {
    if (cursorY > doc.internal.pageSize.getHeight() - 120) {
      doc.addPage();
      cursorY = 42;
    }

    if (section.title) {
      doc.setFont('helvetica', 'bold');
      doc.setFontSize(12);
      doc.text(section.title, marginX, cursorY);
      cursorY += 14;
    }

    if (Array.isArray(section.lines)) {
      doc.setFont('helvetica', 'normal');
      doc.setFontSize(10);
      section.lines.forEach((line) => {
        const wrapped = doc.splitTextToSize(`- ${line}`, pageWidth - marginX * 2);
        doc.text(wrapped, marginX, cursorY);
        cursorY += wrapped.length * 11;
      });
      cursorY += 6;
    }

    if (section.table && Array.isArray(section.table.rows) && section.table.rows.length > 0) {
      autoTable(doc, {
        startY: cursorY,
        head: [section.table.headers || []],
        body: section.table.rows,
        margin: { left: marginX, right: marginX },
        styles: { fontSize: 9, cellPadding: 4 },
        headStyles: { fillColor: [24, 70, 54] },
        theme: 'grid',
      });
      cursorY = (doc.lastAutoTable?.finalY || cursorY) + 16;
    } else if (section.table) {
      doc.setFont('helvetica', 'italic');
      doc.setFontSize(10);
      doc.text('Keine Einträge vorhanden.', marginX, cursorY);
      cursorY += 14;
    }
  });

  doc.save(filename);
}
