import React, { useImperativeHandle, forwardRef } from 'react';
import { jsPDF } from 'jspdf';
import autoTable from 'jspdf-autotable';
import { format } from 'date-fns';
import { convert } from 'html-to-text';

async function getImageDataUrl(url) {
  try {
    const response = await fetch(url, { mode: 'cors' });
    const blob = await response.blob();
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.onloadend = () => resolve(reader.result);
      reader.readAsDataURL(blob);
    });
  } catch (e) {
    console.error('Failed to load image for PDF:', url, e);
    return null;
  }
}

export const StatusUpdatesPdfExport = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    generatePdf: async (data, dateRange, associationName = "Organization") => {
      const doc = new jsPDF({ orientation: 'landscape', unit: 'pt', format: 'letter' });
      doc.setCharSpace(0);

      const marginLeft = 43;
      const marginTop = 34;
      const marginRight = 43;
      const marginBottom = 34;
      const pageWidth = doc.internal.pageSize.getWidth();
      const pageHeight = doc.internal.pageSize.getHeight();
      const today = format(new Date(), 'MMM dd, yyyy');
      let currentY = marginTop;

      doc.setFontSize(18);
      doc.setTextColor(33, 37, 41);
      doc.setFont("helvetica", "bold");
      doc.text("Status Updates Report", marginLeft, currentY + 14);

      doc.setFontSize(11);
      doc.setTextColor(108, 117, 125);
      doc.setFont("helvetica", "normal");
      doc.text(`Generated: ${today}`, pageWidth - marginRight, currentY + 14, { align: 'right' });
      currentY += 35;

      let rangeText = "All Available Records";
      if (dateRange?.start && dateRange?.end) {
        rangeText = `${format(dateRange.start, 'MMM dd, yyyy')} - ${format(dateRange.end, 'MMM dd, yyyy')}`;
      } else if (dateRange?.start) {
        rangeText = `From ${format(dateRange.start, 'MMM dd, yyyy')}`;
      }

      doc.setFontSize(12);
      doc.setTextColor(0, 0, 0);
      doc.text(`Association: ${associationName}`, marginLeft, currentY);
      doc.text(`Period: ${rangeText}`, pageWidth - marginRight, currentY, { align: 'right' });
      currentY += 18;
      doc.setDrawColor(200, 200, 200);
      doc.setLineWidth(1);
      doc.line(marginLeft, currentY, pageWidth - marginRight, currentY);
      currentY += 25;

      const tableBody = [];
      for (const item of data) {
        const dateStr = item.created_at ? format(new Date(item.created_at), 'MMM dd, yyyy HH:mm') : 'N/A';
        const title = item.title || 'Untitled';
        const assocName = item.associations?.name || 'General';
        const details = convert(item.content || '', {
          wordwrap: false,
          selectors: [{ selector: 'img', format: 'skip' }, { selector: 'a', options: { hideLinkHrefIfSameAsText: true } }]
        });

        let imageData = null;
        if (item.image_urls && item.image_urls.length > 0) {
          imageData = await getImageDataUrl(item.image_urls[0]);
        }

        tableBody.push({
          date: dateStr, title, client: assocName, details, image: imageData,
          imageCount: item.image_urls ? item.image_urls.length : 0
        });
      }

      autoTable(doc, {
        startY: currentY,
        head: [['Date', 'Title', 'Association', 'Details', 'Images']],
        body: tableBody.map(row => [
          row.date, row.title, row.client, row.details,
          row.image ? '' : (row.imageCount > 0 ? `${row.imageCount} Images` : 'None')
        ]),
        theme: 'grid',
        styles: {
          font: 'helvetica', fontSize: 10, cellPadding: 8, textColor: 30,
          halign: 'left', valign: 'top', lineWidth: 0.5, lineColor: [220, 220, 220],
          overflow: 'linebreak', minCellHeight: 40
        },
        headStyles: {
          fillColor: [59, 130, 246], textColor: 255, fontSize: 11, fontStyle: 'bold', halign: 'left', cellPadding: 8
        },
        alternateRowStyles: { fillColor: [248, 250, 252] },
        columnStyles: {
          0: { cellWidth: 90 }, 1: { cellWidth: 140, fontStyle: 'bold' },
          2: { cellWidth: 110 }, 3: { halign: 'justify', cellWidth: 'auto' },
          4: { cellWidth: 80, halign: 'center' }
        },
        margin: { left: marginLeft, right: marginRight, top: marginTop, bottom: marginBottom },
        didDrawCell: (data) => {
          if (data.section === 'body' && data.column.index === 4) {
            const rowData = tableBody[data.row.index];
            if (rowData && rowData.image) {
              try {
                const dim = data.cell.height - 10;
                const x = data.cell.x + (data.cell.width - dim) / 2;
                const y = data.cell.y + 5;
                doc.addImage(rowData.image, 'JPEG', x, y, dim, dim);
                if (rowData.imageCount > 1) {
                  doc.setFontSize(8);
                  doc.text(`+${rowData.imageCount - 1} more`, data.cell.x + data.cell.width / 2, y + dim + 8, { align: 'center' });
                }
              } catch (err) { console.error("Error adding image to PDF", err); }
            }
          }
        },
        didDrawPage: () => {
          const pageCount = doc.internal.getNumberOfPages();
          doc.setFontSize(9);
          doc.setTextColor(150);
          doc.text(`Page ${pageCount}`, pageWidth - marginRight, pageHeight - 20, { align: 'right' });
        }
      });

      doc.save(`Status_Updates_${format(new Date(), 'yyyy-MM-dd')}.pdf`);
    }
  }));

  return null;
});

StatusUpdatesPdfExport.displayName = "StatusUpdatesPdfExport";
