import React, { useRef, useState } from 'react';
import { __ } from '@wordpress/i18n';
import { Button } from 'primereact/button';
import { confirmPopup } from 'primereact/confirmpopup';

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

/**
 * Cella compatta per gestire il file allegato a una entita.
 *
 * Stati:
 *   nessun file        -> bottone "Carica"
 *   file presente      -> chip nome + icone (preview, download, delete)
 *   upload in corso    -> spinner
 *
 * Props:
 *   entityType   'invoice' | 'ula' | 'document'
 *   entityId     UUID
 *   filename     nome file corrente (null se nessuno)
 *   sizeBytes    dimensione in byte (opzionale)
 *   readOnly     se true nasconde upload/delete, mostra solo download/preview
 *   compact      se true riduce bottone "Carica"
 *   onChange     (fileMeta | null) => void  — callback dopo upload/delete OK
 *   onPreview    () => void  — attiva dialog preview esterno
 *   onError      (err) => void
 *   toastRef     ref al Toast per messaggi
 */
const MAX_BYTES = 15 * 1024 * 1024;
const ACCEPT = '.pdf,.jpg,.jpeg,.png,application/pdf,image/jpeg,image/png';

const formatSize = (n) => {
    if (!n) return '';
    if (n < 1024) return `${n} B`;
    if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`;
    return `${(n / (1024 * 1024)).toFixed(1)} MB`;
};

const FileUploadCell = ({
    entityType, entityId, filename, sizeBytes,
    readOnly = false, compact = false,
    onChange, onPreview, onError, toastRef
}) => {
    const inputRef = useRef(null);
    const [uploading, setUploading] = useState(false);

    const triggerPick = () => inputRef.current && inputRef.current.click();

    const onFileChange = (e) => {
        const f = e.target.files && e.target.files[0];
        e.target.value = ''; // reset per riupload stesso nome
        if (!f) return;
        if (f.size > MAX_BYTES) {
            const msg = __('File troppo grande (max 15 MB)', 'gepafin');
            toastRef && toastRef.current && toastRef.current.show({ severity: 'error', summary: __('Errore', 'gepafin'), detail: msg });
            onError && onError({ detail: msg });
            return;
        }
        setUploading(true);
        RendicontazioneService.uploadEntityFile(entityType, entityId, f,
            (resp) => {
                setUploading(false);
                toastRef && toastRef.current && toastRef.current.show({
                    severity: 'success', summary: __('File caricato', 'gepafin'),
                    detail: resp.data && resp.data.filename_original });
                onChange && onChange(resp.data);
            },
            (err) => {
                setUploading(false);
                const msg = err.detail || __('Errore upload', 'gepafin');
                toastRef && toastRef.current && toastRef.current.show({ severity: 'error', summary: __('Errore', 'gepafin'), detail: msg });
                onError && onError(err);
            }
        );
    };

    const onDownloadClick = () => {
        RendicontazioneService.downloadEntityFile(entityType, entityId,
            (err) => {
                const msg = err.detail || __('Errore download', 'gepafin');
                toastRef && toastRef.current && toastRef.current.show({ severity: 'error', summary: __('Errore', 'gepafin'), detail: msg });
            }
        );
    };

    const onDeleteClick = (ev) => {
        confirmPopup({
            target: ev.currentTarget,
            message: __('Eliminare il file allegato?', 'gepafin'),
            icon: 'pi pi-exclamation-triangle',
            acceptLabel: __('Elimina', 'gepafin'),
            rejectLabel: __('Annulla', 'gepafin'),
            acceptClassName: 'p-button-danger p-button-sm',
            rejectClassName: 'p-button-text p-button-sm',
            accept: () => {
                RendicontazioneService.deleteEntityFile(entityType, entityId,
                    () => {
                        toastRef && toastRef.current && toastRef.current.show({
                            severity: 'info', summary: __('File eliminato', 'gepafin') });
                        onChange && onChange(null);
                    },
                    (err) => {
                        const msg = err.detail || __('Errore eliminazione', 'gepafin');
                        toastRef && toastRef.current && toastRef.current.show({ severity: 'error', summary: __('Errore', 'gepafin'), detail: msg });
                    }
                );
            }
        });
    };

    if (!filename) {
        if (readOnly) {
            return <span className="text-color-secondary text-sm">{__('— non caricato —', 'gepafin')}</span>;
        }
        return (
            <>
                <Button
                    icon={uploading ? 'pi pi-spin pi-spinner' : 'pi pi-upload'}
                    label={compact ? null : __('Carica', 'gepafin')}
                    className={compact ? 'p-button-sm p-button-text' : 'p-button-sm p-button-outlined'}
                    disabled={uploading}
                    onClick={triggerPick}
                    tooltip={__('Carica PDF/JPG/PNG (max 15 MB)', 'gepafin')}
                    tooltipOptions={{ position: 'top' }}
                />
                <input type="file" ref={inputRef} accept={ACCEPT}
                       style={{ display: 'none' }} onChange={onFileChange} />
            </>
        );
    }

    return (
        <div className="flex align-items-center gap-1" style={{ flexWrap: 'nowrap' }}>
            <div className="flex align-items-center" style={{ minWidth: 0, flex: 1 }}>
                <i className="pi pi-file-pdf text-primary mr-1" />
                <span className="text-sm" style={{
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 200
                }} title={filename}>
                    {filename}
                </span>
                {sizeBytes ? <span className="text-color-secondary text-xs ml-1">({formatSize(sizeBytes)})</span> : null}
            </div>
            <Button icon="pi pi-eye" className="p-button-text p-button-sm"
                    tooltip={__('Anteprima', 'gepafin')} tooltipOptions={{ position: 'top' }}
                    onClick={() => onPreview && onPreview()} />
            <Button icon="pi pi-download" className="p-button-text p-button-sm"
                    tooltip={__('Scarica', 'gepafin')} tooltipOptions={{ position: 'top' }}
                    onClick={onDownloadClick} />
            {!readOnly && (
                <>
                    <Button icon="pi pi-refresh" className="p-button-text p-button-sm p-button-secondary"
                            tooltip={__('Sostituisci', 'gepafin')} tooltipOptions={{ position: 'top' }}
                            disabled={uploading} onClick={triggerPick} />
                    <Button icon="pi pi-trash" className="p-button-text p-button-sm p-button-danger"
                            tooltip={__('Elimina', 'gepafin')} tooltipOptions={{ position: 'top' }}
                            disabled={uploading} onClick={onDeleteClick} />
                    <input type="file" ref={inputRef} accept={ACCEPT}
                           style={{ display: 'none' }} onChange={onFileChange} />
                </>
            )}
        </div>
    );
};

export default FileUploadCell;
