import { jsPDF } from 'jspdf';
import { cleanText } from '@/lib/pdfTextUtils';

export const generateProofOfDeliveryPdf = (emailRecord) => {
  const doc = new jsPDF();
  const pageHeight = doc.internal.pageSize.height;
  const pageWidth = doc.internal.pageSize.width;
  const margin = 20;
  let yPos = margin;

  const checkPageBreak = (neededHeight) => {
    if (yPos + neededHeight > pageHeight - margin) {
      doc.addPage();
      yPos = margin;
    }
  };

  // 1. Document Header & Seal
  doc.setFillColor(248, 250, 252);
  doc.rect(0, 0, pageWidth, 40, 'F');
  
  doc.setFontSize(24);
  doc.setFont('helvetica', 'bold');
  doc.setTextColor(15, 23, 42); // Slate-900
  doc.text("Proof of Verification", margin, yPos + 8);
  
  // Draw a professional "seal" on the top right
  doc.setDrawColor(37, 99, 235); // Blue-600
  doc.setLineWidth(1);
  doc.circle(pageWidth - margin - 15, yPos + 4, 12, 'S');
  doc.circle(pageWidth - margin - 15, yPos + 4, 10, 'S');
  doc.setFontSize(8);
  doc.setTextColor(37, 99, 235);
  doc.text("VERIFIED", pageWidth - margin - 22, yPos + 5.5);

  yPos += 18;
  doc.setFontSize(10);
  doc.setFont('helvetica', 'normal');
  doc.setTextColor(100, 116, 139); // Slate-500
  doc.text(`Record ID: ${emailRecord.id}`, margin, yPos);
  doc.text(`Generated: ${new Date().toLocaleString()}`, pageWidth - margin, yPos, { align: 'right' });
  
  yPos += 8;
  doc.setDrawColor(226, 232, 240); // Slate-200
  doc.line(margin, yPos, pageWidth - margin, yPos);
  yPos += 12;

  // 2. Metadata Section
  doc.setFontSize(14);
  doc.setFont('helvetica', 'bold');
  doc.setTextColor(15, 23, 42);
  doc.text("Transmission Details", margin, yPos);
  yPos += 8;

  doc.setFontSize(11);
  const details = [
    { label: "Delivery Status:", value: (emailRecord.status || 'Unknown').toUpperCase() },
    { label: "Timestamp (UTC):", value: emailRecord.sent_at ? new Date(emailRecord.sent_at).toUTCString() : 'N/A' },
    { label: "Sender Address:", value: emailRecord.sender_email || 'N/A' },
    { label: "Recipient Address:", value: emailRecord.recipient_email || 'N/A' },
    { label: "Subject Line:", value: emailRecord.subject || 'No Subject' },
  ];

  details.forEach(detail => {
    checkPageBreak(8);
    doc.setFont('helvetica', 'bold');
    doc.setTextColor(71, 85, 105); // Slate-600
    doc.text(detail.label, margin, yPos);
    
    doc.setFont('helvetica', 'normal');
    // Color status based on success/fail
    if (detail.label === "Delivery Status:") {
      doc.setTextColor(detail.value === 'SENT' ? 22 : 220, detail.value === 'SENT' ? 163 : 38, detail.value === 'SENT' ? 74 : 38);
      doc.setFont('helvetica', 'bold');
    } else {
      doc.setTextColor(15, 23, 42); // Slate-900
    }
    
    const valueX = margin + 45;
    const splitValue = doc.splitTextToSize(detail.value, pageWidth - margin - valueX);
    doc.text(splitValue, valueX, yPos);
    
    yPos += (splitValue.length * 6) + 2;
  });

  yPos += 6;
  doc.setDrawColor(226, 232, 240);
  doc.line(margin, yPos, pageWidth - margin, yPos);
  yPos += 12;

  // 3. Clean Content Section
  checkPageBreak(15);
  doc.setFontSize(14);
  doc.setFont('helvetica', 'bold');
  doc.setTextColor(15, 23, 42);
  doc.text("Message Content Snapshot", margin, yPos);
  yPos += 8;

  doc.setFontSize(10);
  doc.setFont('helvetica', 'normal');
  doc.setTextColor(51, 65, 85); // Slate-700

  const rawContent = emailRecord.body_text || emailRecord.raw_body || "No body text recorded.";
  const cleanedText = cleanText(rawContent);
  
  const bodyLines = doc.splitTextToSize(cleanedText, pageWidth - (margin * 2));
  
  // Draw a light box around the content
  doc.setFillColor(248, 250, 252);
  doc.rect(margin - 2, yPos - 4, pageWidth - (margin * 2) + 4, (bodyLines.length * 5.5) + 8, 'F');
  
  bodyLines.forEach(line => {
    checkPageBreak(6);
    doc.text(line, margin, yPos);
    yPos += 5.5;
  });

  // 4. Footer on all pages
  const pageCount = doc.internal.getNumberOfPages();
  for (let i = 1; i <= pageCount; i++) {
    doc.setPage(i);
    doc.setFontSize(8);
    doc.setTextColor(148, 163, 184); // Slate-400
    doc.text(
      `Official Proof of Verification - Page ${i} of ${pageCount}`,
      pageWidth / 2,
      pageHeight - 10,
      { align: 'center' }
    );
  }

  doc.save(`Proof_of_Verification_${emailRecord.id.substring(0,8)}.pdf`);
};