import { jsPDF } from 'jspdf';
import { supabase } from '@/integrations/supabase/client';
import { buildSecureStorageKey } from '@/lib/secureStorageNaming';

const PROOF_BUCKETS = ['proof-files', 'email-proofs', 'files'];

async function uploadProofPdf(pdfBlob, originalName, prefix) {
  const filePath = buildSecureStorageKey(originalName, prefix);
  let lastError = null;

  for (const bucket of PROOF_BUCKETS) {
    const { error } = await supabase.storage
      .from(bucket)
      .upload(filePath, pdfBlob, { contentType: 'application/pdf', upsert: true });

    if (!error) {
      const { data } = supabase.storage.from(bucket).getPublicUrl(filePath);
      return { publicUrl: data.publicUrl, filePath, bucket };
    }

    lastError = error;
  }

  throw lastError || new Error('Unable to upload proof PDF.');
}

function stripHtml(value = '') {
  return value.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
}

export async function generateEmailHistoryProofPdf(email) {
  const doc = new jsPDF({ format: 'letter', unit: 'pt' });
  const margin = 40;
  const pageWidth = doc.internal.pageSize.getWidth();
  const pageHeight = doc.internal.pageSize.getHeight();
  let currentY = margin;

  doc.setFont('helvetica', 'bold');
  doc.setFontSize(18);
  doc.text('Email Delivery Proof', margin, currentY);

  currentY += 24;
  doc.setFont('helvetica', 'normal');
  doc.setFontSize(10);
  doc.setTextColor(90, 90, 90);
  doc.text(`Generated: ${new Date().toLocaleString()}`, margin, currentY);
  doc.text(`Record ID: ${email.id}`, pageWidth - margin, currentY, { align: 'right' });

  currentY += 18;
  doc.setDrawColor(210, 210, 210);
  doc.line(margin, currentY, pageWidth - margin, currentY);
  currentY += 22;

  const rows = [
    ['Status', email.status || 'unknown'],
    ['Sender', email.sender_email || 'N/A'],
    ['Recipient', email.recipient_email || 'N/A'],
    ['Subject', email.subject || 'N/A'],
    ['Sent At', email.sent_at ? new Date(email.sent_at).toLocaleString() : 'N/A'],
    ['Feature', email.feature_type || 'N/A'],
  ];

  if (email.opened_at) {
    const openLabel = email.open_count && Number(email.open_count) > 1
      ? `${new Date(email.opened_at).toLocaleString()} (${email.open_count} opens)`
      : new Date(email.opened_at).toLocaleString();
    rows.push(['Opened', openLabel]);
  } else {
    rows.push(['Opened', 'Not opened yet']);
  }

  const errorText = email.email_headers?.error || email.email_headers?.message || null;
  if (errorText) rows.push(['Error', String(errorText)]);

  doc.setTextColor(0, 0, 0);
  rows.forEach(([label, value]) => {
    doc.setFont('helvetica', 'bold');
    doc.text(`${label}:`, margin, currentY);
    doc.setFont('helvetica', 'normal');
    const lines = doc.splitTextToSize(String(value), pageWidth - margin * 2 - 90);
    doc.text(lines, margin + 90, currentY);
    currentY += Math.max(16, lines.length * 12 + 4);
  });

  currentY += 12;
  doc.setFont('helvetica', 'bold');
  doc.text('Email Content:', margin, currentY);
  currentY += 14;

  doc.setFont('helvetica', 'normal');
  doc.setFontSize(9);
  const bodyLines = doc.splitTextToSize(stripHtml(email.body_text || ''), pageWidth - margin * 2);

  bodyLines.forEach((line) => {
    if (currentY > pageHeight - margin) {
      doc.addPage();
      currentY = margin;
    }
    doc.text(line, margin, currentY);
    currentY += 12;
  });

  const pdfBlob = doc.output('blob');
  return uploadProofPdf(pdfBlob, `email-proof-${email.id || Date.now()}.pdf`, 'email-history');
}
