const { useState, useEffect, useMemo } = window.React || {};

/**
 * Clinical Dashboard: Professional View for NeuroHUB B2B
 * Provides clinical insights, multi-patient monitoring, and task assignment.
 */
window.ClinicalDashboard = ({ user, centerId }) => {
    const [patients, setPatients] = useState([]);
    const [selectedPatient, setSelectedPatient] = useState(null);
    const [loading, setLoading] = useState(true);
    const [brief, setBrief] = useState(null);
    const [briefLoading, setBriefLoading] = useState(false);
    const [tasks, setTasks] = useState([]);
    const [history, setHistory] = useState([]);

    const db = window.db;
    const { collection, query, where, getDocs, orderBy, limit, doc } = window.firestore;

    useEffect(() => {
        if (centerId) {
            fetchPatients();
        }
    }, [centerId]);

    const fetchPatients = async () => {
        setLoading(true);
        try {
            const q = query(
                collection(db, "users"),
                where("center_id", "==", centerId)
            );
            const snapshot = await getDocs(q);
            const list = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
            setPatients(list);
        } catch (error) {
            console.error("Error fetching patients:", error);
        } finally {
            setLoading(false);
        }
    };

    const loadPatientData = async (patient) => {
        setSelectedPatient(patient);
        setBrief(null);
        // Load Shadow Analysis
        try {
            const analysisQ = query(
                collection(db, "users", patient.id, "shadow_analysis"),
                orderBy("timestamp", "desc"),
                limit(20)
            );
            const analysisSnap = await getDocs(analysisQ);
            setHistory(analysisSnap.docs.map(d => d.data()));
        } catch (err) {
            console.warn("Shadow analysis not found or error:", err);
            setHistory([]);
        }
    };

    const generateBrief = async () => {
        if (!selectedPatient) return;
        setBriefLoading(true);
        try {
            const getBrief = window.httpsCallable('getClinicalBrief');
            const result = await getBrief({ patientId: selectedPatient.id });
            if (result.data.success) {
                setBrief(result.data.brief);
            }
        } catch (error) {
            console.error("Error generating brief:", error);
        } finally {
            setBriefLoading(false);
        }
    };

    const getStatusColor = (level) => {
        if (level >= 8) return 'bg-rose-500'; // High Alert
        if (level >= 5) return 'bg-amber-500'; // Warning
        return 'bg-teal-500'; // Stable
    };

    const [inviteEmail, setInviteEmail] = useState('');
    const [inviting, setInviting] = useState(false);
    const [showInviteModal, setShowInviteModal] = useState(false);

    const handleInvite = async (e) => {
        e.preventDefault();
        setInviting(true);
        try {
            const inviteDoc = window.httpsCallable('inviteDoctor');
            const result = await inviteDoc({ 
                email: inviteEmail, 
                centerId: centerId,
                specialty: "Psicología" 
            });
            if (result.data.success) {
                alert("Invitación enviada exitosamente");
                setShowInviteModal(false);
                setInviteEmail('');
            } else {
                alert("Error: " + result.data.error);
            }
        } catch (error) {
            console.error("Invite error:", error);
            alert("Error al invitar al doctor");
        } finally {
            setInviting(false);
        }
    };

    return (
        <div className="min-h-screen bg-slate-50 pt-32 pb-20 px-6">
            <div className="max-w-7xl mx-auto">
                <header className="mb-12 flex justify-between items-center">
                    <div>
                        <h1 className="text-3xl font-black text-slate-900 font-display">Dashboard Clínico</h1>
                        <p className="text-slate-500 font-medium tracking-tight">Panel de Gestión Profesional - {centerId}</p>
                    </div>
                    <div className="flex gap-4">
                        {user?.isAdmin && (
                            <button 
                                onClick={() => setShowInviteModal(true)}
                                className="px-6 py-4 bg-indigo-600 text-white font-black rounded-2xl hover:bg-indigo-700 transition-all flex items-center gap-3 shadow-lg shadow-indigo-500/20 uppercase tracking-widest text-xs"
                            >
                                <i className="fas fa-plus"></i>
                                Invitar Especialista
                            </button>
                        )}
                        <div className="flex items-center gap-4 bg-white p-4 rounded-2xl shadow-sm border border-slate-100">
                            <div className="w-10 h-10 bg-indigo-100 rounded-full flex items-center justify-center text-indigo-600">
                                <i className="fas fa-user-md"></i>
                            </div>
                            <div>
                                <p className="text-xs font-black text-slate-400 uppercase tracking-widest">
                                    {user?.isAdmin ? 'Administrador' : 'Especialista'}
                                </p>
                                <p className="text-sm font-bold text-slate-800">{user?.email}</p>
                            </div>
                        </div>
                    </div>
                </header>

                <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
                    {/* Patient List */}
                    <aside className="lg:col-span-3 space-y-4">
                        <div className="bg-white p-6 rounded-[2rem] shadow-xl border border-slate-100">
                            <h3 className="text-lg font-black text-slate-900 mb-6 flex items-center gap-2">
                                <i className="fas fa-users text-indigo-500"></i>
                                Pacientes ({patients.length})
                            </h3>
                            <div className="space-y-2 overflow-y-auto max-h-[600px] pr-2 custom-scrollbar">
                                {patients.map(p => (
                                    <button
                                        key={p.id}
                                        onClick={() => loadPatientData(p)}
                                        className={`w-full text-left p-4 rounded-2xl transition-all border ${
                                            selectedPatient?.id === p.id 
                                            ? 'bg-indigo-600 border-indigo-600 text-white shadow-lg' 
                                            : 'bg-slate-50 border-slate-100 hover:border-slate-200 text-slate-700'
                                        }`}
                                    >
                                        <div className="font-bold truncate">{p.name || p.nickname || p.email}</div>
                                        <div className={`text-[10px] font-black uppercase tracking-widest ${selectedPatient?.id === p.id ? 'text-indigo-200' : 'text-slate-400'}`}>
                                            {p.status || 'Activo'}
                                        </div>
                                    </button>
                                ))}
                            </div>
                        </div>
                    </aside>

                    {/* Statistics & Insights */}
                    <main className="lg:col-span-9 space-y-8">
                        {selectedPatient ? (
                            <div className="animate-fadeIn space-y-8">
                                {/* Header Stats */}
                                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                                    <div className="bg-white p-8 rounded-[2.5rem] shadow-xl border border-slate-100 relative overflow-hidden group">
                                        <div className="relative z-10">
                                            <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2">Estrés Promedio (7d)</p>
                                            <div className="flex items-end gap-3">
                                                <h4 className="text-4xl font-black text-slate-900">
                                                    {(history.reduce((acc, curr) => acc + (curr.stress_level || 0), 0) / (history.length || 1)).toFixed(1)}
                                                </h4>
                                                <span className={`px-2 py-1 rounded-md text-[10px] font-black text-white ${getStatusColor(6)} mb-1`}>
                                                    MODERADO
                                                </span>
                                            </div>
                                        </div>
                                        <div className="absolute top-0 right-0 p-8 opacity-10 text-indigo-900 transform group-hover:scale-110 transition-transform">
                                            <i className="fas fa-heartbeat text-5xl"></i>
                                        </div>
                                    </div>

                                    <div className="bg-white p-8 rounded-[2.5rem] shadow-xl border border-slate-100">
                                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2">Estado Reportado (LIA)</p>
                                        <div className="flex items-center gap-3">
                                            <div className={`w-3 h-3 rounded-full ${getStatusColor(history[0]?.stress_level || 0)} animate-pulse`}></div>
                                            <h4 className="text-2xl font-black text-slate-900 uppercase">
                                                {history[0]?.child_status || 'ESTABLE'}
                                            </h4>
                                        </div>
                                    </div>

                                    <div className="bg-white p-8 rounded-[2.5rem] shadow-xl border border-slate-100 flex flex-col justify-center">
                                        <button 
                                            onClick={generateBrief}
                                            disabled={briefLoading}
                                            className="w-full py-4 bg-slate-900 text-white font-black rounded-2xl hover:bg-slate-800 transition-all flex items-center justify-center gap-3 text-xs tracking-widest uppercase disabled:opacity-50"
                                        >
                                            {briefLoading ? 'Analizando...' : (
                                                <>
                                                    <i className="fas fa-magic"></i>
                                                    Generar Pre-Session Brief
                                                </>
                                            )}
                                        </button>
                                    </div>
                                </div>

                                {brief && (
                                    <div className="bg-indigo-900 text-white p-8 rounded-[2.5rem] shadow-2xl border border-indigo-500/30 animate-in slide-in-from-top duration-500">
                                        <h3 className="text-sm font-black uppercase tracking-[0.2em] mb-6 text-indigo-300 flex items-center gap-3">
                                            <i className="fas fa-sparkles"></i>
                                            Shadow Agent Insight
                                        </h3>
                                        <div className="prose prose-invert max-w-none text-indigo-100 font-medium leading-relaxed">
                                            {brief}
                                        </div>
                                    </div>
                                )}

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                                    {/* Comparative Radar */}
                                    <div className="bg-white p-8 rounded-[3rem] shadow-xl border border-slate-100 flex flex-col items-center">
                                        <h3 className="text-xl font-black text-slate-900 mb-2 font-display">Performance Cognitivo</h3>
                                        <p className="text-xs text-slate-400 font-bold mb-8 italic">Datos de fluidez vs esfuerzo reportado</p>
                                        <div className="w-full bg-slate-950 rounded-[2rem] p-4 scale-90 md:scale-100">
                                            {window.NeuroRadarChart && (
                                                <window.NeuroRadarChart 
                                                    effortStats={selectedPatient.progress?.pillars || {}}
                                                    fluidStats={selectedPatient.progress?.fluidity || {}}
                                                />
                                            )}
                                        </div>
                                    </div>

                                    {/* Shadow Tracking Trend */}
                                    <div className="bg-white p-8 rounded-[3rem] shadow-xl border border-slate-100">
                                        <h3 className="text-xl font-black text-slate-900 mb-8 font-display">Tendencia de Crisis (Semaphore)</h3>
                                        <div className="space-y-4">
                                            {history.slice(0, 8).map((h, i) => (
                                                <div key={i} className="flex items-center gap-4 p-4 bg-slate-50 rounded-2xl border border-slate-100">
                                                    <div className={`w-10 h-10 rounded-xl ${getStatusColor(h.stress_level)} flex items-center justify-center text-white font-bold`}>
                                                        {h.stress_level}
                                                    </div>
                                                    <div className="flex-1">
                                                        <p className="text-[10px] font-black text-slate-400 tracking-widest uppercase">{h.pilar_impactado}</p>
                                                        <p className="text-sm font-bold text-slate-700">{h.insight}</p>
                                                    </div>
                                                    <div className="text-[10px] text-slate-400 font-medium">
                                                        {h.timestamp?.toDate ? h.timestamp.toDate().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : ''}
                                                    </div>
                                                </div>
                                            ))}
                                            {history.length === 0 && (
                                                <div className="text-center py-20 text-slate-400 font-medium italic">
                                                    No hay interacciones recientes analizadas por el Shadow Agent.
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        ) : (
                            <div className="h-[600px] bg-white rounded-[3rem] shadow-xl border border-dashed border-slate-200 flex flex-col items-center justify-center text-center p-12">
                                <div className="w-32 h-32 bg-slate-50 rounded-full flex items-center justify-center mb-8">
                                    <i className="fas fa-user-injured text-5xl text-slate-200"></i>
                                </div>
                                <h2 className="text-2xl font-black text-slate-900 mb-4 font-display italic">Selecciona un paciente para comenzar</h2>
                                <p className="text-slate-500 max-w-sm font-medium">
                                    Para ver el Pre-Session Brief y las estadísticas de desempeño, elige a una persona de la lista de la izquierda.
                                </p>
                            </div>
                        )}
                    </main>
                </div>
            </div>

            {/* Invite Modal */}
            {showInviteModal && (
                <div className="fixed inset-0 z-[1000] flex items-center justify-center p-6 bg-slate-900/60 backdrop-blur-sm animate-fadeIn">
                    <div className="bg-white rounded-[2.5rem] p-10 max-w-md w-full shadow-2xl relative overflow-hidden">
                        <div className="absolute top-0 left-0 w-full h-2 bg-indigo-600"></div>
                        <button 
                            onClick={() => setShowInviteModal(false)}
                            className="absolute top-8 right-8 text-slate-400 hover:text-slate-600 transition-all"
                        >
                            <i className="fas fa-times text-xl"></i>
                        </button>
                        <h2 className="text-2xl font-black text-slate-900 mb-2 font-display">Invitar a un Colega</h2>
                        <p className="text-slate-500 mb-8 font-medium italic">Se le asignará automáticamente el acceso al centro {centerId}.</p>
                        
                        <form onSubmit={handleInvite} className="space-y-6">
                            <div>
                                <label className="block text-[10px] font-black text-slate-400 uppercase tracking-widest mb-3">Correo Electrónico del Profesional</label>
                                <input 
                                    type="email"
                                    required
                                    value={inviteEmail}
                                    onChange={(e) => setInviteEmail(e.target.value)}
                                    className="w-full p-5 bg-slate-50 border border-slate-100 rounded-2xl outline-none focus:ring-2 focus:ring-indigo-500/20 text-slate-900 placeholder-slate-300"
                                    placeholder="doctor@neurohub.health"
                                />
                            </div>
                            <button 
                                type="submit"
                                disabled={inviting}
                                className="w-full py-5 bg-slate-900 text-white font-black rounded-2xl hover:bg-slate-800 transition-all shadow-xl disabled:opacity-50 uppercase tracking-widest text-xs"
                            >
                                {inviting ? 'Enviando...' : 'Enviar Invitación Segura'}
                            </button>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};
