import { jsPDF } from 'jspdf';
import 'jspdf-autotable';
import { format } from 'date-fns';
import { getHighQualityPdfSettings, loadImageHighQuality, applyHighQualityImageToPdf } from '@/lib/pdfQualityUtils';
import { formatARCSummary } from '@/lib/arcSummaryUtils';

/**
 * Generates and downloads a PDF summary for an ARC Application.
 * @param {object} application - The ARC application data object
 * @param {string} logoUrl - Optional URL for the company/association logo
 */
export const generateARCApplicationPDF = async (application, logoUrl) => {
  if (!application) return;

  // Format data using the existing utility to ensure consistency
  const data = formatARCSummary(application);
  const doc = new jsPDF(getHighQualityPdfSettings('portrait', 'pt', 'letter'));
  
  const pageWidth = doc.internal.pageSize.getWidth();
  const pageHeight = doc.internal.pageSize.getHeight();
  const margin = 40;
  let currentY = 40;

  // --- Header Section ---
  
  // 1. Logo (if available)
  if (logoUrl) {
    try {
      const logoSize = 60;
      await applyHighQualityImageToPdf(doc, logoUrl, margin, currentY, logoSize, logoSize);
      // We don't advance Y yet, we'll place text to the right
    } catch (error) {
      console.warn('Failed to load logo for PDF', error);
    }
  }

  // 2. Header Text
  doc.setFont('helvetica', 'bold');
  doc.setFontSize(22);
  doc.setTextColor(30, 41, 59); // Slate 800
  const titleX = logoUrl ? margin + 75 : margin;
  doc.text('ARC Application Summary', titleX, currentY + 20);

  doc.setFont('helvetica', 'normal');
  doc.setFontSize(10);
  doc.setTextColor(100, 116, 139); // Slate 500
  doc.text(`Generated on ${format(new Date(), 'MMMM do, yyyy')}`, titleX, currentY + 35);
  doc.text(`ID: ${application.id?.slice(0, 8)}`, titleX, currentY + 48);

  currentY += 80;

  // --- Status Banner ---
  const statusColor = 
    data.status === 'approved' ? [34, 197, 94] : // Green
    data.status === 'rejected' ? [239, 68, 68] : // Red
    [234, 179, 8]; // Yellow

  doc.setFillColor(...statusColor);
  doc.roundedRect(margin, currentY, pageWidth - (margin * 2), 25, 3, 3, 'F');
  
  doc.setTextColor(255, 255, 255);
  doc.setFont('helvetica', 'bold');
  doc.setFontSize(10);
  doc.text(`STATUS: ${data.status.toUpperCase()}`, margin + 15, currentY + 16);
  
  currentY += 45;

  // --- Application Details Table ---
  doc.autoTable({
    startY: currentY,
    head: [['Project Details', '']],
    body: [
      ['Property Address', data.address || 'N/A'],
      // 'Applicant/Owner' row removed as per request
      ['Association', data.displayClient],
      ['Submission Date', data.displayDate],
      ['Project Title', data.title]
    ],
    theme: 'grid',
    styles: {
      fontSize: 10,
      cellPadding: 8,
      lineColor: [226, 232, 240], // Slate 200
      lineWidth: 0.5,
    },
    headStyles: {
      fillColor: [51, 65, 85], // Slate 700
      textColor: [255, 255, 255],
      fontStyle: 'bold'
    },
    columnStyles: {
      0: { fontStyle: 'bold', cellWidth: 120, textColor: [71, 85, 105] },
      1: { textColor: [15, 23, 42] }
    },
    margin: { left: margin, right: margin }
  });

  currentY = doc.lastAutoTable.finalY + 30;

  // --- Description Section ---
  doc.setFont('helvetica', 'bold');
  doc.setFontSize(12);
  doc.setTextColor(15, 23, 42); // Slate 900
  doc.text('Description of Work', margin, currentY);
  
  currentY += 15;
  
  doc.setFont('helvetica', 'normal');
  doc.setFontSize(10);
  doc.setTextColor(51, 65, 85); // Slate 700
  
  const splitDescription = doc.splitTextToSize(data.description || 'No description provided.', pageWidth - (margin * 2));
  doc.text(splitDescription, margin, currentY);
  
  currentY += (splitDescription.length * 12) + 30;

  // --- Thumbnail / Attachment Image ---
  // If we have room on this page, add it, otherwise add new page
  if (data.thumbnailUrl) {
    // Check space
    if (pageHeight - currentY < 200) {
      doc.addPage();
      currentY = 40;
    }

    doc.setFont('helvetica', 'bold');
    doc.setFontSize(12);
    doc.setTextColor(15, 23, 42);
    doc.text('Attached Image Preview', margin, currentY);
    currentY += 20;

    try {
      // Limit image height
      const maxImgHeight = 300;
      const maxImgWidth = pageWidth - (margin * 2);
      
      const loadedImg = await loadImageHighQuality(data.thumbnailUrl);
      
      if (loadedImg) {
        let finalWidth = maxImgWidth;
        let finalHeight = finalWidth / loadedImg.ratio;

        if (finalHeight > maxImgHeight) {
          finalHeight = maxImgHeight;
          finalWidth = finalHeight * loadedImg.ratio;
        }

        await applyHighQualityImageToPdf(doc, loadedImg, margin, currentY, finalWidth, finalHeight);
        
        // Add a subtle border around image
        doc.setDrawColor(226, 232, 240);
        doc.rect(margin, currentY, finalWidth, finalHeight);
      }
    } catch (e) {
      console.error("Error adding thumbnail to PDF", e);
      doc.setFont('helvetica', 'italic');
      doc.setFontSize(9);
      doc.setTextColor(150);
      doc.text('(Image could not be loaded)', margin, currentY);
    }
  }

  // --- Footer ---
  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(
      `Page ${i} of ${pageCount}`,
      pageWidth / 2,
      pageHeight - 20,
      { align: 'center' }
    );
  }

  // Save File
  const cleanTitle = (data.title || 'Application').replace(/[^a-z0-9]/gi, '_').substring(0, 20);
  const dateStr = format(new Date(), 'yyyy-MM-dd');
  doc.save(`ARC_Application_${cleanTitle}_${dateStr}.pdf`);
};