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

window.RegisterCenter = ({ onComplete, onOpenLegal }) => {
    const [step, setStep] = useState(1); // 1: Data, 2: OTP
    const [loading, setLoading] = useState(false);
    const [otp, setOtp] = useState('');
    const [error, setError] = useState('');
    const [formData, setFormData] = useState({
        centerName: '',
        email: '',
        phone: '',
        country: '',
        city: '',
        address: '',
        legalId: '',
        adminName: '',
        password: ''
    });

    const handleDataSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        setError('');
        try {
            const sendCode = window.httpsCallable('sendB2BVerificationCode');
            const result = await sendCode({ 
                email: formData.email, 
                centerName: formData.centerName 
            });
            if (result.data.success) {
                setStep(2);
            } else {
                setError(result.data.error || "Error al enviar código");
            }
        } catch (err) {
            setError("Error de conexión con el servidor.");
        } finally {
            setLoading(false);
        }
    };

    const handleVerifyOtp = async (e) => {
        e.preventDefault();
        if (otp.length !== 6) return setError("El código debe tener 6 dígitos.");
        
        setLoading(true);
        setError('');
        try {
            // 1. Create Auth User first (to ensure we can assign claims)
            const userCred = await window.firebaseAuth.createUserWithEmailAndPassword(
                window.firebaseAuth.auth, 
                formData.email.trim(), 
                formData.password
            );

            // 2. Verify Code and Create Organization document
            const verifyCode = window.httpsCallable('verifyB2BCode');
            const result = await verifyCode({
                email: formData.email,
                code: otp,
                orgData: {
                    name: formData.centerName,
                    city: formData.city,
                    address: formData.address,
                    country: formData.country,
                    legalId: formData.legalId,
                    adminName: formData.adminName,
                    phone: formData.phone
                }
            });

            if (result.data.success) {
                // 3. Create a basic user profile for the admin
                await window.firestore.setDoc(window.firestore.doc(window.db, "users", userCred.user.uid), {
                    name: formData.adminName,
                    email: formData.email.toLowerCase(),
                    role: 'org_admin',
                    centerId: result.data.centerId,
                    createdAt: window.firestore.serverTimestamp()
                });

                onComplete();
            } else {
                setError(result.data.error || "Código inválido.");
            }
        } catch (err) {
            setError("Error: " + err.message);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="min-h-screen bg-slate-900 flex items-center justify-center p-6 relative overflow-hidden">
            {/* Background elements */}
            <div className="absolute top-0 left-0 w-full h-full opacity-10 pointer-events-none">
                <div className="absolute top-[-10%] left-[-5%] w-[40%] h-[40%] bg-indigo-500 rounded-full blur-[120px]"></div>
                <div className="absolute bottom-[-10%] right-[-5%] w-[40%] h-[40%] bg-teal-500 rounded-full blur-[120px]"></div>
            </div>

            <div className="max-w-xl w-full bg-white/5 backdrop-blur-xl border border-white/10 p-10 rounded-[3rem] shadow-2xl relative z-10 animate-fadeIn">
                <div className="text-center mb-10">
                    <div className="w-20 h-20 bg-indigo-600 rounded-3xl mx-auto flex items-center justify-center mb-6 shadow-xl shadow-indigo-500/20">
                        <i className={`fas ${step === 1 ? 'fa-hospital' : 'fa-shield-alt'} text-white text-3xl`}></i>
                    </div>
                    <h2 className="text-3xl font-black text-white mb-2 font-display">
                        {step === 1 ? 'Registro de Centro Clínico' : 'Verifica tu Identidad'}
                    </h2>
                    <p className="text-slate-400 font-medium italic">
                        {step === 1 ? 'Únete a la red global de salud mental NeuroHUB' : `Hemos enviado un código a ${formData.email}`}
                    </p>
                </div>

                {step === 1 ? (
                    <form onSubmit={handleDataSubmit} className="space-y-6">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label className="block text-[10px] font-black text-slate-500 uppercase tracking-widest mb-3">Nombre del Centro</label>
                                <input 
                                    required 
                                    className="w-full p-4 bg-slate-800/50 border border-white/10 rounded-2xl outline-none focus:ring-2 focus:ring-indigo-500/20 text-white placeholder-slate-600"
                                    placeholder="Ej: Clínica NeuroVid"
                                    value={formData.centerName}
                                    onChange={e => setFormData({...formData, centerName: e.target.value})}
                                />
                            </div>
                            <div>
                                <label className="block text-[10px] font-black text-slate-500 uppercase tracking-widest mb-3">Email Institucional</label>
                                <input 
                                    type="email" required 
                                    className="w-full p-4 bg-slate-800/50 border border-white/10 rounded-2xl outline-none focus:ring-2 focus:ring-indigo-500/20 text-white placeholder-slate-600"
                                    placeholder="admin@clinica.com"
                                    value={formData.email}
                                    onChange={e => setFormData({...formData, email: e.target.value})}
                                />
                            </div>
                            <div>
                                <label className="block text-[10px] font-black text-slate-500 uppercase tracking-widest mb-3">Nombre Administrador</label>
                                <input 
                                    required 
                                    className="w-full p-4 bg-slate-800/50 border border-white/10 rounded-2xl outline-none focus:ring-2 focus:ring-indigo-500/20 text-white placeholder-slate-600"
                                    placeholder="Juan Pérez"
                                    value={formData.adminName}
                                    onChange={e => setFormData({...formData, adminName: e.target.value})}
                                />
                            </div>
                            <div>
                                <label className="block text-[10px] font-black text-slate-500 uppercase tracking-widest mb-3">ID Legal / NIT</label>
                                <input 
                                    required 
                                    className="w-full p-4 bg-slate-800/50 border border-white/10 rounded-2xl outline-none focus:ring-2 focus:ring-indigo-500/20 text-white placeholder-slate-600"
                                    placeholder="000.000.000-0"
                                    value={formData.legalId}
                                    onChange={e => setFormData({...formData, legalId: e.target.value})}
                                />
                            </div>
                            <div>
                                <label className="block text-[10px] font-black text-slate-500 uppercase tracking-widest mb-3">Ciudad</label>
                                <input 
                                    required 
                                    className="w-full p-4 bg-slate-800/50 border border-white/10 rounded-2xl outline-none focus:ring-2 focus:ring-indigo-500/20 text-white placeholder-slate-600"
                                    placeholder="Ej: Bogotá"
                                    value={formData.city}
                                    onChange={e => setFormData({...formData, city: e.target.value})}
                                />
                            </div>
                            <div className="md:col-span-2">
                                <label className="block text-[10px] font-black text-slate-500 uppercase tracking-widest mb-3">Contraseña del Administrador</label>
                                <input 
                                    type="password" required 
                                    className="w-full p-4 bg-slate-800/50 border border-white/10 rounded-2xl outline-none focus:ring-2 focus:ring-indigo-500/20 text-white placeholder-slate-600"
                                    placeholder="••••••••"
                                    value={formData.password}
                                    onChange={e => setFormData({...formData, password: e.target.value})}
                                />
                            </div>
                        </div>

                        {error && <p className="text-rose-400 text-xs font-bold text-center bg-rose-400/10 p-3 rounded-xl border border-rose-400/20">{error}</p>}

                        <button 
                            disabled={loading}
                            className="w-full py-5 bg-indigo-600 hover:bg-indigo-500 text-white font-black rounded-2xl transition-all shadow-xl shadow-indigo-600/20 uppercase tracking-widest text-xs disabled:opacity-50"
                        >
                            {loading ? 'Procesando...' : 'Registrar Centro Clínico'}
                        </button>
                    </form>
                ) : (
                    <form onSubmit={handleVerifyOtp} className="space-y-8 animate-fadeIn">
                        <div className="flex justify-center gap-4">
                            <input 
                                maxLength="6"
                                required
                                value={otp}
                                onChange={e => setOtp(e.target.value.replace(/\D/g,''))}
                                className="w-full max-w-[280px] text-center text-4xl font-black tracking-[0.5em] p-6 bg-slate-800/50 border border-white/10 rounded-3xl outline-none focus:ring-4 focus:ring-indigo-500/20 text-white"
                                placeholder="000000"
                            />
                        </div>
                        {error && <p className="text-rose-400 text-xs font-bold text-center">{error}</p>}
                        <div className="space-y-4">
                            <button 
                                disabled={loading}
                                className="w-full py-5 bg-teal-500 hover:bg-teal-400 text-slate-950 font-black rounded-2xl transition-all shadow-xl shadow-teal-500/20 uppercase tracking-widest text-xs disabled:opacity-50"
                            >
                                {loading ? 'Verificando...' : 'Activar Cuenta Profesional'}
                            </button>
                            <button 
                                type="button" 
                                onClick={() => setStep(1)}
                                className="w-full py-4 text-slate-500 hover:text-white font-bold transition-all text-sm"
                            >
                                Corregir datos de registro
                            </button>
                        </div>
                    </form>
                )}

                <p className="mt-12 text-center text-[10px] text-slate-500 font-bold uppercase tracking-widest leading-relaxed">
                    Al continuar, confirmas que representas legalmente a la institución y aceptas nuestros <br/>
                    <button onClick={() => onOpenLegal('legal')} className="text-indigo-400 hover:underline">Términos B2B</button> y <button onClick={() => onOpenLegal('privacy')} className="text-indigo-400 hover:underline">Privacidad Pro</button>.
                </p>
            </div>
        </div>
    );
};
