import { jsPDF } from 'jspdf';
import autoTable from 'jspdf-autotable';
import { supabase } from '@/integrations/supabase/client';
import { v4 as uuidv4 } from 'uuid';
import { format } from 'date-fns';
import { buildSecureStorageKey } from '@/lib/secureStorageNaming';

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

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

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

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

    lastError = error;
  }

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

export async function generateOwnerNotificationProofPdf({
  associationName,
  subject,
  body,
  owners,
  attachments = [],
  senderName,
  senderEmail
}) {
  const doc = new jsPDF({ format: 'letter', unit: 'pt' });
  const validationId = uuidv4();
  const timestamp = new Date();

  // Page 1: Notification Details
  const margin = 40;
  let currentY = margin;
  const pageWidth = doc.internal.pageSize.getWidth();

  // Header
  doc.setFont('helvetica', 'bold');
  doc.setFontSize(18);
  doc.setTextColor(44, 62, 80);
  doc.text('Owner Notification Report', margin, currentY);
  
  currentY += 25;
  doc.setFontSize(10);
  doc.setFont('helvetica', 'normal');
  doc.setTextColor(100, 100, 100);
  doc.text(`Generated: ${format(timestamp, 'MMM d, yyyy h:mm a')}`, margin, currentY);
  doc.text(`Validation ID: ${validationId}`, pageWidth - margin, currentY, { align: 'right' });
  
  currentY += 20;
  doc.setDrawColor(200, 200, 200);
  doc.line(margin, currentY, pageWidth - margin, currentY);
  currentY += 20;

  // Metadata
  doc.setFont('helvetica', 'bold');
  doc.setTextColor(0, 0, 0);
  doc.text('Association:', margin, currentY);
  doc.setFont('helvetica', 'normal');
  doc.text(associationName || 'N/A', margin + 80, currentY);
  currentY += 15;

  doc.setFont('helvetica', 'bold');
  doc.text('Sender:', margin, currentY);
  doc.setFont('helvetica', 'normal');
  doc.text(`${senderName} (${senderEmail})`, margin + 80, currentY);
  currentY += 15;

  doc.setFont('helvetica', 'bold');
  doc.text('Subject:', margin, currentY);
  doc.setFont('helvetica', 'normal');
  
  const subjectLines = doc.splitTextToSize(subject, pageWidth - margin * 2 - 80);
  doc.text(subjectLines, margin + 80, currentY);
  currentY += (subjectLines.length * 12) + 5;

  // Attachments Info
  if (attachments && attachments.length > 0) {
    doc.setFont('helvetica', 'bold');
    doc.text('Attachments:', margin, currentY);
    doc.setFont('helvetica', 'normal');
    const attNames = attachments.map(a => a.name).join(', ');
    const attLines = doc.splitTextToSize(attNames, pageWidth - margin * 2 - 80);
    doc.text(attLines, margin + 80, currentY);
    currentY += (attLines.length * 12) + 10;
  }

  // Message Body
  currentY += 10;
  doc.setFont('helvetica', 'bold');
  doc.text('Message Content:', margin, currentY);
  currentY += 15;
  
  doc.setFont('helvetica', 'normal');
  doc.setFontSize(9);
  
  const strippedBody = body.replace(/<[^>]*>?/gm, '');
  const bodyLines = doc.splitTextToSize(strippedBody, pageWidth - margin * 2);
  
  if (currentY + (bodyLines.length * 12) > doc.internal.pageSize.getHeight() - margin) {
     doc.addPage();
     currentY = margin;
  }
  
  doc.text(bodyLines, margin, currentY);
  currentY += (bodyLines.length * 12) + 30;

  // Recipient List Page
  doc.addPage();
  currentY = margin;
  
  doc.setFont('helvetica', 'bold');
  doc.setFontSize(14);
  doc.setTextColor(44, 62, 80);
  doc.text(`Recipients (${owners.length} Total)`, margin, currentY);
  currentY += 15;

  const tableData = owners.map(o => [
    o.first_name && o.last_name ? `${o.first_name} ${o.last_name}` : (o.owner_name || 'Unknown'),
    o.email || 'N/A',
    o.status === 'failed' ? 'Failed' : (o.status === 'accepted' || o.status === 'sent' ? 'Accepted by SMTP' : (o.status || 'Unknown'))
  ]);

  autoTable(doc, {
    startY: currentY,
    head: [['Owner Name', 'Email Address', 'Status']],
    body: tableData,
    theme: 'grid',
    headStyles: { fillColor: [41, 128, 185], textColor: 255 },
    styles: { fontSize: 8, cellPadding: 4 },
    margin: { top: margin, right: margin, bottom: margin, left: margin },
  });

  const pdfBlob = doc.output('blob');
  const upload = await uploadProofPdf(pdfBlob, `owner-notification-proof-${validationId}.pdf`, 'owner-notification-proofs');

  return { ...upload, validationId };
}
