
/**
 * PDF Generation Utility: generateComprehensivePDF
 * 
 * Expected Usage:
 * Generates a multi-page comprehensive report (Executive Summary + Data Tables) using jsPDF.
 * 
 * Troubleshooting Blank PDFs:
 * - Empty arrays for sections (e.g., `reportData.statusUpdates`) simply omit that section.
 * - If the entire PDF is blank or lacks pages, check if `reportData` properties are correctly populated.
 * 
 * Supported Content:
 * - Text, Rectangles, AutoTables.
 */

import { jsPDF } from 'jspdf';
import autoTable from 'jspdf-autotable';
import { format, isValid } from 'date-fns';

// Helper for safe date formatting
const safeFormat = (dateInput, formatStr) => {
  if (!dateInput) return '-';
  const date = new Date(dateInput);
  if (!isValid(date)) return '-';
  return format(date, formatStr);
};

export const generateComprehensivePDF = async (reportData, config) => {
  if (!reportData) throw new Error("No report data provided");

  const { 
    clientName, 
    periodStart, 
    periodEnd, 
    reportType = "Management Report",
    logoUrl 
  } = config;
  
  // Set to standard Letter size (8.5x11 inches, pt units)
  const doc = new jsPDF({ format: 'letter', unit: 'pt', compress: true });
  const pageWidth = doc.internal.pageSize.width;
  let finalY = 0;

  // --- Helper: Centered Text ---
  const centerText = (text, y, options = {}) => {
    doc.text(text || '', pageWidth / 2, y, { align: "center", ...options });
  };

  // --- Helper: Add Section Header ---
  const addSectionHeader = (title) => {
    if (finalY > 700) {
      doc.addPage();
      finalY = 40;
    } else {
      finalY += 30;
    }
    
    doc.setFontSize(16);
    doc.setFont("helvetica", "bold");
    doc.setTextColor(30, 41, 59); // Slate 800
    doc.text(title || 'Section', 40, finalY);
    
    // Underline
    doc.setLineWidth(0.5);
    doc.setDrawColor(203, 213, 225); // Slate 300
    doc.line(40, finalY + 5, pageWidth - 40, finalY + 5);
    
    finalY += 20;
  };

  // --- 1. COVER PAGE ---
  // Background/Decorative Strip
  doc.setFillColor(30, 41, 59); // Slate 800
  doc.rect(0, 0, pageWidth, 40, 'F');

  // Title Area
  doc.setFontSize(36);
  doc.setTextColor(30, 41, 59);
  doc.setFont("helvetica", "bold");
  centerText((reportType || "Report").toUpperCase(), 150);

  doc.setFontSize(16);
  doc.setFont("helvetica", "normal");
  doc.setTextColor(100, 116, 139); // Slate 500
  centerText("CONFIDENTIAL REPORT", 180);

  // Period
  doc.setFontSize(14);
  doc.setTextColor(15, 23, 42);
  const pStart = safeFormat(periodStart, 'MMMM d, yyyy');
  const pEnd = safeFormat(periodEnd, 'MMMM d, yyyy');
  centerText(`${pStart} — ${pEnd}`, 210);

  // Client Name Box
  doc.setDrawColor(30, 41, 59);
  doc.setLineWidth(1);
  doc.rect(pageWidth/4, 250, pageWidth/2, 60);
  doc.setFontSize(18);
  doc.setFont("helvetica", "bold");
  centerText(clientName || 'Client Report', 285);

  // Footer
  doc.setFontSize(10);
  doc.setTextColor(148, 163, 184);
  centerText(`Generated on ${safeFormat(new Date(), 'MMMM d, yyyy h:mm a')}`, 750);

  // --- 2. EXECUTIVE SUMMARY ---
  doc.addPage();
  finalY = 50;
  
  doc.setFontSize(24);
  doc.setTextColor(30, 41, 59);
  doc.text("Executive Summary", 40, finalY);
  finalY += 30;

  // Stats Grid
  const stats = [
    { label: "Status Updates", value: reportData.statusUpdates?.length || 0 },
    { label: "Violations", value: reportData.violations?.length || 0 },
    { label: "ARC Requests", value: reportData.arcApplications?.length || 0 },
    { label: "Open Collections", value: reportData.collections?.length || 0 },
  ];

  let xPos = 40;
  stats.forEach((stat) => {
    doc.setFillColor(241, 245, 249); // Slate 100
    doc.roundedRect(xPos, finalY, 100, 60, 4, 4, 'F');
    
    doc.setFontSize(14);
    doc.setFont("helvetica", "bold");
    doc.setTextColor(30, 41, 59);
    doc.text(String(stat.value), xPos + 50, finalY + 25, { align: "center" });
    
    doc.setFontSize(10);
    doc.setFont("helvetica", "normal");
    doc.setTextColor(100, 116, 139);
    doc.text(stat.label, xPos + 50, finalY + 45, { align: "center" });
    
    xPos += 120;
  });
  finalY += 90;

  // Financial Snapshot
  if (reportData.financialMetrics) {
    const fm = reportData.financialMetrics;
    doc.setFontSize(14);
    doc.setTextColor(30, 41, 59);
    doc.text("Financial Snapshot", 40, finalY);
    finalY += 15;
    
    autoTable(doc, {
      startY: finalY,
      head: [['Metric', 'Amount']],
      body: [
        ['Operating Balance', `$${fm.current_balance || '0.00'}`],
        ['Reserve Fund', `$${fm.reserve_fund_balance || '0.00'}`],
        ['Net Income (YTD)', `$${fm.net_income || '0.00'}`]
      ],
      theme: 'grid',
      headStyles: { fillColor: [71, 85, 105] },
      margin: { left: 40, right: 200 }
    });
    finalY = doc.lastAutoTable.finalY + 30;
  }

  // --- 3. SECTIONS ---
  
  // Status Updates
  if (reportData.statusUpdates?.length > 0) {
    addSectionHeader("Status Updates");
    autoTable(doc, {
      startY: finalY,
      head: [['Date', 'Title', 'Details']],
      body: reportData.statusUpdates.map(i => [
        safeFormat(i.created_at, 'MMM d'),
        i.title || '-',
        i.content || '-'
      ]),
      theme: 'grid',
      headStyles: { fillColor: [37, 99, 235] }, // Blue
      margin: { left: 40, right: 40 }
    });
    finalY = doc.lastAutoTable.finalY;
  }

  // Owner Updates
  if (reportData.ownerUpdates?.length > 0) {
    addSectionHeader("Owner Updates");
    autoTable(doc, {
      startY: finalY,
      head: [['Date', 'Address', 'Update']],
      body: reportData.ownerUpdates.map(i => [
        safeFormat(i.posted_at, 'MMM d'),
        i.property_owners?.property_address || '-',
        i.content || '-'
      ]),
      theme: 'grid',
      headStyles: { fillColor: [13, 148, 136] }, // Teal
      margin: { left: 40, right: 40 }
    });
    finalY = doc.lastAutoTable.finalY;
  }

  // Violations
  if (reportData.violations?.length > 0) {
    addSectionHeader("Violations");
    autoTable(doc, {
      startY: finalY,
      head: [['Date', 'Address', 'Type', 'Status']],
      body: reportData.violations.map(i => [
        safeFormat(i.created_at, 'MMM d'),
        i.address || '-',
        i.violation_type || '-',
        i.status || '-'
      ]),
      theme: 'grid',
      headStyles: { fillColor: [220, 38, 38] }, // Red
      margin: { left: 40, right: 40 }
    });
    finalY = doc.lastAutoTable.finalY;
  }

  // ARC Applications
  if (reportData.arcApplications?.length > 0) {
    addSectionHeader("ARC Applications");
    autoTable(doc, {
      startY: finalY,
      head: [['Date', 'Address', 'Description', 'Status']],
      body: reportData.arcApplications.map(i => [
        safeFormat(i.created_at, 'MMM d'),
        i.address || '-',
        i.description || i.title || '-',
        i.status || '-'
      ]),
      theme: 'grid',
      headStyles: { fillColor: [16, 185, 129] }, // Emerald
      margin: { left: 40, right: 40 }
    });
    finalY = doc.lastAutoTable.finalY;
  }

  // Collections
  if (reportData.collections?.length > 0) {
    addSectionHeader("Collections");
    autoTable(doc, {
      startY: finalY,
      head: [['Address', 'Stage', 'Status', 'Amount']],
      body: reportData.collections.map(i => [
        i.address || '-',
        i.stage || '-',
        i.status || '-',
        `$${i.amount_due || '0.00'}`
      ]),
      theme: 'grid',
      headStyles: { fillColor: [124, 58, 237] }, // Violet
      margin: { left: 40, right: 40 }
    });
    finalY = doc.lastAutoTable.finalY;
  }

  // Call Logs
  if (reportData.callLogs?.length > 0) {
    addSectionHeader("Call Logs");
    autoTable(doc, {
      startY: finalY,
      head: [['Date', 'Caller', 'Notes']],
      body: reportData.callLogs.map(i => [
        safeFormat(i.created_at, 'MMM d'),
        i.caller_name || 'Unknown',
        i.notes || '-'
      ]),
      theme: 'grid',
      headStyles: { fillColor: [249, 115, 22] }, // Orange
      margin: { left: 40, right: 40 }
    });
    finalY = doc.lastAutoTable.finalY;
  }
  
  // Board Votes
  if (reportData.boardVotes?.length > 0) {
      addSectionHeader("Board Votes");
      autoTable(doc, {
          startY: finalY,
          head: [['Date', 'Title', 'Status']],
          body: reportData.boardVotes.map(i => [
              safeFormat(i.created_at, 'MMM d'),
              i.title || '-',
              i.status || '-'
          ]),
          theme: 'grid',
          headStyles: { fillColor: [75, 85, 99] }, // Gray
          margin: { left: 40, right: 40 }
      });
      finalY = doc.lastAutoTable.finalY;
  }
  
  // Legal Matters
  if (reportData.legalMatters?.length > 0) {
      addSectionHeader("Legal Matters");
      autoTable(doc, {
          startY: finalY,
          head: [['Title', 'Case No', 'Status']],
          body: reportData.legalMatters.map(i => [
              i.title || '-',
              i.case_no || '-',
              i.current_stage || '-'
          ]),
          theme: 'grid',
          headStyles: { fillColor: [185, 28, 28] }, // Dark Red
          margin: { left: 40, right: 40 }
      });
      finalY = doc.lastAutoTable.finalY;
  }

  // Save
  const safeClientName = (clientName || 'Report').replace(/[^a-zA-Z0-9]/g, '_');
  const safeDate = safeFormat(new Date(), 'yyyy-MM-dd');
  const filename = `${safeClientName}_Report_${safeDate}.pdf`;
  doc.save(filename);
  
  return true;
};
