// src/App.js (Your 'pdfForm' page equivalent)
import React, { useEffect, useRef, useState } from 'react';
// import './App.css'; // For basic styling
import axios from 'axios';

// Import your chosen commercial PDF SDK (e.g., PSPDFKit)
import PSPDFKit from 'pspdfkit';

function PDF() {
    const viewerRef = useRef(null); // Ref for the DOM element where PDF will render
    const instanceRef = useRef(null); // Ref for the PSPDFKit instance
    const [pdfLoaded, setPdfLoaded] = useState(false);

    useEffect(() => {
        const loadPdfViewer = async () => {
            if (viewerRef.current) {
                try {
                    // 1. Fetch the blank PDF template from your Spring Boot backend
                    const response = await axios.get('http://localhost:8090/api/pdf/template', {
                        responseType: 'arraybuffer' // Essential for binary data
                    });
                    const pdfBlob = new Blob([response.data], { type: 'application/pdf' });
                    const pdfUrl = URL.createObjectURL(pdfBlob);

                    // 2. Initialize the PDF SDK (e.g., PSPDFKit)
                    const instance = await PSPDFKit.load({
                        container: viewerRef.current,
                        document: pdfUrl,
                        // Remember to add your SDK license key if applicable
                        // licenseKey: "YOUR_PSPDFKIT_LICENSE_KEY",
                        baseUrl: process.env.PUBLIC_URL + '/pspdfkit-lib/', // Path to SDK assets
                        // Enable form filling UI
                        formDesignerViewMode: PSPDFKit.FormDesignerViewMode.Enabled
                    });

                    instanceRef.current = instance;
                    setPdfLoaded(true);

                    // 3. Clean up on component unmount
                    return () => {
                        if (instance) {
                            instance.unload(); // Unload SDK instance
                        }
                        URL.revokeObjectURL(pdfUrl); // Revoke the Blob URL
                    };

                } catch (error) {
                    console.error('Error loading PDF:', error);
                }
            }
        };

        loadPdfViewer();
    }, []); // Empty dependency array means this runs once on mount

    const handleSavePdf = async () => {
        if (instanceRef.current) {
            try {
                // Export the filled PDF from the SDK as an ArrayBuffer
                const arrayBuffer = await instanceRef.current.exportPDF();
                const filledPdfBlob = new Blob([arrayBuffer], { type: 'application/pdf' });

                // Create FormData to send the file to Spring Boot
                const formData = new FormData();
                formData.append('file', filledPdfBlob, 'filled_form.pdf');

                // Send the filled PDF to your Spring Boot backend's save endpoint
                const response = await axios.post('http://localhost:8090/api/pdf/saveFilled', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data' // Important for file uploads
                    }
                });
                console.log('PDF saved on server:', response.data);
                alert('PDF saved successfully on server!');
            } catch (error) {
                console.error('Error saving PDF:', error);
                alert('Failed to save PDF.');
            }
        }
    };

    const handlePrintPdf = () => {
        if (instanceRef.current) {
            // Trigger the SDK's built-in print functionality
            instanceRef.current.print();
        }
    };

    return (
        <div className="pdf-form-page"> {/* This is your 'pdfForm' page */}
            <header className="page-header">
                <h1>Fill and Manage Your PDF Form</h1>
                {pdfLoaded ? (
                    <div className="action-buttons">
                        <button onClick={handleSavePdf} className="action-button save-button">
                            Save Filled PDF
                        </button>
                        <button onClick={handlePrintPdf} className="action-button print-button">
                            Print PDF
                        </button>
                    </div>
                ) : (
                    <p>Loading PDF viewer...</p>
                )}
            </header>
            <div
                ref={viewerRef}
                className="pdf-viewer-container"
                style={{
                    width: '100%',
                    height: 'calc(100vh - 180px)', // Adjust height based on header/footer
                    border: '1px solid #ccc'
                }}
            >
                {/* The PDF SDK will render the PDF viewer here */}
            </div>
        </div>
    );
}

export default PDF;