import React, { useEffect, useState } from 'react';
import { DataProvider, useReportData } from './ReportEditor/DataContext';
import { BandProvider } from './ReportEditor/BandContext';
import EditorCanvas from './ReportEditor/EditorCanvas';
import api from '../services/api';
import './ReportPreviewModal.css';

function PreviewContent({ vehicleData, elements }) {
    const { setData } = useReportData();

    useEffect(() => {
        setData(vehicleData);
    }, [vehicleData]);

    return (
        <BandProvider>
            <EditorCanvas
                elements={elements}
                selectedElementIds={[]}
                previewMode={true}
                toolMode="select"
                borderStyle="single"
                onElementSelect={() => {}}
                onSelectMultiple={() => {}}
                onDeselectAll={() => {}}
                onElementUpdate={() => {}}
                onElementDelete={() => {}}
                onAddElement={() => {}}
            />
        </BandProvider>
    );
}

export default function ReportPreviewModal({ vehicleData, onClose }) {
    const [elements, setElements] = useState(null);
    const [error, setError] = useState('');

    useEffect(() => {
        api.get('/api/reports/')
            .then(res => {
                const reports = res.data.results || res.data;
                const report = reports.find(r => r.name === 'notice_report');
                if (report) {
                    setElements(report.elements || []);
                } else {
                    setError('Report "notice_report" not found. Create it in the Report Editor first.');
                }
            })
            .catch(() => setError('Failed to load report'));
    }, []);

    return (
        <div className="report-preview-overlay" onClick={onClose}>
            <div className="report-preview-modal" onClick={e => e.stopPropagation()}>
                <div className="report-preview-header">
                    <span>Notice Report — {vehicleData.vehicle.vehicle_number}</span>
                    <button className="report-preview-close" onClick={onClose}>×</button>
                </div>
                <div className="report-preview-body">
                    {error ? (
                        <div className="report-preview-error">{error}</div>
                    ) : elements === null ? (
                        <div className="report-preview-loading">Loading...</div>
                    ) : (
                        <DataProvider>
                            <PreviewContent vehicleData={vehicleData} elements={elements} />
                        </DataProvider>
                    )}
                </div>
            </div>
        </div>
    );
}
