import React, { useEffect, useState, useRef } from 'react';
import { __ } from '@wordpress/i18n';
import { Dialog } from 'primereact/dialog';
import { Button } from 'primereact/button';
import { ProgressSpinner } from 'primereact/progressspinner';

import RendicontazioneService from '../service/rendicontazioneService';

/**
 * Dialog full-height per preview inline PDF/immagini.
 * Fetcha il blob dal microservizio (Authorization header), crea object URL,
 * lo monta in iframe. Revoca l'URL alla chiusura.
 *
 * Props:
 *   visible          boolean
 *   onHide           () => void
 *   entityType       'invoice' | 'ula' | 'document'
 *   entityId         UUID
 *   title            stringa titolo dialog
 *   filename         nome file da mostrare e usare per download
 */
const FilePreviewDialog = ({ visible, onHide, entityType, entityId, title, filename }) => {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [objectUrl, setObjectUrl] = useState(null);
    const currentUrlRef = useRef(null);

    useEffect(() => {
        // cleanup url precedente
        if (currentUrlRef.current) {
            URL.revokeObjectURL(currentUrlRef.current);
            currentUrlRef.current = null;
        }

        if (!visible || !entityType || !entityId) {
            setObjectUrl(null);
            setError(null);
            return;
        }

        setLoading(true);
        setError(null);
        RendicontazioneService.fetchEntityFileBlob(entityType, entityId, true,
            ({ objectUrl }) => {
                currentUrlRef.current = objectUrl;
                setObjectUrl(objectUrl);
                setLoading(false);
            },
            (err) => {
                setError(err.detail || __('Errore caricamento file', 'gepafin'));
                setLoading(false);
            }
        );

        return () => {
            if (currentUrlRef.current) {
                URL.revokeObjectURL(currentUrlRef.current);
                currentUrlRef.current = null;
            }
        };
    }, [visible, entityType, entityId]);

    const onDownload = () => {
        RendicontazioneService.downloadEntityFile(entityType, entityId,
            (err) => setError(err.detail || __('Errore download', 'gepafin'))
        );
    };

    const footer = (
        <div className="flex justify-content-between">
            <span className="text-color-secondary">{filename}</span>
            <div>
                <Button label={__('Scarica', 'gepafin')} icon="pi pi-download"
                        className="p-button-sm p-button-outlined"
                        onClick={onDownload} disabled={!objectUrl} />
                <Button label={__('Chiudi', 'gepafin')} icon="pi pi-times"
                        className="p-button-sm p-button-text ml-2"
                        onClick={onHide} />
            </div>
        </div>
    );

    return (
        <Dialog
            header={title || __('Anteprima file', 'gepafin')}
            visible={visible}
            onHide={onHide}
            style={{ width: '90vw', height: '92vh' }}
            contentStyle={{ padding: 0, overflow: 'hidden' }}
            maximizable
            footer={footer}
        >
            {loading && (
                <div className="flex align-items-center justify-content-center" style={{ height: '100%' }}>
                    <ProgressSpinner />
                </div>
            )}
            {error && !loading && (
                <div className="p-4">
                    <div className="p-error">{error}</div>
                </div>
            )}
            {!loading && !error && objectUrl && (
                <iframe
                    src={objectUrl}
                    title={filename || 'preview'}
                    style={{ width: '100%', height: '100%', border: 'none' }}
                />
            )}
        </Dialog>
    );
};

export default FilePreviewDialog;
