import React, { useState } from 'react';

// prime
import { Card } from 'primereact/card';
import { Button } from 'primereact/button';
import { InputText } from 'primereact/inputtext';
import { InputTextarea } from 'primereact/inputtextarea';
import { Dropdown } from 'primereact/dropdown';
import { InputNumber } from 'primereact/inputnumber';
import { Checkbox } from 'primereact/checkbox';
import { Tag } from 'primereact/tag';
import { Divider } from 'primereact/divider';
import { Message } from 'primereact/message';
import { Accordion, AccordionTab } from 'primereact/accordion';
import { confirmDialog } from 'primereact/confirmdialog';

const FIELD_TYPE_OPTIONS = [
    { label: 'Testo libero', value: 'text' },
    { label: 'Email', value: 'email' },
    { label: 'Data', value: 'date' },
    { label: 'Checkbox (si/no)', value: 'checkbox' },
    { label: 'Scelta singola (radio)', value: 'radio' },
    { label: 'Menu a tendina (enum)', value: 'enum' },
    { label: 'Si/No con nota', value: 'yes_no_with_note' }
];

/**
 * Editor della struttura questions_snapshot di un template AR1.
 *
 * Props:
 *   value: { quadri: [...], variant, legal_ref, ... }
 *   onChange: (newValue) => void
 *
 * Permette:
 *  - Modificare metadati snapshot (variant_label, variant_description, legal_ref, normative_frame)
 *  - Modificare per ogni quadro: id, title, description
 *  - Aggiungere/rimuovere/modificare fields con tipo, label, required, pattern, max_length, options, prefill_from
 *  - Per Quadro G (is_legal_frame=true): warning visuale + editor del description
 *  - Per Quadri B (row_type=titolare): edit row_fields separato
 *  - Per Quadri C/D (nested_full): edit fields nested
 *  - Aggiungere/rimuovere quadri interi
 */
