// Job Detail Modal Component
const { useState, useEffect, useRef } = React;

const JobDetailModal = ({ job, onClose, onRetry, onJobUpdated }) => {
    const toast = useToast();
    const providers = useProviders();
    const [activeTab, setActiveTab] = useState('result');
    const [logs, setLogs] = useState([]);
    const logsEndRef = useRef();
    
    // Edit state for queued jobs
    const [personalData, setPersonalData] = useState({});
    const [additionalData, setAdditionalData] = useState({});
    const [crifMode, setCrifMode] = useState(false);
    const [crifOnly, setCrifOnly] = useState(false);
    const [existingEmail, setExistingEmail] = useState('');
    const [saving, setSaving] = useState(false);
    
    // Video state
    const [videoExists, setVideoExists] = useState(false);
    const [videoLoading, setVideoLoading] = useState(true);
    
    // Live screenshot streaming state
    const [liveScreenshot, setLiveScreenshot] = useState(null);

    const isQueued = job?.status === 'queued';
    const isCancelled = job?.status === 'cancelled';
    const isError = job?.status === 'error';
    const isRunning = job?.status === 'running';
    const canEdit = isQueued || isCancelled || isError;

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

    // Initialize edit state when job changes
    useEffect(() => {
        if (job) {
            setPersonalData(job.personal_data || {});
            setAdditionalData(job.additional_data || {});
            setCrifMode(job.additional_data?.crif_mode || false);
            setCrifOnly(job.additional_data?.crif_only || false);
            setExistingEmail(job.additional_data?.existing_email || '');
            // Default to edit tab for queued/cancelled jobs (editable)
            if (job.status === 'queued' || job.status === 'cancelled') setActiveTab('edit');
            else if (job.status === 'running') setActiveTab('logs');
            else setActiveTab('result');
        }
    }, [job]);

    // Check if video exists for this job
    useEffect(() => {
        if (!job) return;
        
        setVideoLoading(true);
        fetch(`/queue/job/${job.id}/video/exists`)
            .then(res => res.json())
            .then(data => {
                setVideoExists(data.exists);
                setVideoLoading(false);
            })
            .catch(() => {
                setVideoExists(false);
                setVideoLoading(false);
            });
    }, [job]);

    // Live screenshot streaming for running jobs
    useEffect(() => {
        if (!job || job.status !== 'running' || activeTab !== 'video') return;
        
        const es = new EventSource(`/queue/job/${job.id}/screenshots/stream`);
        es.onmessage = (e) => {
            setLiveScreenshot(e.data);
        };
        es.onerror = () => es.close();
        return () => es.close();
    }, [job, activeTab]);

    // Clear logs when job changes
    useEffect(() => {
        setLogs([]);
    }, [job?.id]);

    useEffect(() => {
        if (!job || activeTab !== 'logs') return;
        
        // Clear logs before connecting to new stream
        setLogs([]);
        
        const es = new EventSource(`/queue/job/${job.id}/logs/stream`);
        es.onmessage = (e) => {
            try { setLogs(prev => [...prev, JSON.parse(e.data)]); }
            catch (err) { console.error(err); }
        };
        es.onerror = () => es.close();
        return () => es.close();
    }, [job?.id, activeTab]);

    useEffect(() => {
        if (logsEndRef.current && activeTab === 'logs') logsEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }, [logs, activeTab]);

    if (!job) return null;

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

    const handleSave = async () => {
        // Validate required 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 (!additionalData.phone_number) { toast('Numero di telefono obbligatorio', 'error'); return; }
            if (!additionalData.email) { toast('Email di recupero obbligatoria', 'error'); return; }
        }

        setSaving(true);
        try {
            const response = await fetch(`/queue/job/${job.id}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    personal_data: personalData,
                    additional_data: {
                        ...additionalData,
                        crif_mode: crifMode && !crifOnly, // crif_mode is false when crif_only is true
                        crif_only: crifOnly,
                        existing_email: crifOnly ? existingEmail.trim() : undefined,
                    }
                })
            });
            const data = await response.json();
            if (response.ok && data.status === 'success') {
                toast('Lavoro aggiornato con successo', 'success');
                if (onJobUpdated) onJobUpdated(data.job);
                onClose();
            } else {
                toast(data.detail || 'Errore durante il salvataggio', 'error');
            }
        } catch (error) {
            toast(`Errore: ${error.message}`, 'error');
        } finally {
            setSaving(false);
        }
    };

    const isSuccess = job.result?.status === 'success';
    const hasVideo = videoExists && !videoLoading;
    const tabs = [
        { id: 'result', label: isSuccess ? '✅ Risultato' : job.status === 'error' ? '❌ Errore' : job.status === 'running' ? '⚡ Stato' : '⏳ In Coda' },
        { id: 'logs', label: '📋 Logs' },
        { id: 'video', label: isRunning ? '📺 Live' : '🎬 Video', disabled: !hasVideo && !isRunning },
        { id: 'edit', label: canEdit ? '✏️ Modifica Dati' : '📝 Dati' },
    ];

    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
            <Card className="w-full max-w-3xl m-4 max-h-[85vh] flex flex-col" onClick={e => e.stopPropagation()}>
                <div className="p-4 border-b border-slate-200 flex items-center justify-between shrink-0">
                    <div className="flex items-center gap-3">
                        <h3 className="font-semibold text-slate-900">Lavoro #{job.id?.slice(-8)}</h3>
                        {canEdit && <Badge variant="warning">Modificabile</Badge>}
                    </div>
                    <button className="text-slate-400 hover:text-slate-600 text-2xl" onClick={onClose}>×</button>
                </div>

                {/* Tabs */}
                <div className="flex border-b border-slate-200 shrink-0">
                    {tabs.map(tab => (
                        <button
                            key={tab.id}
                            onClick={() => !tab.disabled && setActiveTab(tab.id)}
                            className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
                                activeTab === tab.id ? 'border-brand-500 text-brand-600' : 
                                tab.disabled ? 'border-transparent text-slate-300 cursor-not-allowed' :
                                'border-transparent text-slate-500 hover:text-slate-700'
                            }`}
                            disabled={tab.disabled}
                        >{tab.label}</button>
                    ))}
                </div>

                <div className="p-6 overflow-y-auto flex-1">
                    {activeTab === 'result' && (
                        <div className="space-y-4">
                            {isSuccess && job.result ? (
                                <div className="space-y-3">
                                    <div className="bg-emerald-50 border border-emerald-200 rounded-lg p-4">
                                        <div className="text-emerald-700 font-medium mb-2">✓ Registrazione Completata</div>
                                        <div className="font-mono text-sm space-y-1">
                                            <div><span className="text-slate-500">Username:</span> {job.result.username}</div>
                                            <div><span className="text-slate-500">Password:</span> {job.result.password}</div>
                                        </div>
                                    </div>
                                </div>
                            ) : job.status === 'error' ? (
                                <div className="space-y-3">
                                    <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                                        <div className="text-red-700 font-medium mb-2">✕ Errore</div>
                                        <p className="text-sm text-red-600">{job.message || 'Errore sconosciuto'}</p>
                                    </div>
                                    {job.error_details && (
                                        <pre className="bg-slate-900 text-slate-100 p-4 rounded-lg text-xs overflow-x-auto">{job.error_details}</pre>
                                    )}
                                    <Button variant="primary" onClick={() => { onRetry(job.id); onClose(); }}>🔄 Riprova</Button>
                                </div>
                            ) : job.status === 'running' ? (
                                <div className="text-center py-8">
                                    <Spinner className="w-8 h-8 mx-auto text-blue-500 mb-3" />
                                    <p className="text-slate-600">{job.message || 'Elaborazione in corso...'}</p>
                                </div>
                            ) : (
                                <div className="text-center py-8">
                                    <div className="text-4xl mb-3">⏳</div>
                                    <p className="text-slate-600 font-medium">In attesa nella coda</p>
                                    <p className="text-sm text-slate-500 mt-1">Puoi modificare i dati nella scheda "Modifica Dati"</p>
                                    <Button variant="primary" className="mt-4" onClick={() => setActiveTab('edit')}>✏️ Modifica Dati</Button>
                                </div>
                            )}
                        </div>
                    )}

                    {activeTab === 'logs' && (
                        <div className="bg-slate-900 rounded-lg p-4 font-mono text-xs max-h-80 overflow-y-auto">
                            {logs.length === 0 ? (
                                <div className="text-slate-500 text-center py-4">Nessun log disponibile</div>
                            ) : logs.map((log, i) => (
                                <div key={i} className="flex gap-3 py-1">
                                    <span className="text-slate-500">{new Date(log.timestamp).toLocaleTimeString('it-IT')}</span>
                                    <span className={log.level === 'ERROR' ? 'text-red-400' : log.level === 'SUCCESS' ? 'text-emerald-400' : 'text-slate-300'}>[{log.level}]</span>
                                    <span className="text-slate-100">{log.message}</span>
                                </div>
                            ))}
                            <div ref={logsEndRef} />
                        </div>
                    )}

                    {activeTab === 'video' && (
                        <div className="space-y-4">
                            {/* Live view for running jobs */}
                            {isRunning ? (
                                <div className="space-y-3">
                                    <div className="flex items-center justify-between">
                                        <h4 className="font-medium text-slate-900 flex items-center gap-2">
                                            📺 Vista Live
                                            <Badge variant="info" className="animate-pulse">
                                                ● In Diretta
                                            </Badge>
                                        </h4>
                                        <span className="text-xs text-slate-500">Aggiornamento ogni secondo</span>
                                    </div>
                                    <div className="border border-slate-200 rounded-lg overflow-hidden bg-slate-900 relative">
                                        {liveScreenshot ? (
                                            <img 
                                                src={`data:image/jpeg;base64,${liveScreenshot}`}
                                                alt="Live view"
                                                className="w-full"
                                                style={{ maxHeight: '500px', objectFit: 'contain' }}
                                            />
                                        ) : (
                                            <div className="flex items-center justify-center py-32">
                                                <div className="text-center">
                                                    <Spinner className="w-8 h-8 mx-auto text-blue-500 mb-3" />
                                                    <p className="text-slate-400">In attesa del primo frame...</p>
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                    <p className="text-xs text-slate-500 text-center">
                                        Il video completo sarà disponibile al termine del lavoro
                                    </p>
                                </div>
                            ) : hasVideo ? (
                                <div className="space-y-3">
                                    <div className="flex items-center justify-between">
                                        <h4 className="font-medium text-slate-900 flex items-center gap-2">
                                            🎬 Registrazione Automazione
                                            <Badge variant={job.status === 'error' ? 'error' : job.status === 'completed' ? 'success' : 'info'}>
                                                {job.status === 'error' ? 'Errore' : job.status === 'completed' ? 'Completato' : 'In corso'}
                                            </Badge>
                                        </h4>
                                        <a 
                                            href={`/queue/job/${job.id}/video`}
                                            download={`video_${job.id?.slice(-8)}.webm`}
                                            className="text-sm text-brand-600 hover:text-brand-700 flex items-center gap-1"
                                            onClick={e => e.stopPropagation()}
                                        >
                                            💾 Scarica Video
                                        </a>
                                    </div>
                                    <div className="border border-slate-200 rounded-lg overflow-hidden bg-slate-900">
                                        <video 
                                            controls 
                                            className="w-full"
                                            style={{ maxHeight: '500px' }}
                                            src={`/queue/job/${job.id}/video`}
                                        >
                                            Il tuo browser non supporta la riproduzione video.
                                        </video>
                                    </div>
                                    <p className="text-xs text-slate-500 text-center">
                                        Video registrato durante l'esecuzione dell'automazione browser
                                    </p>
                                </div>
                            ) : videoLoading ? (
                                <div className="text-center py-12">
                                    <Spinner className="w-8 h-8 mx-auto text-blue-500 mb-3" />
                                    <p className="text-slate-600 font-medium">Verifica disponibilità video...</p>
                                </div>
                            ) : (
                                <div className="text-center py-12">
                                    <div className="text-4xl mb-3">🎬</div>
                                    <p className="text-slate-600 font-medium">Nessun video disponibile</p>
                                    <p className="text-sm text-slate-500 mt-1">
                                        {job.status === 'queued' ? 'Il lavoro non è ancora stato eseguito' : 'La registrazione video non è stata abilitata per questo lavoro'}
                                    </p>
                                </div>
                            )}
                        </div>
                    )}

                    {activeTab === 'edit' && (
                        <div className="space-y-6">
                            {!canEdit && (
                                <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 text-sm text-amber-700">
                                    ⚠️ Questo lavoro non può essere modificato perché è già in esecuzione o terminato.
                                </div>
                            )}

                            {/* Job Mode Selector */}
                            <div className="space-y-4">
                                <h4 className="font-semibold text-slate-900 flex items-center gap-2">⚙️ Modalità Lavoro</h4>
                                <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                                    {/* 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'} ${!canEdit ? 'opacity-60 cursor-not-allowed' : ''}`}
                                        onClick={() => canEdit && (setCrifMode(false), setCrifOnly(false))}
                                    >
                                        <div className="text-center">
                                            <div className="text-2xl mb-2">📧</div>
                                            <div className="font-medium text-slate-900">Solo Email</div>
                                            <p className="text-xs 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'} ${!canEdit ? 'opacity-60 cursor-not-allowed' : ''}`}
                                        onClick={() => canEdit && (setCrifMode(true), setCrifOnly(false))}
                                    >
                                        <div className="text-center">
                                            <div className="text-2xl mb-2">📧+📊</div>
                                            <div className="font-medium text-slate-900">Email + CRIF</div>
                                            <p className="text-xs 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'} ${!canEdit ? 'opacity-60 cursor-not-allowed' : ''}`}
                                        onClick={() => canEdit && (setCrifMode(false), setCrifOnly(true))}
                                    >
                                        <div className="text-center">
                                            <div className="text-2xl mb-2">📊</div>
                                            <div className="font-medium text-slate-900">Solo CRIF</div>
                                            <p className="text-xs text-slate-500 mt-1">Usa email esistente per CRIF</p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {/* Email Settings - only show for email creation modes */}
                            {!crifOnly && (
                                <div className="space-y-4">
                                    <h4 className="font-semibold text-slate-900 flex items-center gap-2">📧 Impostazioni Email</h4>
                                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                                        <div>
                                            <label className="block text-sm font-medium text-slate-700 mb-1">Provider Email<span className="text-red-500 ml-1">*</span></label>
                                            <select
                                                className="w-full px-3 py-2 bg-white border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
                                                value={additionalData.mail_provider || 'virgilio'}
                                                onChange={e => handleAdditionalChange('mail_provider', e.target.value)}
                                                disabled={!canEdit}
                                            >
                                                {providers.map(p => <option key={p.id} value={p.id}>{p.name} ({p.domain})</option>)}
                                            </select>
                                        </div>
                                        <Input
                                            label="Numero di Telefono"
                                            required
                                            type="tel"
                                            placeholder="+39 123 456 7890"
                                            value={additionalData.phone_number || ''}
                                            onChange={e => handleAdditionalChange('phone_number', e.target.value)}
                                            disabled={!canEdit}
                                        />
                                        <Input
                                            label="Email di Recupero"
                                            required
                                            type="email"
                                            placeholder="recupero@esempio.com"
                                            value={additionalData.email || ''}
                                            onChange={e => handleAdditionalChange('email', e.target.value)}
                                            disabled={!canEdit}
                                        />
                                    </div>
                                </div>
                            )}

                            {/* Existing Email - only show for CRIF-only mode */}
                            {crifOnly && (
                                <div className="space-y-4">
                                    <h4 className="font-semibold text-slate-900 flex items-center gap-2">📧 Email Esistente per CRIF</h4>
                                    <div className="bg-emerald-50 border border-emerald-200 rounded-lg p-3 text-sm text-emerald-700 mb-3">
                                        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)}
                                        disabled={!canEdit}
                                    />
                                </div>
                            )}

                            {/* Form Sections */}
                            {FORM_SECTIONS.filter(section => !section.crifOnly || crifMode || crifOnly).map(section => (
                                <div key={section.id} className="space-y-3">
                                    <h4 className="font-semibold text-slate-900 flex items-center gap-2">
                                        {section.icon} {section.title}
                                        {section.required && <Badge variant="error">Obbligatorio</Badge>}
                                        {section.crifOnly && (crifMode || crifOnly) && <Badge variant={crifOnly ? 'success' : 'brand'}>{crifOnly ? 'Solo CRIF' : 'CRIF'}</Badge>}
                                    </h4>
                                    <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                                        {section.fields.map(field => (
                                            field.type === 'select' ? (
                                                <Select
                                                    key={field.key}
                                                    label={field.label}
                                                    required={field.required}
                                                    options={field.options}
                                                    value={personalData[field.key] || ''}
                                                    onChange={e => handleFieldChange(field.key, e.target.value)}
                                                    disabled={!canEdit}
                                                />
                                            ) : (
                                                <Input
                                                    key={field.key}
                                                    label={field.label}
                                                    required={field.required}
                                                    placeholder={field.placeholder || field.label}
                                                    value={personalData[field.key] || ''}
                                                    onChange={e => handleFieldChange(field.key, e.target.value)}
                                                    disabled={!canEdit}
                                                />
                                            )
                                        ))}
                                    </div>
                                </div>
                            ))}

                            {/* Save Button */}
                            {canEdit && (
                                <div className="flex justify-end gap-3 pt-4 border-t border-slate-200">
                                    <Button variant="secondary" onClick={onClose}>Annulla</Button>
                                    <Button variant="primary" onClick={handleSave} disabled={saving}>
                                        {saving ? <><Spinner className="w-4 h-4" /> Salvataggio...</> : '💾 Salva Modifiche'}
                                    </Button>
                                </div>
                            )}
                        </div>
                    )}
                </div>
            </Card>
        </div>
    );
};

window.JobDetailModal = JobDetailModal;

