import React, { useEffect, useMemo, 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 { InputText } from 'primereact/inputtext';
import { InputTextarea } from 'primereact/inputtextarea';
import { Calendar } from 'primereact/calendar';
import { RadioButton } from 'primereact/radiobutton';
import { Checkbox } from 'primereact/checkbox';
import { Dropdown } from 'primereact/dropdown';
import { Toast } from 'primereact/toast';
import { Steps } from 'primereact/steps';
import { ProgressSpinner } from 'primereact/progressspinner';
import { Message } from 'primereact/message';
import { FileUpload } from 'primereact/fileupload';

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

/**
 * Wizard data-driven: legge schema_snapshot del form e genera step/field dinamicamente.
 * Uno step per quadro. Auto-save onBlur via PUT /quadri.
 *
 * URL: /ar1/wizard/:formId
 */
const Ar1Wizard = () => {
    const { formId } = useParams();
    const navigate = useNavigate();
    const toast = useRef(null);

    const [form, setForm] = useState(null);
    const [quadriValues, setQuadriValues] = useState({});
    const [loading, setLoading] = useState(true);
    const [activeIndex, setActiveIndex] = useState(0);
    const [saving, setSaving] = useState(false);
    const [submitting, setSubmitting] = useState(false);

    const quadri = useMemo(
        () => (form?.schema_snapshot?.quadri || []).filter(q => !q.is_legal_frame),
        [form]
    );

    const [stepErrors, setStepErrors] = useState([]);
    const [authExpired, setAuthExpired] = useState(false);
    const authExpiredRef = useRef(false);
    const [draftNotice, setDraftNotice] = useState(null);

    // --- Validazione client obbligatori (specchio di app/validation.py BE) ---
    const isEmptyVal = (v) => {
        if (v === null || v === undefined) return true;
        if (typeof v === 'string') return v.trim() === '';
        if (Array.isArray(v)) return v.length === 0;
        if (typeof v === 'object') {
            if ('value' in v) return isEmptyVal(v.value);
            return Object.values(v).every(isEmptyVal);
        }
        return false;
    };

    // show_if formati seed: "campo == 'VALORE'", "campo == true", "campo != true"
    const evalShowIf = (expr, quadroData) => {
        if (!expr) return true;
        const m = String(expr).match(/^\s*(\w+)\s*(==|!=)\s*(?:'(.*)'|(true|false))\s*$/);
        if (!m) return true; // formato ignoto: non nascondere mai per errore
        const raw = (quadroData || {})[m[1]];
        const val = raw && typeof raw === 'object' && 'value' in raw ? raw.value : raw;
        const target = m[4] !== undefined ? (m[4] === 'true') : m[3];
        const eq = m[4] !== undefined ? (!!val === target) : (String(val ?? '') === target);
        return m[2] === '==' ? eq : !eq;
    };
    const isFieldVisible = (field, quadroData) => evalShowIf(field.show_if, quadroData);

    const validateQuadro = (quadro, data) => {
        const errs = [];
        const d = data || {};
        if (!quadro || quadro.is_legal_frame) return errs;
        if (quadro.row_type) {
            const rows = d.rows || [];
            if (rows.length === 0) {
                errs.push(`Quadro ${quadro.id}: obbligatoria almeno una riga di dati`);
                return errs;
            }
            rows.forEach((row, i) => {
                (quadro.row_fields || []).forEach(f => {
                    if (f.required && !f.show_if && isEmptyVal((row || {})[f.id])) {
                        errs.push(`Quadro ${quadro.id} (riga ${i + 1}): ${f.label}`);
                    }
                });
            });
            return errs;
        }
        (quadro.upload_slots || []).forEach(sl => {
            if (sl.required && isEmptyVal(d[sl.id])) errs.push(`Quadro ${quadro.id}: allegato obbligatorio — ${sl.label}`);
        });
        (quadro.fields || []).forEach(f => {
            if (f.required && isFieldVisible(f, d) && isEmptyVal(d[f.id])) errs.push(`Quadro ${quadro.id}: ${f.label}`);
        });
        if (quadro.nested_full && evalShowIf(quadro.nested_full.show_if, d)) {
            const nd = d.nested || {};
            (quadro.nested_full.fields || []).forEach(f => {
                if (f.required && isFieldVisible(f, nd) && isEmptyVal(nd[f.id])) errs.push(`Quadro ${quadro.id} (dettaglio): ${f.label}`);
            });
        }
        return errs;
    };

    // Valida tutti i quadri in [from, to): al salto in avanti nessun quadro
    // intermedio puo essere incompleto (report test 4/7/2026 P1)
    const validateRange = (fromIdx, toIdx) => {
        for (let i = fromIdx; i < toIdx; i++) {
            const q = quadri[i];
            const errs = validateQuadro(q, quadriValues[q.id]);
            if (errs.length) return { errs, badIndex: i };
        }
        return null;
    };

    // detail BE puo essere stringa o {message, errors[]} (validazione 422)
    const errDetail = (err) => {
        const d = err?.detail;
        if (d && typeof d === 'object') {
            const list = (d.errors || []).slice(0, 5).join('; ');
            return `${d.message || 'Errore'}${list ? ': ' + list : ''}`;
        }
        return d || 'Errore';
    };

    // JWT scaduto durante la compilazione: bozza in localStorage + avviso persistente
    const backupDraft = () => {
        try {
            localStorage.setItem(`ar1_draft_${formId}`, JSON.stringify({ ts: Date.now(), quadri: quadriValues }));
        } catch (e) { /* quota o private mode: pazienza */ }
    };
    const handleAuthExpired = () => {
        backupDraft();
        if (authExpiredRef.current) return; // banner unico, niente pile di avvisi (P6)
        authExpiredRef.current = true;
        setAuthExpired(true);
    };

    useEffect(() => {
        if (!formId) return;
        Ar1Service.getForm(formId,
            (resp) => {
                setForm(resp);
                let initial = resp.quadri || {};
                try {
                    const raw = localStorage.getItem(`ar1_draft_${formId}`);
                    if (raw && resp.status === 'DRAFT') {
                        const draft = JSON.parse(raw);
                        if (draft && draft.quadri) {
                            initial = { ...initial, ...draft.quadri };
                            setDraftNotice(__('Bozza recuperata: ripristinati i dati non salvati della sessione precedente.', 'gepafin'));
                        }
                    }
                } catch (e) { /* draft corrotto: ignora */ }
                setQuadriValues(initial);
                setLoading(false);
            },
            (err) => {
                setLoading(false);
                if (toast.current) toast.current.show({ severity: 'error', summary: 'Errore', detail: err?.detail || 'Form non trovato' });
            }
        );
    }, [formId]);

    const isReadonly = form && form.status !== 'DRAFT';

    const saveQuadro = (quadroId) => {
        if (isReadonly) return;
        if (authExpiredRef.current) { backupDraft(); return; } // 401 gia noto: solo backup locale
        const patch = { [quadroId]: quadriValues[quadroId] || {} };
        setSaving(true);
        Ar1Service.updateQuadri(formId, patch,
            (resp) => {
                setSaving(false); setForm(resp);
                try { localStorage.removeItem(`ar1_draft_${formId}`); } catch (e) { /* noop */ }
            },
            (err) => {
                setSaving(false);
                if (err?.status === 401) { handleAuthExpired(); return; }
                backupDraft();
                if (toast.current) toast.current.show({ severity: 'warn', summary: 'Save fallito', detail: errDetail(err) });
            }
        );
    };

    const handleFieldChange = (quadroId, fieldId, value) => {
        setQuadriValues(prev => ({
            ...prev,
            [quadroId]: { ...(prev[quadroId] || {}), [fieldId]: value }
        }));
    };

    const handleRowFieldChange = (quadroId, rowIndex, fieldId, value) => {
        setQuadriValues(prev => {
            const q = prev[quadroId] || { rows: [] };
            const rows = [...(q.rows || [])];
            rows[rowIndex] = { ...(rows[rowIndex] || {}), [fieldId]: value };
            return { ...prev, [quadroId]: { ...q, rows } };
        });
    };

    const addRow = (quadroId, maxRows) => {
        setQuadriValues(prev => {
            const q = prev[quadroId] || { rows: [] };
            if ((q.rows || []).length >= maxRows) return prev;
            return { ...prev, [quadroId]: { ...q, rows: [...(q.rows || []), {}] } };
        });
    };

    const removeRow = (quadroId, rowIndex) => {
        setQuadriValues(prev => {
            const q = prev[quadroId] || { rows: [] };
            const rows = (q.rows || []).filter((_, i) => i !== rowIndex);
            return { ...prev, [quadroId]: { ...q, rows } };
        });
    };

    const submitFinale = () => {
        if (!activeQuadro) return;
        // Gate client: tutti i quadri obbligatori completi prima della firma
        const allErrs = [];
        let firstBadIndex = -1;
        quadri.forEach((q, i) => {
            const errs = validateQuadro(q, quadriValues[q.id]);
            if (errs.length && firstBadIndex === -1) firstBadIndex = i;
            allErrs.push(...errs);
        });
        if (allErrs.length) {
            setStepErrors(allErrs);
            if (firstBadIndex >= 0) setActiveIndex(firstBadIndex);
            if (toast.current) toast.current.show({ severity: 'warn', summary: __('Quadri obbligatori incompleti', 'gepafin'), detail: allErrs.slice(0, 4).join(' — '), life: 8000 });
            return;
        }
        setStepErrors([]);
        setSubmitting(true);
        const patch = { [activeQuadro.id]: quadriValues[activeQuadro.id] || {} };
        Ar1Service.updateQuadri(formId, patch,
            () => {
                Ar1Service.submitForSignature(formId,
                    () => {
                        setSubmitting(false);
                        try { localStorage.removeItem(`ar1_draft_${formId}`); } catch (e) { /* noop */ }
                        if (toast.current) toast.current.show({ severity: 'success', summary: 'OK', detail: 'Modulo pronto per la firma' });
                        setTimeout(() => navigate(`/ar1/signature/${formId}`), 600);
                    },
                    (err) => {
                        setSubmitting(false);
                        if (err?.status === 401) { handleAuthExpired(); return; }
                        const beErrs = (err?.detail && typeof err.detail === 'object' && err.detail.errors) || [];
                        if (beErrs.length) setStepErrors(beErrs);
                        if (toast.current) toast.current.show({ severity: 'error', summary: 'Errore', detail: errDetail(err) });
                    }
                );
            },
            (err) => {
                setSubmitting(false);
                if (err?.status === 401) { handleAuthExpired(); return; }
                if (toast.current) toast.current.show({ severity: 'error', summary: 'Errore', detail: errDetail(err) });
            }
        );
    };

    const renderField = (field, value, onChange, path = '') => {
        const key = `${path}-${field.id}`;
        const disabled = isReadonly;
        const req = field.required ? ' *' : '';
        const commonLabel = <label htmlFor={key} style={{ display: 'block', marginBottom: 4, fontWeight: 500 }}>{field.label}{req}</label>;

        switch (field.type) {
            case 'text':
            case 'email':
                return (
                    <div key={key} style={{ marginBottom: 14 }}>
                        {commonLabel}
                        <InputText
                            id={key}
                            value={value || ''}
                            onChange={(e) => onChange(field.id, field.uppercase ? e.target.value.toUpperCase() : e.target.value)}
                            disabled={disabled}
                            maxLength={field.max_length}
                            placeholder={field.placeholder}
                            style={{ width: '100%' }}
                        />
                        {field.legal_ref && <small style={{ color: '#888' }}>{field.legal_ref}</small>}
                    </div>
                );
            case 'textarea':
                return (
                    <div key={key} style={{ marginBottom: 14 }}>
                        {commonLabel}
                        <InputTextarea id={key} value={value || ''} onChange={(e) => onChange(field.id, e.target.value)} disabled={disabled} rows={3} maxLength={field.max_length} style={{ width: '100%' }} />
                    </div>
                );
            case 'date':
                return (
                    <div key={key} style={{ marginBottom: 14 }}>
                        {commonLabel}
                        <Calendar id={key} value={value ? new Date(value) : null} onChange={(e) => onChange(field.id, e.value ? e.value.toISOString().slice(0, 10) : null)} disabled={disabled} dateFormat="dd/mm/yy" showIcon style={{ width: '100%' }} />
                    </div>
                );
            case 'checkbox':
                return (
                    <div key={key} style={{ marginBottom: 14, display: 'flex', alignItems: 'center', gap: 8 }}>
                        <Checkbox inputId={key} checked={!!value} onChange={(e) => onChange(field.id, e.checked)} disabled={disabled} />
                        <label htmlFor={key}>{field.label}</label>
                    </div>
                );
            case 'radio':
                return (
                    <div key={key} style={{ marginBottom: 14 }}>
                        {commonLabel}
                        {(field.options || []).map((opt, idx) => {
                            const optVal = typeof opt === 'string' ? opt : opt.value;
                            const optLabel = typeof opt === 'string' ? opt : opt.label;
                            const rid = `${key}-opt-${idx}`;
                            return (
                                <div key={rid} style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                                    <RadioButton inputId={rid} value={optVal} checked={value === optVal} onChange={(e) => onChange(field.id, e.value)} disabled={disabled} />
                                    <label htmlFor={rid}>{optLabel}</label>
                                </div>
                            );
                        })}
                    </div>
                );
            case 'enum':
                return (
                    <div key={key} style={{ marginBottom: 14 }}>
                        {commonLabel}
                        <Dropdown id={key} value={value} options={(field.options || []).map(o => ({ label: o.replace(/_/g, ' '), value: o }))} onChange={(e) => onChange(field.id, e.value)} disabled={disabled} style={{ width: '100%' }} showClear />
                    </div>
                );
            case 'yes_no_with_note': {
                const v = typeof value === 'object' && value ? value : {};
                const yes = v.value === 'si' || v.value === 'yes' || v.value === 'true';
                const no = v.value === 'no' || v.value === 'false';
                return (
                    <div key={key} style={{ marginBottom: 14, padding: 10, background: '#fafafa', borderLeft: '3px solid #003d7a' }}>
                        {commonLabel}
                        {field.legal_ref && <small style={{ color: '#888', display: 'block', marginBottom: 6 }}>{field.legal_ref}</small>}
                        <div style={{ display: 'flex', gap: 16, marginBottom: 8 }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                                <RadioButton inputId={`${key}-yes`} checked={yes} onChange={() => onChange(field.id, { ...v, value: 'si' })} disabled={disabled} />
                                <label htmlFor={`${key}-yes`}>{__('Si', 'gepafin')}</label>
                            </div>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                                <RadioButton inputId={`${key}-no`} checked={no} onChange={() => onChange(field.id, { value: 'no' })} disabled={disabled} />
                                <label htmlFor={`${key}-no`}>{__('No', 'gepafin')}</label>
                            </div>
                        </div>
                        {yes && (
                            <InputTextarea
                                value={v.note || ''}
                                onChange={(e) => onChange(field.id, { ...v, note: e.target.value })}
                                disabled={disabled}
                                rows={2}
                                placeholder={field.note_label || __('Specificare', 'gepafin')}
                                style={{ width: '100%' }}
                            />
                        )}
                    </div>
                );
            }
            default:
                return (
                    <div key={key} style={{ marginBottom: 14 }}>
                        {commonLabel}
                        <InputText value={value || ''} onChange={(e) => onChange(field.id, e.target.value)} disabled={disabled} style={{ width: '100%' }} />
                    </div>
                );
        }
    };

    const renderQuadro = (quadro) => {
        const q = quadriValues[quadro.id] || {};

        if (quadro.upload_slots) {
            return (
                <div>
                    <h3>{quadro.title}</h3>
                    {quadro.description && <p style={{ color: '#666' }}>{quadro.description}</p>}
                    <Message severity="info" text={__('Carica qui i documenti richiesti. Il PDF firmato dell\'AR1 verra archiviato automaticamente nei tuoi documenti aziendali.', 'gepafin')} style={{ marginBottom: 14 }} />
                    {quadro.upload_slots.map(slot => (
                        <div key={slot.id} style={{ marginBottom: 14, padding: 10, border: '1px solid #ddd', borderRadius: 4 }}>
                            <label style={{ fontWeight: 500 }}>{slot.label}{slot.required ? ' *' : ''}</label>
                            {q[slot.id]?.filename ? (
                                <div style={{ marginTop: 6, display: 'flex', alignItems: 'center', gap: 8, padding: 8, background: '#f0f7ff', border: '1px solid #b3d4f0', borderRadius: 4 }}>
                                    <i className="pi pi-file" style={{ color: '#003d7a' }} />
                                    <span style={{ flex: 1, wordBreak: 'break-all' }}>{q[slot.id].filename}</span>
                                    <Button
                                        icon="pi pi-times"
                                        label={__('Rimuovi', 'gepafin')}
                                        severity="danger"
                                        outlined
                                        size="small"
                                        disabled={isReadonly}
                                        onClick={() => handleFieldChange(quadro.id, slot.id, null)}
                                    />
                                </div>
                            ) : (
                                <FileUpload
                                    name={slot.id}
                                    mode="basic"
                                    accept={(slot.accept || []).join(',')}
                                    maxFileSize={(slot.max_size_mb || 300) * 1024 * 1024}
                                    disabled={isReadonly}
                                    customUpload
                                    uploadHandler={(e) => {
                                        const file = e.files[0];
                                        handleFieldChange(quadro.id, slot.id, { filename: file.name, size: file.size });
                                        if (toast.current) toast.current.show({ severity: 'info', summary: 'File selezionato', detail: file.name });
                                    }}
                                    auto
                                    chooseLabel={__('Scegli file', 'gepafin')}
                                    style={{ marginTop: 6 }}
                                />
                            )}
                        </div>
                    ))}
                </div>
            );
        }

        if (quadro.row_type) {
            const rows = q.rows || [];
            return (
                <div>
                    <h3>{quadro.title}</h3>
                    {quadro.description && <p style={{ color: '#666' }}>{quadro.description}</p>}
                    {rows.map((row, idx) => (
                        <Card key={idx} title={`${quadro.row_type.replace(/_/g, ' ').toUpperCase()} #${idx + 1}`} style={{ marginBottom: 12 }}>
                            {(quadro.row_fields || []).map(field => renderField(field, row[field.id], (fid, val) => handleRowFieldChange(quadro.id, idx, fid, val), `q-${quadro.id}-row-${idx}`))}
                            {!isReadonly && (
                                <Button label={__('Rimuovi', 'gepafin')} severity="danger" outlined icon="pi pi-trash" size="small" onClick={() => removeRow(quadro.id, idx)} />
                            )}
                        </Card>
                    ))}
                    {!isReadonly && rows.length < (quadro.max_rows || 4) && (
                        <Button label={__('Aggiungi', 'gepafin')} icon="pi pi-plus" outlined onClick={() => addRow(quadro.id, quadro.max_rows || 4)} />
                    )}
                </div>
            );
        }

        return (
            <div>
                <h3>{quadro.title}</h3>
                {quadro.description && <p style={{ color: '#666' }}>{quadro.description}</p>}
                {(quadro.fields || []).filter(field => isFieldVisible(field, q)).map(field => renderField(field, q[field.id], (fid, val) => handleFieldChange(quadro.id, fid, val), `q-${quadro.id}`))}
                {quadro.nested_full && evalShowIf(quadro.nested_full.show_if, q) && (
                    <div style={{ marginTop: 16, padding: 12, background: '#f5f5f5', borderRadius: 4 }}>
                        <h4 style={{ marginTop: 0 }}>{__('Dettaglio aggiuntivo', 'gepafin')}</h4>
                        {(quadro.nested_full.fields || []).map(field => renderField(
                            field,
                            (q.nested || {})[field.id],
                            (fid, val) => handleFieldChange(quadro.id, 'nested', { ...((q.nested) || {}), [fid]: val }),
                            `q-${quadro.id}-nested`
                        ))}
                    </div>
                )}
            </div>
        );
    };

    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>;
    if (quadri.length === 0) return <div style={{ padding: 20 }}><Message severity="warn" text={__('Nessun quadro editabile nel template. Contattare il supporto.', 'gepafin')} /></div>;

    const steps = quadri.map(q => ({ label: q.id }));
    // clamp activeIndex: difensivo se quadri cambia lunghezza o e fuori range
    const safeIndex = quadri.length === 0 ? 0 : Math.max(0, Math.min(activeIndex, quadri.length - 1));
    const activeQuadro = quadri[safeIndex];
    const isLastStep = safeIndex === quadri.length - 1;

    return (
        <div style={{ padding: 16 }}>
            <Toast ref={toast} />
            <h1>{__('Compilazione AR1', 'gepafin')} — {form.variant}</h1>
            {isReadonly && (
                <Message severity="info" text={__(`Form in stato ${form.status} — sola lettura`, 'gepafin')} style={{ marginBottom: 14 }} />
            )}

            <Steps
                model={steps}
                activeIndex={safeIndex}
                onSelect={(e) => {
                    const next = Math.max(0, Math.min(e.index, quadri.length - 1));
                    if (!isReadonly && next > safeIndex) {
                        const bad = validateRange(safeIndex, next);
                        if (bad) {
                            setStepErrors(bad.errs);
                            setActiveIndex(bad.badIndex);
                            if (toast.current) toast.current.show({ severity: 'warn', summary: __('Campi obbligatori mancanti', 'gepafin'), detail: bad.errs.slice(0, 3).join(' — '), life: 6000 });
                            return;
                        }
                        setStepErrors([]);
                    }
                    if (!isReadonly && activeQuadro) saveQuadro(activeQuadro.id);
                    setActiveIndex(next);
                }}
                readOnly={false}
                style={{ marginBottom: 20 }}
            />

            {authExpired && (
                <Message severity="warn" style={{ marginBottom: 14, display: 'block' }} content={
                    <div>
                        <b>{__('Sessione scaduta', 'gepafin')}</b>
                        <div style={{ marginTop: 4 }}>{__('Il salvataggio automatico e sospeso: i dati compilati sono conservati in questo browser. Effettua di nuovo il login e riapri il modulo per recuperarli e continuare.', 'gepafin')}</div>
                    </div>
                } />
            )}
            {draftNotice && !authExpired && (
                <Message severity="info" style={{ marginBottom: 14, display: 'block' }} content={
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
                        <span>{draftNotice}</span>
                        <Button icon="pi pi-times" text size="small" onClick={() => setDraftNotice(null)} />
                    </div>
                } />
            )}
            {stepErrors.length > 0 && (
                <Message severity="warn" style={{ marginBottom: 14, display: 'block' }} content={
                    <div>
                        <b>{__('Campi obbligatori mancanti', 'gepafin')}:</b>
                        <ul style={{ margin: '6px 0 0 0', paddingLeft: 18 }}>
                            {stepErrors.slice(0, 10).map((e, i) => <li key={i}>{e}</li>)}
                            {stepErrors.length > 10 && <li>{__('...e altri', 'gepafin')} {stepErrors.length - 10}</li>}
                        </ul>
                    </div>
                } />
            )}
            <Card style={{ marginBottom: 14 }} onBlur={() => { if (!isReadonly && activeQuadro) saveQuadro(activeQuadro.id); }}>
                {activeQuadro && renderQuadro(activeQuadro)}
            </Card>

            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <Button label={__('Indietro', 'gepafin')} icon="pi pi-arrow-left" severity="secondary" outlined disabled={activeIndex === 0}
                    onClick={() => {
                        setStepErrors([]);
                        if (!isReadonly && activeQuadro) saveQuadro(activeQuadro.id);
                        setActiveIndex(Math.max(0, activeIndex - 1));
                    }}
                />
                <div style={{ display: 'flex', gap: 8 }}>
                    {saving && <span style={{ color: '#888' }}>{__('Salvataggio...', 'gepafin')}</span>}
                    {!isLastStep && (
                        <Button label={__('Avanti', 'gepafin')} icon="pi pi-arrow-right" iconPos="right"
                            onClick={() => {
                                if (!isReadonly) {
                                    const errs = validateQuadro(activeQuadro, quadriValues[activeQuadro.id]);
                                    if (errs.length) {
                                        setStepErrors(errs);
                                        if (toast.current) toast.current.show({ severity: 'warn', summary: __('Campi obbligatori mancanti', 'gepafin'), detail: errs.slice(0, 3).join(' — '), life: 6000 });
                                        return;
                                    }
                                    setStepErrors([]);
                                    saveQuadro(activeQuadro.id);
                                }
                                setActiveIndex(Math.min(quadri.length - 1, activeIndex + 1));
                            }}
                        />
                    )}
                    {isLastStep && !isReadonly && (
                        <Button label={__('Procedi alla firma', 'gepafin')} icon="pi pi-verified" severity="warning" loading={submitting} onClick={submitFinale} />
                    )}
                </div>
            </div>
        </div>
    );
};

export default Ar1Wizard;
