import React, { useEffect, useRef, useState } from 'react';
import { __ } from '@wordpress/i18n';
import { useNavigate, useParams } from 'react-router-dom';

import { Card } from 'primereact/card';
import { Button } from 'primereact/button';
import { Toast } from 'primereact/toast';
import { FileUpload } from 'primereact/fileupload';
import { Message } from 'primereact/message';
import { ProgressSpinner } from 'primereact/progressspinner';

import Ar1Service from '../service/ar1Service';
import Ar1StatusTag from '../components/Ar1StatusTag';

/**
 * Pagina firma AR1.
 * URL: /ar1/signature/:formId
 *
 * Flusso: genera PDF → download unsigned → firma FEQ client side → upload signed → DocVerify.
 */
const Ar1Signature = () => {
    const { formId } = useParams();
    const navigate = useNavigate();
    const toast = useRef(null);

    const [form, setForm] = useState(null);
    const [loading, setLoading] = useState(true);
    const [generating, setGenerating] = useState(false);
    const [uploading, setUploading] = useState(false);
    const [uploadAttempt, setUploadAttempt] = useState(0);
    const fileUploadRef = useRef(null);

    const resetUploadInput = () => {
        try { fileUploadRef.current?.clear?.(); } catch (_) {}
        setUploadAttempt(n => n + 1);
    };

    const refreshForm = () => {
        Ar1Service.getForm(formId,
            (resp) => { setForm(resp); setLoading(false); },
            (err) => {
                setLoading(false);
                if (toast.current) toast.current.show({ severity: 'error', summary: 'Errore', detail: err?.detail || 'Form non trovato' });
            }
        );
    };

    useEffect(() => { if (formId) refreshForm(); /* eslint-disable-next-line */ }, [formId]);

    const handleGeneratePdf = () => {
        setGenerating(true);
        Ar1Service.generatePdf(formId,
            () => {
                setGenerating(false);
                refreshForm();
                if (toast.current) toast.current.show({ severity: 'success', summary: 'OK', detail: 'PDF generato' });
            },
            (err) => {
                setGenerating(false);
                if (toast.current) toast.current.show({ severity: 'error', summary: 'Errore', detail: err?.detail || 'Generazione PDF fallita' });
            }
        );
    };

    const handleDownloadUnsigned = async () => {
        try {
            const blob = await Ar1Service.downloadPdfUnsigned(formId);
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `AR1_${form.variant}_da-firmare.pdf`;
            a.click();
            URL.revokeObjectURL(url);
        } catch (e) {
            if (toast.current) toast.current.show({ severity: 'error', summary: 'Errore', detail: e.message });
        }
    };

    const [uploadRecap, setUploadRecap] = useState(null);

    const handleUploadSigned = (event) => {
        setUploadRecap(null);
        const file = event.files?.[0];
        if (!file) return;

        const ext = file.name.toLowerCase().slice(file.name.lastIndexOf('.'));
        if (ext !== '.pdf' && ext !== '.p7m') {
            if (toast.current) toast.current.show({ severity: 'warn', summary: 'Formato non valido', detail: 'Accettati: .pdf (PAdES) o .p7m (CAdES)' });
            resetUploadInput();
            return;
        }

        setUploading(true);
        if (toast.current) toast.current.show({ severity: 'info', summary: 'Verifica in corso...', detail: 'Analisi firma digitale (fino a 60 secondi)' });

        Ar1Service.uploadSignature(formId, file,
            (resp) => {
                setUploading(false);
                resetUploadInput();
                refreshForm();
                const outcome = resp?.outcome;
                const sig = resp?.signature || {};
                const recapByOutcome = {
                    VERIFIED: { severity: 'success', title: __('Firma verificata', 'gepafin'), body: __('La dichiarazione e stata archiviata automaticamente nei tuoi documenti aziendali.', 'gepafin') },
                    SIGNED_NOT_VERIFIED: { severity: 'warn', title: __('Firma accettata — verifica manuale', 'gepafin'), body: __('La firma e presente ma richiede verifica manuale da parte dell\'istruttore.', 'gepafin') },
                    SIGNED_DOCVERIFY_UNAVAILABLE: { severity: 'warn', title: __('Firma accettata — verifica rimandata', 'gepafin'), body: __('Servizio di verifica momentaneamente non disponibile. L\'istruttore verifichera la firma manualmente.', 'gepafin') }
                };
                const r = recapByOutcome[outcome];
                if (r) setUploadRecap({ ...r, outcome, signerName: sig.signer_name, signerCf: sig.signer_cf, method: sig.method });
            },
            (err) => {
                setUploading(false);
                resetUploadInput();
                if (err?.detail?.code === 'NO_SIGNATURE_DETECTED') {
                    setUploadRecap({
                        severity: 'error', outcome: 'NO_SIGNATURE_DETECTED',
                        title: __('Firma non rilevata', 'gepafin'),
                        body: __('Il file caricato non contiene una firma digitale valida. Firmare il PDF con il proprio strumento FEQ (CAdES .p7m o PAdES) e ricaricarlo.', 'gepafin')
                    });
                } else {
                    setUploadRecap({
                        severity: 'error', outcome: 'UPLOAD_ERROR',
                        title: __('Errore', 'gepafin'),
                        body: typeof err?.detail === 'string' ? err.detail : (err?.detail?.message || __('Upload fallito', 'gepafin'))
                    });
                }
            }
        );
    };

    if (loading) return <div style={{ textAlign: 'center', padding: 40 }}><ProgressSpinner /></div>;
    if (!form) return <div style={{ padding: 20 }}><Message severity="error" text={__('Form non trovato', 'gepafin')} /></div>;

    const hasUnsignedPdf = !!form.pdf_unsigned_path;
    const hasSignedPdf = !!form.pdf_signed_path;
    const canUploadSig = form.status === 'AWAITING_SIGNATURE';
    const isDone = ['VERIFIED', 'SIGNED'].includes(form.status);

    return (
        <div style={{ padding: 16, maxWidth: 900, margin: '0 auto' }}>
            <Toast ref={toast} />
            <h1>{__('Firma AR1', 'gepafin')} — {form.variant}</h1>
            <div style={{ marginBottom: 20 }}><Ar1StatusTag status={form.status} /></div>

            {uploadRecap && (
                <Message severity={uploadRecap.severity} style={{ marginBottom: 14, display: 'block' }} content={
                    <div style={{ width: '100%' }}>
                        <b>{uploadRecap.title}</b>
                        <div style={{ marginTop: 4 }}>{uploadRecap.body}</div>
                        {(uploadRecap.signerName || uploadRecap.signerCf || uploadRecap.method) && (
                            <div style={{ marginTop: 6, fontSize: '0.9em' }}>
                                {uploadRecap.signerName && <span>{__('Firmatario', 'gepafin')}: <b>{uploadRecap.signerName}</b>{' '}</span>}
                                {uploadRecap.signerCf && <span>({uploadRecap.signerCf}){' '}</span>}
                                {uploadRecap.method && <span>— {uploadRecap.method}</span>}
                            </div>
                        )}
                        {uploadRecap.outcome === 'VERIFIED' && (
                            <div style={{ marginTop: 10 }}>
                                <Button label={__('Torna ai documenti', 'gepafin')} icon="pi pi-arrow-left" size="small" onClick={() => navigate('/ar1')} />
                            </div>
                        )}
                    </div>
                } />
            )}

            <Card title={__('1. Scarica il modulo AR1 da firmare', 'gepafin')} style={{ marginBottom: 14 }}>
                {!hasUnsignedPdf && (
                    <div>
                        <p>{__('Il PDF del tuo modulo AR1 non e ancora stato generato.', 'gepafin')}</p>
                        <Button label={__('Genera PDF', 'gepafin')} icon="pi pi-file-pdf" onClick={handleGeneratePdf} loading={generating} />
                    </div>
                )}
                {hasUnsignedPdf && (
                    <div>
                        <p>{__('Scarica il PDF, firmalo con il tuo strumento FEQ (CNS, Aruba, Namirial, Dike) e ricaricalo qui sotto.', 'gepafin')}</p>
                        <Button label={__('Scarica PDF', 'gepafin')} icon="pi pi-download" onClick={handleDownloadUnsigned} outlined />
                        {!isDone && (
                            <Button label={__('Rigenera PDF', 'gepafin')} icon="pi pi-refresh" text onClick={handleGeneratePdf} loading={generating} style={{ marginLeft: 8 }} />
                        )}
                    </div>
                )}
            </Card>

            <Card title={__('2. Carica il PDF firmato', 'gepafin')} style={{ marginBottom: 14 }}>
                {!canUploadSig && !isDone && (
                    <Message severity="warn" text={__(`Il modulo non e in stato AWAITING_SIGNATURE (attuale: ${form.status})`, 'gepafin')} />
                )}
                {canUploadSig && (
                    <div>
                        <p>{__('Formati accettati: PDF con firma PAdES oppure file .p7m (CAdES). Dimensione massima 50 MB.', 'gepafin')}</p>
                        <FileUpload
                            ref={fileUploadRef}
                            key={uploadAttempt}
                            name="file"
                            mode="basic"
                            accept=".pdf,.p7m"
                            maxFileSize={50 * 1024 * 1024}
                            customUpload
                            uploadHandler={handleUploadSigned}
                            auto
                            chooseLabel={uploading ? __('Verifica in corso...', 'gepafin') : __('Seleziona PDF firmato', 'gepafin')}
                            disabled={uploading}
                        />
                    </div>
                )}
                {isDone && (
                    <div>
                        <Message severity="success" text={
                            form.status === 'VERIFIED'
                                ? __('Firma verificata con successo. La dichiarazione e archiviata nei tuoi documenti aziendali.', 'gepafin')
                                : __('Firma accettata. Potrebbe richiedere verifica manuale.', 'gepafin')
                        } style={{ marginBottom: 12 }} />
                        {hasSignedPdf && (
                            <Button label={__('Scarica PDF firmato', 'gepafin')} icon="pi pi-download" onClick={async () => {
                                try {
                                    const blob = await Ar1Service.downloadPdfSigned(formId);
                                    const url = URL.createObjectURL(blob);
                                    const a = document.createElement('a');
                                    a.href = url;
                                    a.download = `AR1_${form.variant}_signed${form.pdf_signed_path?.endsWith('.p7m') ? '.p7m' : '.pdf'}`;
                                    a.click();
                                    URL.revokeObjectURL(url);
                                } catch (e) {
                                    if (toast.current) toast.current.show({ severity: 'error', summary: 'Errore', detail: e.message });
                                }
                            }} outlined />
                        )}
                    </div>
                )}
            </Card>

            {form.signature_verified_at && (
                <Card title={__('Dettagli verifica', 'gepafin')}>
                    <p><strong>{__('Firmatario:', 'gepafin')}</strong> {form.signature_signer_name || '—'}</p>
                    <p><strong>{__('Codice fiscale:', 'gepafin')}</strong> {form.signature_signer_cf || '—'}</p>
                    <p><strong>{__('Metodo:', 'gepafin')}</strong> {form.signature_type || '—'}</p>
                    <p><strong>{__('Verificato il:', 'gepafin')}</strong> {new Date(form.signature_verified_at).toLocaleString('it-IT')}</p>
                    <p><strong>{__('Scade il:', 'gepafin')}</strong> {form.expires_at ? new Date(form.expires_at).toLocaleDateString('it-IT') : '—'}</p>
                </Card>
            )}

            <div style={{ marginTop: 20, textAlign: 'center' }}>
                <Button label={__('Torna alla Home AR1', 'gepafin')} severity="secondary" outlined onClick={() => navigate('/ar1')} />
            </div>
        </div>
    );
};

export default Ar1Signature;