const QuadriStructureEditor = ({ value, onChange }) => {
    const qs = value || { quadri: [] };
    const quadri = qs.quadri || [];

    const update = (newQs) => onChange(newQs);

    // --- metadati snapshot ---
    const updateMeta = (key, v) => update({ ...qs, [key]: v });

    // --- quadri ---
    const updateQuadro = (idx, partial) => {
        const newQuadri = quadri.map((q, i) => i === idx ? { ...q, ...partial } : q);
        update({ ...qs, quadri: newQuadri });
    };

    const moveQuadro = (idx, direction) => {
        const newIdx = idx + direction;
        if (newIdx < 0 || newIdx >= quadri.length) return;
        const newQuadri = [...quadri];
        [newQuadri[idx], newQuadri[newIdx]] = [newQuadri[newIdx], newQuadri[idx]];
        update({ ...qs, quadri: newQuadri });
    };

    const removeQuadro = (idx) => {
        const q = quadri[idx];
        confirmDialog({
            message: `Eliminare il quadro "${q.id} - ${q.title}"? Sara creata una nuova versione.`,
            header: 'Conferma eliminazione quadro',
            icon: 'pi pi-exclamation-triangle',
            acceptLabel: 'Elimina',
            rejectLabel: 'Annulla',
            acceptClassName: 'p-button-danger',
            accept: () => {
                const newQuadri = quadri.filter((_, i) => i !== idx);
                update({ ...qs, quadri: newQuadri });
            }
        });
    };

    const addQuadro = () => {
        const nextLetter = String.fromCharCode(65 + quadri.length); // A, B, C...
        const newQuadro = {
            id: nextLetter,
            title: `Quadro ${nextLetter} - Nuovo quadro`,
            description: '',
            fields: []
        };
        update({ ...qs, quadri: [...quadri, newQuadro] });
    };

    // --- fields dentro quadro ---
    const updateField = (qIdx, fIdx, partial) => {
        const q = quadri[qIdx];
        const newFields = (q.fields || []).map((f, i) => i === fIdx ? { ...f, ...partial } : f);
        updateQuadro(qIdx, { fields: newFields });
    };

    const addField = (qIdx) => {
        const q = quadri[qIdx];
        const fields = q.fields || [];
        // id basato su letter quadro + numero crescente per evitare collisioni
        const newField = {
            id: `campo_${q.id || 'X'}_${fields.length + 1}`.toLowerCase(),
            type: 'text',
            label: 'Nuovo campo',
            required: false
        };
        updateQuadro(qIdx, { fields: [...fields, newField] });
    };

    const removeField = (qIdx, fIdx) => {
        const q = quadri[qIdx];
        const newFields = (q.fields || []).filter((_, i) => i !== fIdx);
        updateQuadro(qIdx, { fields: newFields });
    };

    const moveField = (qIdx, fIdx, direction) => {
        const q = quadri[qIdx];
        const fields = q.fields || [];
        const newIdx = fIdx + direction;
        if (newIdx < 0 || newIdx >= fields.length) return;
        const newFields = [...fields];
        [newFields[fIdx], newFields[newIdx]] = [newFields[newIdx], newFields[fIdx]];
        updateQuadro(qIdx, { fields: newFields });
    };

    // --- row_fields (es. Quadro B titolari) ---
    const updateRowField = (qIdx, fIdx, partial) => {
        const q = quadri[qIdx];
        const newRowFields = (q.row_fields || []).map((f, i) => i === fIdx ? { ...f, ...partial } : f);
        updateQuadro(qIdx, { row_fields: newRowFields });
    };

    const addRowField = (qIdx) => {
        const q = quadri[qIdx];
        const rowFields = q.row_fields || [];
        updateQuadro(qIdx, {
            row_fields: [...rowFields, { id: `campo_${rowFields.length + 1}`, type: 'text', label: 'Nuovo campo', required: false }]
        });
    };

    const removeRowField = (qIdx, fIdx) => {
        const q = quadri[qIdx];
        updateQuadro(qIdx, { row_fields: (q.row_fields || []).filter((_, i) => i !== fIdx) });
    };

    // --- nested fields (es. Quadro C/D) ---
    const updateNestedField = (qIdx, fIdx, partial) => {
        const q = quadri[qIdx];
        const nested = q.nested_full || {};
        const newNestedFields = (nested.fields || []).map((f, i) => i === fIdx ? { ...f, ...partial } : f);
        updateQuadro(qIdx, { nested_full: { ...nested, fields: newNestedFields } });
    };

    const addNestedField = (qIdx) => {
        const q = quadri[qIdx];
        const nested = q.nested_full || { fields: [] };
        const fields = nested.fields || [];
        updateQuadro(qIdx, {
            nested_full: {
                ...nested,
                fields: [...fields, { id: `campo_${fields.length + 1}`, type: 'text', label: 'Nuovo campo', required: false }]
            }
        });
    };

    const removeNestedField = (qIdx, fIdx) => {
        const q = quadri[qIdx];
        const nested = q.nested_full || {};
        updateQuadro(qIdx, {
            nested_full: { ...nested, fields: (nested.fields || []).filter((_, i) => i !== fIdx) }
        });
    };

    // ----- render field editor (atom) -----
    const renderFieldRow = (field, idx, onUpdate, onRemove, onMoveUp, onMoveDown, total) => {
        const isEnum = field.type === 'enum' || field.type === 'radio';
        return (
            <div key={idx} style={{
                border: '1px solid #ddd', borderRadius: 4, padding: 10,
                marginBottom: 8, background: '#fafafa'
            }}>
                <div style={{ display: 'grid', gridTemplateColumns: '160px 1fr 160px auto', gap: 8, alignItems: 'end' }}>
                    <div>
                        <label style={{ fontSize: 11, color: '#555' }}>ID (kebab, no spazi)</label>
                        <InputText value={field.id || ''}
                            onChange={(e) => onUpdate({ id: e.target.value.replace(/\s+/g, '_') })}
                            style={{ width: '100%', fontFamily: 'monospace', fontSize: 12 }} />
                    </div>
                    <div>
                        <label style={{ fontSize: 11, color: '#555' }}>Label visualizzato</label>
                        <InputText value={field.label || ''}
                            onChange={(e) => onUpdate({ label: e.target.value })}
                            style={{ width: '100%' }} />
                    </div>
                    <div>
                        <label style={{ fontSize: 11, color: '#555' }}>Tipo</label>
                        <Dropdown value={field.type || 'text'} options={FIELD_TYPE_OPTIONS}
                            onChange={(e) => onUpdate({ type: e.value })}
                            style={{ width: '100%' }} />
                    </div>
                    <div style={{ display: 'flex', gap: 4 }}>
                        <Button icon="pi pi-arrow-up" rounded outlined size="small"
                            disabled={idx === 0} onClick={() => onMoveUp()} tooltip="Sposta su" />
                        <Button icon="pi pi-arrow-down" rounded outlined size="small"
                            disabled={idx === total - 1} onClick={() => onMoveDown && onMoveDown()} tooltip="Sposta giu" />
                        <Button icon="pi pi-trash" rounded outlined size="small" severity="danger"
                            onClick={() => onRemove()} tooltip="Elimina campo" />
                    </div>
                </div>

                <div style={{ display: 'flex', gap: 16, marginTop: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <Checkbox inputId={`req_${idx}_${field.id}`} checked={!!field.required}
                            onChange={(e) => onUpdate({ required: e.checked })} />
                        <label htmlFor={`req_${idx}_${field.id}`} style={{ fontSize: 12 }}>Obbligatorio</label>
                    </div>

                    {field.type === 'text' && (
                        <>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                                <label style={{ fontSize: 11, color: '#555' }}>Max lunghezza:</label>
                                <InputNumber value={field.max_length || null}
                                    onValueChange={(e) => onUpdate({ max_length: e.value })}
                                    style={{ width: 90 }} inputStyle={{ fontSize: 12 }} />
                            </div>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                                <label style={{ fontSize: 11, color: '#555' }}>Pattern regex:</label>
                                <InputText value={field.pattern || ''}
                                    onChange={(e) => onUpdate({ pattern: e.target.value || undefined })}
                                    style={{ width: 180, fontFamily: 'monospace', fontSize: 11 }}
                                    placeholder="es. ^[0-9]{11}$" />
                            </div>
                        </>
                    )}

                    {field.prefill_from && (
                        <Tag severity="info" value={`prefill: ${field.prefill_from}`} style={{ fontSize: 11 }} />
                    )}
                </div>

                {isEnum && (
                    <div style={{ marginTop: 8 }}>
                        <label style={{ fontSize: 11, color: '#555', display: 'block', marginBottom: 2 }}>
                            Opzioni (una per riga)
                        </label>
                        <InputTextarea rows={3}
                            value={(field.options || []).map(o => typeof o === 'string' ? o : (o.label || o.value || '')).join('\n')}
                            onChange={(e) => {
                                const opts = e.target.value.split('\n').filter(Boolean);
                                onUpdate({ options: opts });
                            }}
                            style={{ width: '100%', fontSize: 12 }} />
                    </div>
                )}
            </div>
        );
    };

    // ----- render -----
    return (
        <div>
            <Message severity="warn" style={{ marginBottom: 14 }}
                text="Attenzione: modifiche alla struttura dei quadri generano automaticamente una nuova versione del template. I form gia compilati continuano a usare la versione precedente grazie allo snapshot." />

            {/* Metadati */}
            <Card title="Metadati template" style={{ marginBottom: 14 }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                    <div>
                        <label style={{ fontSize: 11, color: '#555' }}>Etichetta variante</label>
                        <InputText value={qs.variant_label || ''}
                            onChange={(e) => updateMeta('variant_label', e.target.value)} style={{ width: '100%' }} />
                    </div>
                    <div>
                        <label style={{ fontSize: 11, color: '#555' }}>Riferimento normativo</label>
                        <InputText value={qs.legal_ref || ''}
                            onChange={(e) => updateMeta('legal_ref', e.target.value)} style={{ width: '100%' }}
                            placeholder="es. D.Lgs. 231/2007" />
                    </div>
                    <div style={{ gridColumn: '1 / -1' }}>
                        <label style={{ fontSize: 11, color: '#555' }}>Descrizione variante</label>
                        <InputTextarea rows={2} value={qs.variant_description || ''}
                            onChange={(e) => updateMeta('variant_description', e.target.value)} style={{ width: '100%' }} />
                    </div>
                    <div style={{ gridColumn: '1 / -1' }}>
                        <label style={{ fontSize: 11, color: '#555' }}>Cornice normativa (testo completo)</label>
                        <InputTextarea rows={3} value={qs.normative_frame || ''}
                            onChange={(e) => updateMeta('normative_frame', e.target.value)}
                            style={{ width: '100%', fontSize: 12 }} />
                    </div>
                </div>
            </Card>

            {/* Quadri */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                <h3 style={{ margin: 0 }}>Quadri ({quadri.length})</h3>
                <Button label="Aggiungi quadro" icon="pi pi-plus" size="small" outlined onClick={addQuadro} />
            </div>

            <Accordion multiple>
                {quadri.map((q, qIdx) => (
                    <AccordionTab key={qIdx}
                        header={
                            <div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
                                <Tag value={q.id || '?'} severity={q.is_legal_frame ? 'warning' : 'info'} />
                                <strong style={{ flex: 1 }}>{q.title || '(senza titolo)'}</strong>
                                {q.is_legal_frame && <Tag value="NORMATIVO" severity="warning" />}
                                {q.row_type && <Tag value={`ripetuto (${q.row_type})`} severity="secondary" />}
                                {q.nested_full && <Tag value="annidato" severity="secondary" />}
                                <small style={{ color: '#888' }}>
                                    {(q.fields || []).length} campi
                                    {q.row_fields ? ` +${q.row_fields.length} riga` : ''}
                                    {q.nested_full?.fields ? ` +${q.nested_full.fields.length} nidif.` : ''}
                                </small>
                            </div>
                        }>
                        <div style={{ display: 'grid', gridTemplateColumns: '140px 1fr 1fr auto', gap: 8, alignItems: 'end', marginBottom: 10 }}>
                            <div>
                                <label style={{ fontSize: 11, color: '#555' }}>ID quadro</label>
                                <InputText value={q.id || ''}
                                    onChange={(e) => updateQuadro(qIdx, { id: e.target.value.toUpperCase() })}
                                    style={{ width: '100%', fontFamily: 'monospace' }} maxLength={4} />
                            </div>
                            <div style={{ gridColumn: 'span 2' }}>
                                <label style={{ fontSize: 11, color: '#555' }}>Titolo</label>
                                <InputText value={q.title || ''}
                                    onChange={(e) => updateQuadro(qIdx, { title: e.target.value })}
                                    style={{ width: '100%' }} />
                            </div>
                            <div style={{ display: 'flex', gap: 4 }}>
                                <Button icon="pi pi-arrow-up" rounded outlined size="small"
                                    disabled={qIdx === 0} onClick={() => moveQuadro(qIdx, -1)} tooltip="Su" />
                                <Button icon="pi pi-arrow-down" rounded outlined size="small"
                                    disabled={qIdx === quadri.length - 1} onClick={() => moveQuadro(qIdx, 1)} tooltip="Giu" />
                                <Button icon="pi pi-trash" rounded outlined size="small" severity="danger"
                                    onClick={() => removeQuadro(qIdx)} tooltip="Elimina quadro" />
                            </div>
                        </div>

                        <div style={{ marginBottom: 10 }}>
                            <label style={{ fontSize: 11, color: '#555' }}>Descrizione</label>
                            <InputTextarea rows={2} value={q.description || ''}
                                onChange={(e) => updateQuadro(qIdx, { description: e.target.value })}
                                style={{ width: '100%' }} />
                        </div>

                        {q.is_legal_frame && (
                            <Message severity="error" style={{ marginBottom: 10 }}
                                text="Quadro normativo (D.Lgs. 231/2007). Il testo dichiara responsabilita legali del firmatario. Modifica con massima cautela: il contenuto viene inserito nel PDF firmato dal beneficiario." />
                        )}

                        {/* Fields normali — sempre mostrato, anche se q.fields non esiste (Quadri B/F/G) */}
                        <>
                            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                                <strong style={{ fontSize: 13 }}>Campi ({(q.fields || []).length})</strong>
                                <Button label="Aggiungi campo" icon="pi pi-plus" size="small" outlined
                                    onClick={() => addField(qIdx)} />
                            </div>
                            {(q.fields || []).map((f, fIdx) =>
                                renderFieldRow(f, fIdx,
                                    (p) => updateField(qIdx, fIdx, p),
                                    () => removeField(qIdx, fIdx),
                                    () => moveField(qIdx, fIdx, -1),
                                    () => moveField(qIdx, fIdx, 1),
                                    (q.fields || []).length
                                )
                            )}
                            {(!q.fields || q.fields.length === 0) && (
                                <p style={{ color: '#888', fontStyle: 'italic', textAlign: 'center', fontSize: 12 }}>
                                    Nessun campo diretto. Aggiungine uno col bottone qui sopra
                                    {q.row_type ? ` (o usa i "Campi riga" qui sotto per i ${q.row_type})` : ''}
                                    {q.nested_full ? ' (o usa i "Campi annidati" qui sotto)' : ''}
                                    .
                                </p>
                            )}
                        </>

                        {/* Row fields (Quadro B titolari) */}
                        {q.row_type && (
                            <>
                                <Divider />
                                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                                    <strong style={{ fontSize: 13 }}>Campi riga (per ogni {q.row_type}): ({(q.row_fields || []).length})</strong>
                                    <Button label="Aggiungi campo riga" icon="pi pi-plus" size="small" outlined
                                        onClick={() => addRowField(qIdx)} />
                                </div>
                                <Message severity="info" style={{ marginBottom: 8, fontSize: 12 }}
                                    text={`Questi campi si ripetono per ogni ${q.row_type} aggiunto dal beneficiario. Non eliminare il row_type se ci sono form gia compilati.`} />
                                {(q.row_fields || []).map((f, fIdx) =>
                                    renderFieldRow(f, fIdx,
                                        (p) => updateRowField(qIdx, fIdx, p),
                                        () => removeRowField(qIdx, fIdx),
                                        () => {}, () => {},
                                        (q.row_fields || []).length
                                    )
                                )}
                            </>
                        )}

                        {/* Nested full (Quadro C/D rappresentante/esecutore) */}
                        {q.nested_full && (
                            <>
                                <Divider />
                                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                                    <strong style={{ fontSize: 13 }}>Campi annidati: ({(q.nested_full.fields || []).length})</strong>
                                    <Button label="Aggiungi campo annidato" icon="pi pi-plus" size="small" outlined
                                        onClick={() => addNestedField(qIdx)} />
                                </div>
                                {(q.nested_full.fields || []).map((f, fIdx) =>
                                    renderFieldRow(f, fIdx,
                                        (p) => updateNestedField(qIdx, fIdx, p),
                                        () => removeNestedField(qIdx, fIdx),
                                        () => {}, () => {},
                                        (q.nested_full.fields || []).length
                                    )
                                )}
                            </>
                        )}

                        {/* Upload slots info (Quadro F) */}
                        {q.upload_slots && (
                            <>
                                <Divider />
                                <strong style={{ fontSize: 13 }}>Slot upload:</strong>
                                <div style={{ marginTop: 4 }}>
                                    {q.upload_slots.map((slot, i) => (
                                        <Tag key={i} value={slot.label || slot.id} severity="secondary" style={{ marginRight: 4 }} />
                                    ))}
                                </div>
                                <small style={{ color: '#888' }}>Gli slot upload sono gestiti dal modello: modifica avanzata non ancora via UI.</small>
                            </>
                        )}
                    </AccordionTab>
                ))}
            </Accordion>
        </div>
    );
};

export default QuadriStructureEditor;
