// New Registration View Component
const { useState, useEffect } = React;

const NewRegistrationView = ({ emailSettings, setEmailSettings, onJobAdded, prepopulatedData, onClearPrepopulated }) => {
    const toast = useToast();
    const [personalData, setPersonalData] = useState({});
    const [crifMode, setCrifMode] = useState(false);
    const [crifOnly, setCrifOnly] = useState(false);
    const [existingEmail, setExistingEmail] = useState('');
    const [submitting, setSubmitting] = useState(false);
    const [showUpload, setShowUpload] = useState(false);
    const [loadingSample, setLoadingSample] = useState(false);
    const [linkedProjectId, setLinkedProjectId] = useState(null);
    const [linkedProjectName, setLinkedProjectName] = useState(null);

    const { DATI_ANAGRAFICI_FIELDS, DATI_RESIDENZA_FIELDS, DOCUMENTO_FIELDS, FORM_SECTIONS } = FormConstants;
    const { fetchRandomSample } = ApiUtils;

    // Load prepopulated data when it arrives from a project
    useEffect(() => {
        if (prepopulatedData) {
            const data = prepopulatedData.personalData || {};
            setPersonalData(data);
            setLinkedProjectId(prepopulatedData.projectId);
            setLinkedProjectName(prepopulatedData.projectName);
            // Enable CRIF mode if residence or document data is present
            const hasResidenceData = data.address || data.residence_city;
            const hasDocumentData = data.document_type || data.document_number;
            if (hasResidenceData && hasDocumentData) {
                setCrifMode(true);
            }
            toast(`Dati caricati da pratica: ${prepopulatedData.projectName}`, 'info');
        } else {
            // Reset state when prepopulated data is cleared
            setLinkedProjectId(null);
            setLinkedProjectName(null);
        }
    }, [prepopulatedData]);

    // Clear linked project when unmounting
    useEffect(() => {
        return () => {
            if (onClearPrepopulated) onClearPrepopulated();
        };
    }, []);

    const handleFieldChange = (key, value) => {
        setPersonalData(prev => ({ ...prev, [key]: value }));
    };

    const loadSample = (sample) => {
        setPersonalData(sample.personal_data);
        setEmailSettings(prev => ({
            ...prev,
            mail_provider: sample.additional_data.mail_provider || 'virgilio',
            phone_number: sample.additional_data.phone_number || '',
            email: sample.additional_data.email || ''
        }));
        setCrifMode(sample.additional_data.crif_mode || false);
        toast(`Caricato: ${sample.label}`, 'info');
    };

    const loadRandomSample = async (forCrif = true) => {
        setLoadingSample(true);
        try {
            const sample = await fetchRandomSample(forCrif);
            if (sample) {
                loadSample(sample);
            } else {
                toast('Errore nel caricamento dati casuali', 'error');
            }
        } catch (error) {
            toast(`Errore: ${error.message}`, 'error');
        } finally {
            setLoadingSample(false);
        }
    };

    const handleSubmit = async () => {
        // Validate basic personal data fields
        const missing = DATI_ANAGRAFICI_FIELDS.filter(f => f.required && !personalData[f.key]).map(f => f.label);
        if (missing.length > 0) { toast(`Campi mancanti: ${missing.join(', ')}`, 'error'); return; }

        // Validate CRIF fields for both CRIF mode and CRIF-only mode
        if (crifMode || crifOnly) {
            const missingRes = DATI_RESIDENZA_FIELDS.filter(f => f.required && !personalData[f.key]).map(f => f.label);
            const missingDoc = DOCUMENTO_FIELDS.filter(f => f.required && !personalData[f.key]).map(f => f.label);
            if (missingRes.length + missingDoc.length > 0) { toast(`Campi CRIF mancanti: ${[...missingRes, ...missingDoc].join(', ')}`, 'error'); return; }
        }

        // For CRIF-only mode: require existing email, don't require phone/recovery email
        if (crifOnly) {
            if (!existingEmail || !existingEmail.trim()) {
                toast('Email esistente obbligatoria per modalità Solo CRIF', 'error');
                return;
            }
        } else {
            // For email creation modes: require phone and recovery email
            if (!emailSettings.phone_number) { toast('Numero di telefono obbligatorio', 'error'); return; }
            if (!emailSettings.email) { toast('Email di recupero obbligatoria', 'error'); return; }
        }

        setSubmitting(true);
        try {
            // Build additional_data with optional project link
            const additionalData = {
                ...emailSettings,
                crif_mode: crifMode && !crifOnly, // crif_mode is false when crif_only is true
                crif_only: crifOnly,
                existing_email: crifOnly ? existingEmail.trim() : undefined,
            };
            if (linkedProjectId) {
                additionalData.project_id = linkedProjectId;
                additionalData.project_name = linkedProjectName;
            }

            const payload = { personal_data: personalData, additional_data: additionalData };

            const response = await fetch('/queue/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const data = await response.json();
            if (response.ok && data.status === 'success') {
                const modeLabel = crifOnly ? '(Solo CRIF)' : crifMode ? '(Email + CRIF)' : '(Solo Email)';
                const msg = linkedProjectId
                    ? `Lavoro #${data.job_id} ${modeLabel} collegato alla pratica!`
                    : `Lavoro #${data.job_id} ${modeLabel} aggiunto alla coda!`;
                toast(msg, 'success');
                setPersonalData({});
                setCrifMode(false);
                setCrifOnly(false);
                setExistingEmail('');
                setLinkedProjectId(null);
                setLinkedProjectName(null);
                setEmailSettings({ mail_provider: 'virgilio', phone_number: '', email: '' });
                onJobAdded?.();
            } else {
                toast(data.detail || 'Errore durante l\'aggiunta', 'error');
            }
        } catch (error) {
            toast(`Errore: ${error.message}`, 'error');
        } finally {
            setSubmitting(false);
        }
    };

    // Handle unlinking from project
    const handleUnlink = () => {
        setLinkedProjectId(null);
        setLinkedProjectName(null);
        if (onClearPrepopulated) onClearPrepopulated();
    };

    return (
        <div className="p-8 space-y-6 max-w-5xl">
            {/* Project Link Banner */}
            {linkedProjectId && (
                <Card className="p-4 bg-blue-50 border-blue-200">
                    <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                            <span className="text-blue-600">🔗</span>
                            <span className="text-sm font-medium text-blue-800">
                                Collegato a pratica: {linkedProjectName}
                            </span>
                        </div>
                        <button
                            onClick={handleUnlink}
                            className="text-xs text-blue-600 hover:text-blue-800 underline"
                        >
                            Scollega
                        </button>
                    </div>
                    <p className="text-xs text-blue-600 mt-1">
                        I risultati della registrazione saranno salvati automaticamente sulla pratica.
                    </p>
                </Card>
            )}

            {/* Quick Load */}
            <Card className="p-4">
                <div className="flex items-center gap-4 flex-wrap">
                    <span className="text-sm font-medium text-slate-600">🧪 Genera Dati Casuali:</span>
                    <Button variant="ghost" size="sm" onClick={() => loadRandomSample(true)} disabled={loadingSample}>
                        {loadingSample ? <><Spinner className="w-3 h-3" /> Generazione...</> : '🎲 Persona Casuale (CRIF)'}
                    </Button>
                    <Button variant="ghost" size="sm" onClick={() => loadRandomSample(false)} disabled={loadingSample}>
                        {loadingSample ? <><Spinner className="w-3 h-3" /> Generazione...</> : '🎲 Persona Casuale (Email)'}
                    </Button>
                </div>
            </Card>

            {/* Job Mode Selector */}
            <Card className="p-6">
                <h3 className="font-semibold text-slate-900 mb-4 flex items-center gap-2">
                    <span>⚙️</span> Modalità Lavoro
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    {/* Email Only */}
                    <div
                        className={`p-4 rounded-lg border cursor-pointer transition-all ${!crifMode && !crifOnly ? 'bg-blue-50 border-blue-300 ring-2 ring-blue-200' : 'bg-slate-50 border-slate-200 hover:border-slate-300'}`}
                        onClick={() => { setCrifMode(false); setCrifOnly(false); }}
                    >
                        <div className="text-center">
                            <div className="text-3xl mb-2">📧</div>
                            <div className="font-semibold text-slate-900">Solo Email</div>
                            <p className="text-sm text-slate-500 mt-1">Crea solo l'account email</p>
                        </div>
                    </div>
                    {/* Email + CRIF */}
                    <div
                        className={`p-4 rounded-lg border cursor-pointer transition-all ${crifMode && !crifOnly ? 'bg-brand-50 border-brand-300 ring-2 ring-brand-200' : 'bg-slate-50 border-slate-200 hover:border-slate-300'}`}
                        onClick={() => { setCrifMode(true); setCrifOnly(false); }}
                    >
                        <div className="text-center">
                            <div className="text-3xl mb-2">📧+📊</div>
                            <div className="font-semibold text-slate-900">Email + CRIF</div>
                            <p className="text-sm text-slate-500 mt-1">Crea email e invia richiesta CRIF</p>
                        </div>
                    </div>
                    {/* CRIF Only */}
                    <div
                        className={`p-4 rounded-lg border cursor-pointer transition-all ${crifOnly ? 'bg-emerald-50 border-emerald-300 ring-2 ring-emerald-200' : 'bg-slate-50 border-slate-200 hover:border-slate-300'}`}
                        onClick={() => { setCrifMode(false); setCrifOnly(true); }}
                    >
                        <div className="text-center">
                            <div className="text-3xl mb-2">📊</div>
                            <div className="font-semibold text-slate-900">Solo CRIF</div>
                            <p className="text-sm text-slate-500 mt-1">Usa email esistente per CRIF</p>
                        </div>
                    </div>
                </div>
            </Card>

            {/* Email Settings - only show for email creation modes */}
            {!crifOnly && (
                <Card className="p-6">
                    <h3 className="font-semibold text-slate-900 mb-4 flex items-center gap-2">
                        <span>📧</span> Impostazioni Email
                    </h3>
                    <RegistrationSettings settings={emailSettings} onChange={setEmailSettings} />
                </Card>
            )}

            {/* Existing Email - only show for CRIF-only mode */}
            {crifOnly && (
                <Card className="p-6">
                    <h3 className="font-semibold text-slate-900 mb-4 flex items-center gap-2">
                        <span>📧</span> Email Esistente per CRIF
                    </h3>
                    <div className="bg-emerald-50 border border-emerald-200 rounded-lg p-3 text-sm text-emerald-700 mb-4">
                        Inserisci l'indirizzo email esistente da usare per la richiesta CRIF. Non verrà creato un nuovo account email.
                    </div>
                    <Input
                        label="Email Esistente"
                        required
                        type="email"
                        placeholder="esempio@virgilio.it"
                        value={existingEmail}
                        onChange={e => setExistingEmail(e.target.value)}
                    />
                </Card>
            )}

            {/* Form Sections */}
            <Card className="p-6 space-y-8">
                {FORM_SECTIONS.map(section => (
                    <FormSection
                        key={section.id}
                        section={section}
                        data={personalData}
                        onChange={handleFieldChange}
                        crifMode={crifMode}
                        crifOnly={crifOnly}
                    />
                ))}

                <div className="pt-4 border-t border-slate-200 flex justify-end gap-3">
                    <Button variant="secondary" onClick={() => setShowUpload(true)}>
                        📁 Carica Documento
                    </Button>
                    <Button variant="primary" size="lg" onClick={handleSubmit} disabled={submitting}>
                        {submitting ? <><Spinner /> Aggiunta...</> : <><span>✓</span> Aggiungi alla Coda</>}
                    </Button>
                </div>
            </Card>

            {/* Upload Modal */}
            {showUpload && <UploadModal onClose={() => setShowUpload(false)} onExtracted={(data) => {
                if (data.personal_data) setPersonalData(data.personal_data);
                setShowUpload(false);
            }} />}
        </div>
    );
};

window.NewRegistrationView = NewRegistrationView;

