// Extracted Data Form Component
const { useState, useEffect } = React;

const ExtractedDataForm = ({ projectId, project, onUpdate }) => {
    const toast = useToast();
    const [saving, setSaving] = useState(false);
    const [expandedSections, setExpandedSections] = useState({
        personal: true,
        residence: true,
        document: true,
    });

    // Local state for form data
    const [personalData, setPersonalData] = useState({});
    const [residenceData, setResidenceData] = useState({});
    const [idDocument, setIdDocument] = useState({});

    // Initialize form data from project
    useEffect(() => {
        setPersonalData(project?.personal_data || {});
        setResidenceData(project?.residence_data || {});
        setIdDocument(project?.id_document || {});
    }, [project?.personal_data, project?.residence_data, project?.id_document]);

    const toggleSection = (section) => {
        setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
    };

    const handleSave = async () => {
        setSaving(true);
        try {
            await window.ApiUtils.updateExtractedData(projectId, {
                personal_data: personalData,
                residence_data: residenceData,
                id_document: idDocument,
            });
            toast('Dati salvati con successo', 'success');
            onUpdate?.();
        } catch (error) {
            toast(error.message || 'Errore durante il salvataggio', 'error');
        } finally {
            setSaving(false);
        }
    };

    const SectionHeader = ({ title, icon, section, isExpanded }) => (
        <button
            type="button"
            onClick={() => toggleSection(section)}
            className="w-full flex items-center justify-between p-2 bg-slate-50 rounded-lg hover:bg-slate-100 transition-colors"
        >
            <div className="flex items-center gap-1.5">
                <span className="text-sm">{icon}</span>
                <h4 className="text-xs font-medium text-slate-900">{title}</h4>
            </div>
            <svg
                className={`w-4 h-4 text-slate-500 transition-transform ${isExpanded ? 'rotate-180' : ''}`}
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
            >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
            </svg>
        </button>
    );

    return (
        <div className="space-y-2">
            {/* Personal Data Section */}
            <div className="border border-slate-200 rounded-lg overflow-hidden">
                <SectionHeader
                    title="Dati Anagrafici"
                    icon="👤"
                    section="personal"
                    isExpanded={expandedSections.personal}
                />
                {expandedSections.personal && (
                    <div className="p-2 space-y-2">
                        <div className="grid grid-cols-2 gap-2">
                            <Input
                                label="Cognome"
                                size="sm"
                                value={personalData.last_name || ''}
                                onChange={e => setPersonalData(prev => ({ ...prev, last_name: e.target.value }))}
                            />
                            <Input
                                label="Nome"
                                size="sm"
                                value={personalData.first_name || ''}
                                onChange={e => setPersonalData(prev => ({ ...prev, first_name: e.target.value }))}
                            />
                        </div>
                        <div className="grid grid-cols-2 gap-2">
                            <Input
                                label="Data di Nascita"
                                size="sm"
                                placeholder="DD/MM/YYYY"
                                value={personalData.date_of_birth || ''}
                                onChange={e => setPersonalData(prev => ({ ...prev, date_of_birth: e.target.value }))}
                            />
                            <Select
                                label="Sesso"
                                size="sm"
                                options={window.GENDERS || []}
                                value={personalData.gender || ''}
                                onChange={e => setPersonalData(prev => ({ ...prev, gender: e.target.value }))}
                            />
                        </div>
                        <Input
                            label="Codice Fiscale"
                            size="sm"
                            value={personalData.fiscal_code || ''}
                            onChange={e => setPersonalData(prev => ({ ...prev, fiscal_code: e.target.value.toUpperCase() }))}
                        />
                        <div className="grid grid-cols-2 gap-2">
                            <Input
                                label="Comune di Nascita"
                                size="sm"
                                value={personalData.birth_city || ''}
                                onChange={e => setPersonalData(prev => ({ ...prev, birth_city: e.target.value }))}
                            />
                            <Select
                                label="Provincia"
                                size="sm"
                                options={window.ITALIAN_PROVINCES || []}
                                value={personalData.birth_province || ''}
                                onChange={e => setPersonalData(prev => ({ ...prev, birth_province: e.target.value }))}
                            />
                        </div>
                        <Select
                            label="Nazione di Nascita"
                            size="sm"
                            options={window.NATIONS || []}
                            value={personalData.birth_nation || ''}
                            onChange={e => setPersonalData(prev => ({ ...prev, birth_nation: e.target.value }))}
                        />
                    </div>
                )}
            </div>

            {/* Residence Data Section */}
            <div className="border border-slate-200 rounded-lg overflow-hidden">
                <SectionHeader
                    title="Dati di Residenza"
                    icon="🏠"
                    section="residence"
                    isExpanded={expandedSections.residence}
                />
                {expandedSections.residence && (
                    <div className="p-2 space-y-2">
                        <Input
                            label="Indirizzo"
                            size="sm"
                            value={residenceData.address || ''}
                            onChange={e => setResidenceData(prev => ({ ...prev, address: e.target.value }))}
                        />
                        <div className="grid grid-cols-2 gap-2">
                            <Input
                                label="Numero Civico"
                                size="sm"
                                value={residenceData.number || ''}
                                onChange={e => setResidenceData(prev => ({ ...prev, number: e.target.value }))}
                            />
                            <Input
                                label="CAP"
                                size="sm"
                                value={residenceData.cap || ''}
                                onChange={e => setResidenceData(prev => ({ ...prev, cap: e.target.value }))}
                            />
                        </div>
                        <div className="grid grid-cols-2 gap-2">
                            <Input
                                label="Comune"
                                size="sm"
                                value={residenceData.city || ''}
                                onChange={e => setResidenceData(prev => ({ ...prev, city: e.target.value }))}
                            />
                            <Select
                                label="Provincia"
                                size="sm"
                                options={window.ITALIAN_PROVINCES || []}
                                value={residenceData.province || ''}
                                onChange={e => setResidenceData(prev => ({ ...prev, province: e.target.value }))}
                            />
                        </div>
                        <Select
                            label="Nazione"
                            size="sm"
                            options={window.NATIONS || []}
                            value={residenceData.nation || ''}
                            onChange={e => setResidenceData(prev => ({ ...prev, nation: e.target.value }))}
                        />
                    </div>
                )}
            </div>

            {/* ID Document Section */}
            <div className="border border-slate-200 rounded-lg overflow-hidden">
                <SectionHeader
                    title="Documento"
                    icon="🪪"
                    section="document"
                    isExpanded={expandedSections.document}
                />
                {expandedSections.document && (
                    <div className="p-2 space-y-2">
                        <div className="grid grid-cols-2 gap-2">
                            <Select
                                label="Tipo"
                                size="sm"
                                options={window.DOCUMENT_TYPES || []}
                                value={idDocument.type || ''}
                                onChange={e => setIdDocument(prev => ({ ...prev, type: e.target.value }))}
                            />
                            <Input
                                label="Numero"
                                size="sm"
                                value={idDocument.number || ''}
                                onChange={e => setIdDocument(prev => ({ ...prev, number: e.target.value.toUpperCase() }))}
                            />
                        </div>
                        <div className="grid grid-cols-2 gap-2">
                            <Input
                                label="Data Rilascio"
                                size="sm"
                                placeholder="DD/MM/YYYY"
                                value={idDocument.start_date || ''}
                                onChange={e => setIdDocument(prev => ({ ...prev, start_date: e.target.value }))}
                            />
                            <Input
                                label="Data Scadenza"
                                size="sm"
                                placeholder="DD/MM/YYYY"
                                value={idDocument.end_date || ''}
                                onChange={e => setIdDocument(prev => ({ ...prev, end_date: e.target.value }))}
                            />
                        </div>
                        <div className="grid grid-cols-2 gap-2">
                            <Input
                                label="Comune Rilascio"
                                size="sm"
                                value={idDocument.release_city || ''}
                                onChange={e => setIdDocument(prev => ({ ...prev, release_city: e.target.value }))}
                            />
                            <Select
                                label="Provincia"
                                size="sm"
                                options={window.ITALIAN_PROVINCES || []}
                                value={idDocument.release_province || ''}
                                onChange={e => setIdDocument(prev => ({ ...prev, release_province: e.target.value }))}
                            />
                        </div>
                        <Select
                            label="Ente di Rilascio"
                            size="sm"
                            options={window.RELEASE_ENTITIES || []}
                            value={idDocument.release_entity || ''}
                            onChange={e => setIdDocument(prev => ({ ...prev, release_entity: e.target.value }))}
                        />
                    </div>
                )}
            </div>

            {/* Save Button */}
            <button
                onClick={handleSave}
                disabled={saving}
                className="w-full flex items-center justify-center gap-1.5 px-3 py-2 bg-brand-500 text-white text-xs font-medium rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
                {saving ? (
                    <>
                        <Spinner size="sm" />
                        <span>Salvataggio...</span>
                    </>
                ) : (
                    <>
                        <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                        </svg>
                        <span>Salva Modifiche</span>
                    </>
                )}
            </button>
        </div>
    );
};

window.ExtractedDataForm = ExtractedDataForm;
