import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';
// --- THIS IS THE KEY CHANGE ---
// We no longer need our custom api client, but we need axios directly.
import axios from 'axios';
import { format } from 'date-fns';


// --- THIS HELPER FUNCTION IS NOW CORRECTED ---
const getBase64ImageFromURL = (url) => {
    return new Promise((resolve, reject) => {
        // We now use `axios.get` directly. It will use the URL as-is
        // without prepending `/api`.
        axios.get(url, { responseType: 'blob' })
            .then(response => {
                const reader = new FileReader();
                reader.onloadend = () => resolve(reader.result);
                reader.onerror = reject;
                reader.readAsDataURL(response.data);
            })
            .catch(reject);
    });
};

export const generatePdfReport = async (violation, vahanData) => {
    document.body.style.cursor = 'wait';
    try {
        const logoUrl = 'https://storageapi.pushpak.cloud/prod-data/cyberabad_logo.png';
        
        // --- THIS URL IS NOW CORRECT ---
        // It correctly creates a relative path like `/images/composite_...jpg`
        // const evidenceUrl = `/images/${violation.composite_image_path.replace('generated_images', '')}`;
        const evidenceUrl = `/images/${violation.composite_image_path.replace('/img_data/', '')}`;



        // The rest of the function works as intended because getBase64ImageFromURL is now fixed.
        const [logoBase64, evidenceBase64] = await Promise.all([
            getBase64ImageFromURL(logoUrl),
            getBase64ImageFromURL(evidenceUrl)
        ]);

        const doc = new jsPDF('p', 'mm', 'a4');
        const pageWidth = doc.internal.pageSize.getWidth();
        const pageHeight = doc.internal.pageSize.getHeight();
        const margin = 10;
        let lastY = 0;

        const STYLES = { titleFontSize: 18, headerFontSize: 10, bodyFontSize: 8.5, cellPadding: 1.5, sectionSpacing: 6 };

        doc.addImage(logoBase64, 'PNG', margin, 10, 20, 20);
        doc.setFont('helvetica', 'bold');
        doc.setFontSize(STYLES.titleFontSize);
        doc.text('E-Challan Violation Report', pageWidth / 2, 22, { align: 'center' });
        doc.setLineWidth(0.5);
        doc.line(margin, 30, pageWidth - margin, 30);
        lastY = 32;

        const violationDetailsBody = [
            ['Violation ID', violation.id], ['License Plate', violation.license_plate_number],
            ['Challan Status', violation.challan_status], ['Timestamp', format(new Date(violation.timestamp + 'Z'), 'dd-MMM-yyyy hh:mm a')],
            ['Location', violation.location_text], ['Officer', violation.username],
        ];
        autoTable(doc, {
            startY: lastY, head: [['Violation Details', '']], body: violationDetailsBody,
            theme: 'grid', headStyles: { fillColor: [22, 160, 133], fontSize: STYLES.headerFontSize },
            styles: { fontSize: STYLES.bodyFontSize, cellPadding: STYLES.cellPadding },
            margin: { left: margin, right: pageWidth / 2 + 5 },
        });
        
        const imageWidth = (pageWidth / 2) - (margin * 1.5);
        const imageHeight = 75;
        doc.addImage(evidenceBase64, 'JPEG', pageWidth / 2, lastY, imageWidth, imageHeight);
        lastY = doc.lastAutoTable.finalY > (lastY + imageHeight) ? doc.lastAutoTable.finalY : (lastY + imageHeight);
        lastY += STYLES.sectionSpacing;

        autoTable(doc, {
            startY: lastY, head: [['Violation Types Cited']],
            body: [[JSON.parse(violation.violation_types).join(', ')]],
            theme: 'striped', headStyles: { fillColor: [44, 62, 80], fontSize: STYLES.headerFontSize },
            styles: { fontSize: STYLES.bodyFontSize, cellPadding: STYLES.cellPadding },
        });
        lastY = doc.lastAutoTable.finalY + STYLES.sectionSpacing;

        const vahanBody = [];
        for (const category in vahanData) {
            const categoryData = vahanData[category];
            vahanBody.push([{ content: categoryData.title, colSpan: 2, styles: { halign: 'left', fontStyle: 'bold', fillColor: [236, 240, 241], textColor: [44, 62, 80] } }]);
            categoryData.details.forEach(item => { vahanBody.push([item.label, item.value]); });
        }
        autoTable(doc, {
            startY: lastY, head: [['Vahan Vehicle Details', '']], body: vahanBody,
            theme: 'grid', headStyles: { fillColor: [41, 128, 185], fontSize: STYLES.headerFontSize },
            styles: { fontSize: STYLES.bodyFontSize, cellPadding: STYLES.cellPadding },
        });

        const signatureY = pageHeight - 35;
        doc.setLineWidth(0.3);
        doc.line(margin, signatureY, margin + 70, signatureY);
        doc.setFontSize(10);
        doc.setFont('helvetica', 'normal');
        doc.text('Signature of Issuing Officer', margin, signatureY + 5);
        
        doc.setLineWidth(0.5);
        doc.line(margin, pageHeight - 20, pageWidth - margin, pageHeight - 20);
        doc.setFontSize(8);
        doc.setFont('helvetica', 'italic');
        doc.text(`Report generated on: ${new Date().toLocaleString()}`, margin, pageHeight - 15);
        doc.text('Powered by Pushpak AI', pageWidth - margin, pageHeight - 15, { align: 'right' });

        doc.save(`violation-report-${violation.id}.pdf`);

    } catch (error) {
        console.error("Failed to generate PDF:", error);
        throw new Error("Could not generate the report. Failed to load necessary images.");
    } finally {
        document.body.style.cursor = 'default';
    }
};