import { jsPDF } from 'jspdf';
import html2canvas from 'html2canvas';

export const exportAsPdf = async (elementId: string, fileName: string, action: 'preview' | 'download'): Promise<void> => {
  const container = document.getElementById(elementId);
  
  if (!container) {
    console.error(`Element with id ${elementId} not found.`);
    return;
  }

  const pages = container.querySelectorAll('.report-page');
  if (pages.length === 0) {
    console.error('No report pages found');
    return;
  }

  try {
    const isDark = document.documentElement.classList.contains('dark');
    if (isDark) {
      document.documentElement.classList.remove('dark');
    }
    
    // Add pdf-export class to force high contrast text
    container.classList.add('pdf-export');
    
    await new Promise(resolve => setTimeout(resolve, 100)); // Allow CSS to recompute

    const pdf = new jsPDF({
      orientation: 'portrait',
      unit: 'mm',
      format: 'a4',
    });

    for (let i = 0; i < pages.length; i++) {
      const pageEl = pages[i] as HTMLElement;
      
      const canvas = await html2canvas(pageEl, {
        scale: 2, // Higher resolution
        useCORS: true,
        logging: false,
        backgroundColor: '#ffffff' // Ensure white background
      });

      const imgData = canvas.toDataURL('image/jpeg', 0.95);
      
      const pdfWidth = pdf.internal.pageSize.getWidth();
      const pdfHeight = (canvas.height * pdfWidth) / canvas.width;

      if (i > 0) {
        pdf.addPage();
      }

      pdf.addImage(imgData, 'JPEG', 0, 0, pdfWidth, pdfHeight);
    }

    container.classList.remove('pdf-export');

    if (isDark) {
      document.documentElement.classList.add('dark');
    }

    if (action === 'download') {
      pdf.save(`${fileName}.pdf`);
    } else {
      const pdfBlob = pdf.output('blob');
      const pdfUrl = URL.createObjectURL(pdfBlob);
      window.open(pdfUrl, '_blank');
      URL.revokeObjectURL(pdfUrl);
    }
  } catch (error) {
    console.error('Error generating PDF with html2canvas:', error);
  }
};