const LeadForm = () => {
    const [formData, setFormData] = React.useState({
        first_name: '',
        last_name: '',
        phone: '',
        email: '',
        in_spain: '',
        country_origin: '',
        location: '',
        interest: '',
        situation: '',
        experience: '',
        availability: '',
        message: '',
        language: 'Español',
        consent_policy: false,
        consent_contact: false
    });

    const [status, setStatus] = React.useState('idle'); // idle, loading, success, error

    const handleChange = (e) => {
        const { name, value, type, checked } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: type === 'checkbox' ? checked : value
        }));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setStatus('loading');

        // Capture UTMs
        const urlParams = new URLSearchParams(window.location.search);
        const utms = {
            utm_source: urlParams.get('utm_source') || '',
            utm_medium: urlParams.get('utm_medium') || '',
            utm_campaign: urlParams.get('utm_campaign') || '',
            utm_content: urlParams.get('utm_content') || '',
            utm_term: urlParams.get('utm_term') || '',
            campaign: urlParams.get('utm_campaign') || 'manual_contact'
        };

        // Logic for segmentation
        const segmentation = {
            segmento: formData.in_spain === 'Sí' ? 'espana' : 'origen',
            subtag: '',
        };
        
        if (formData.situation.includes('legal papers')) segmentation.subtag = 'regular';
        else if (formData.situation.includes('regularizing')) segmentation.subtag = 'regularization';
        else if (formData.situation.includes('doubts')) segmentation.subtag = 'doubts';

        if (formData.interest === 'Quiero más información') segmentation.subtag = 'nurturing';

        const frappeLead = {
            first_name: formData.first_name.trim(),
            last_name: formData.last_name.trim(),
            lead_name: `${formData.first_name} ${formData.last_name}`.trim(),
            email: formData.email.trim(),
            mobile_no: formData.phone.replace(/[^\d+]/g, '').trim(),
            company_name: "", 
            lead_source: "Migrantes",
            source: "Formularios Web",
            status: "Interesado",

            industry: "Sanidad",
            territory: formData.location.trim(),
            custom_nacionalidad: formData.country_origin,
            nacionalidad: formData.country_origin,
            country: formData.country_origin,
            custom_provincia: formData.location.trim(),
            custom_ubicacion: formData.location.trim(),
            custom_experiencia_cuidados: formData.experience,
            custom_situacion_migratoria: formData.situation,
            situacion_migratoria: formData.situation,
            custom_esta_en_espana: formData.in_spain,
            url_origen: typeof window !== "undefined" ? window.location.origin + window.location.pathname : "",
            custom_url_origen: typeof window !== "undefined" ? window.location.origin + window.location.pathname : "",
            
            custom_observaciones: [
                `¿ESTÁ EN ESPAÑA?: ${formData.in_spain}`,
                `SITUACIÓN ACTUAL: ${formData.situation}`,
                `EXPERIENCIA EN CUIDADOS: ${formData.experience}`,
                `MENSAJE: ${formData.message || 'Sin descripción'}`
            ].join('\n'),
            observaciones: [
                `¿ESTÁ EN ESPAÑA?: ${formData.in_spain}`,
                `SITUACIÓN ACTUAL: ${formData.situation}`,
                `EXPERIENCIA EN CUIDADOS: ${formData.experience}`,
                `MENSAJE: ${formData.message || 'Sin descripción'}`
            ].join('\n'),
            notes: [
                `¿ESTÁ EN ESPAÑA?: ${formData.in_spain}`,
                `SITUACIÓN ACTUAL: ${formData.situation}`,
                `EXPERIENCIA EN CUIDADOS: ${formData.experience}`,
                `MENSAJE: ${formData.message || 'Sin descripción'}`
            ].join('\n'),
            description: [
                `¿ESTÁ EN ESPAÑA?: ${formData.in_spain}`,
                `SITUACIÓN ACTUAL: ${formData.situation}`,
                `EXPERIENCIA EN CUIDADOS: ${formData.experience}`,
                `MENSAJE: ${formData.message || 'Sin descripción'}`
            ].join('\n')
        };

        try {
            const isLocal = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
            const crmUrl = isLocal ? 'http://localhost:8099/api/resource/CRM Lead' : '/api/resource/CRM Lead';
            
            const response = await fetch(crmUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(frappeLead)
            });

            if (response.ok) {
                setStatus('success');
                // Automatic PDF download
                const link = document.createElement('a');
                link.href = '/assets/Regularización 2026 en lenguaje claro.pdf';
                link.download = 'Guia_Regularizacion_2026.pdf';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            } else {
                const errorData = await response.json().catch(() => ({}));
                console.error('CRM Error:', errorData);
                setStatus('error');
                // Store error message to show in UI
                setFormData(prev => ({ ...prev, lastError: errorData.message || errorData.exception || `Error ${response.status}` }));
            }
        } catch (error) {
            console.error('Submission error:', error);
            setStatus('error');
        }
    };

    if (status === 'success') {
        return (
            <div className="premium-card p-12 md:p-20 rounded-[4rem] text-center animate-in fade-in zoom-in duration-700">
                <div className="w-28 h-28 bg-green-50 text-green-500 rounded-full flex items-center justify-center mx-auto mb-10 shadow-xl shadow-green-100/50">
                    <Icon name="check-circle" className="w-14 h-14" />
                </div>
                <h3 className="text-4xl font-black text-atu-blue-deep mb-6 leading-tight">¡Solicitud Procesada!</h3>
                <p className="text-xl text-gray-600 leading-relaxed mb-10 max-w-lg mx-auto">
                    Excelente. Tu perfil ha sido registrado con éxito. Nuestro equipo revisará tus datos y se pondrá en contacto contigo muy pronto para orientarte.
                </p>
                <div className="p-6 bg-atu-blue-bright/5 rounded-3xl inline-block">
                    <p className="text-sm text-gray-500 font-bold uppercase tracking-widest mb-2">Canal de atención prioritaria</p>
                    <a href="mailto:migrantes@grupoatu.com" className="text-2xl font-black text-atu-blue-vibrant hover:underline">
                        migrantes@grupoatu.com
                    </a>
                </div>
                <div className="mt-12">
                    <button 
                        onClick={() => setStatus('idle')}
                        className="text-atu-blue-vibrant font-black hover:underline flex items-center justify-center gap-2 mx-auto"
                    >
                        <Icon name="refresh-ccw" className="w-4 h-4" />
                        Enviar otra solicitud
                    </button>
                </div>
            </div>
        );
    }

    return (
        <form onSubmit={handleSubmit} className="premium-card p-10 md:p-14 rounded-[3.5rem] relative overflow-hidden">
            {/* Form Header */}
            <div className="mb-12">
                <div className="flex items-center gap-4 mb-6">
                    <div className="w-12 h-12 bg-atu-blue-vibrant text-white rounded-2xl flex items-center justify-center shadow-lg">
                        <Icon name="file-text" className="w-6 h-6" />
                    </div>
                    <div>
                        <h2 className="text-2xl font-black text-atu-blue-deep tracking-tight">Formulario de Registro</h2>
                        <p className="text-sm text-gray-500 font-medium italic">Evaluación de perfil para residencias</p>
                    </div>
                </div>
                
                {/* Visual Step Indicator */}
                <div className="flex items-center gap-2">
                    <div className="h-1.5 flex-1 bg-atu-blue-vibrant rounded-full"></div>
                    <div className="h-1.5 flex-1 bg-atu-blue-vibrant rounded-full opacity-30"></div>
                    <div className="h-1.5 flex-1 bg-atu-blue-vibrant rounded-full opacity-10"></div>
                </div>
            </div>

            <div className="grid md:grid-cols-2 gap-8 mb-10">
                <div className="space-y-3">
                    <label className="text-xs font-black text-atu-blue-deep/60 uppercase tracking-widest ml-1">Nombre *</label>
                    <input 
                        type="text" name="first_name" required
                        placeholder="Tu nombre"
                        className="w-full px-6 py-5 bg-gray-50/50 border-2 border-gray-100 rounded-3xl focus:border-atu-blue-vibrant focus:bg-white transition-all outline-none font-medium text-atu-blue-deep"
                        onChange={handleChange}
                    />
                </div>
                <div className="space-y-3">
                    <label className="text-xs font-black text-atu-blue-deep/60 uppercase tracking-widest ml-1">Apellidos *</label>
                    <input 
                        type="text" name="last_name" required
                        placeholder="Tus apellidos"
                        className="w-full px-6 py-5 bg-gray-50/50 border-2 border-gray-100 rounded-3xl focus:border-atu-blue-vibrant focus:bg-white transition-all outline-none font-medium text-atu-blue-deep"
                        onChange={handleChange}
                    />
                </div>
                <div className="space-y-3">
                    <label className="text-xs font-black text-atu-blue-deep/60 uppercase tracking-widest ml-1">Teléfono / WhatsApp *</label>
                    <input 
                        type="tel" name="phone" required
                        placeholder="+34 ..."
                        className="w-full px-6 py-5 bg-gray-50/50 border-2 border-gray-100 rounded-3xl focus:border-atu-blue-vibrant focus:bg-white transition-all outline-none font-medium text-atu-blue-deep"
                        onChange={handleChange}
                    />
                </div>
                <div className="space-y-3">
                    <label className="text-xs font-black text-atu-blue-deep/60 uppercase tracking-widest ml-1">Correo electrónico *</label>
                    <input 
                        type="email" name="email" required
                        placeholder="email@ejemplo.com"
                        className="w-full px-6 py-5 bg-gray-50/50 border-2 border-gray-100 rounded-3xl focus:border-atu-blue-vibrant focus:bg-white transition-all outline-none font-medium text-atu-blue-deep"
                        onChange={handleChange}
                    />
                </div>
            </div>

            <div className="grid md:grid-cols-2 gap-8 mb-10">
                <div className="space-y-3">
                    <label className="text-xs font-black text-atu-blue-deep/60 uppercase tracking-widest ml-1">¿Estás en España? *</label>
                        <select 
                            name="in_spain" required
                            className="w-full px-6 py-5 bg-gray-50/50 border-2 border-gray-100 rounded-3xl focus:border-atu-blue-vibrant focus:bg-white transition-all outline-none appearance-none font-medium text-atu-blue-deep"
                            onChange={handleChange}
                        >
                            <option value="">Selecciona una opción</option>
                            <option value="Ya estoy en España">Sí, ya estoy allí</option>
                            <option value="Aún no estoy en España">No, aún no</option>
                        </select>
                </div>
                <div className="space-y-3">
                    <label className="text-xs font-black text-atu-blue-deep/60 uppercase tracking-widest ml-1">País de origen *</label>
                    <input 
                        type="text" name="country_origin" required
                        placeholder="Ej: Venezuela, Colombia..."
                        className="w-full px-6 py-5 bg-gray-50/50 border-2 border-gray-100 rounded-3xl focus:border-atu-blue-vibrant focus:bg-white transition-all outline-none font-medium text-atu-blue-deep"
                        onChange={handleChange}
                    />
                </div>
                <div className="space-y-3">
                    <label className="text-xs font-black text-atu-blue-deep/60 uppercase tracking-widest ml-1">Provincia en España (o donde residas) *</label>
                    <input 
                        type="text" name="location" required
                        placeholder="Ej: Madrid, Barcelona..."
                        className="w-full px-6 py-5 bg-gray-50/50 border-2 border-gray-100 rounded-3xl focus:border-atu-blue-vibrant focus:bg-white transition-all outline-none font-medium text-atu-blue-deep"
                        onChange={handleChange}
                    />
                </div>
            </div>

            <div className="space-y-8 mb-10 border-t-2 border-gray-50 pt-10">
                <div className="grid md:grid-cols-2 gap-8">
                    <div className="space-y-3">
                        <label className="text-xs font-black text-atu-blue-deep/60 uppercase tracking-widest ml-1">Situación actual *</label>
                        <select 
                            name="situation" required
                            className="w-full px-6 py-5 bg-gray-50/50 border-2 border-gray-100 rounded-3xl focus:border-atu-blue-vibrant focus:bg-white transition-all outline-none appearance-none font-medium text-atu-blue-deep"
                            onChange={handleChange}
                        >
                            <option value="">Selecciona tu situación</option>
                            <option value="Con papeles en regla">Con papeles en regla</option>
                            <option value="En proceso de regularización">En proceso de regularización</option>
                            <option value="Tengo dudas sobre mi situación">Tengo dudas sobre mi situación</option>
                            <option value="Fuera de España">Fuera de España</option>
                        </select>
                    </div>
                    <div className="space-y-3">
                        <label className="text-xs font-black text-atu-blue-deep/60 uppercase tracking-widest ml-1">Experiencia en cuidados *</label>
                        <select 
                            name="experience" required
                            className="w-full px-6 py-5 bg-gray-50/50 border-2 border-gray-100 rounded-3xl focus:border-atu-blue-vibrant focus:bg-white transition-all outline-none appearance-none font-medium text-atu-blue-deep"
                            onChange={handleChange}
                        >
                            <option value="">Selecciona experiencia</option>
                            <option value="Tengo experiencia previa">Tengo experiencia previa</option>
                            <option value="No tengo experiencia">No tengo experiencia</option>
                            <option value="Un poco de experiencia">Un poco de experiencia</option>
                        </select>
                    </div>
                </div>

                <div className="space-y-3">
                    <label className="text-xs font-black text-atu-blue-deep/60 uppercase tracking-widest ml-1">Cuéntanos un poco más sobre ti</label>
                    <textarea 
                        name="message"
                        rows="3"
                        placeholder="Tu motivación, idiomas, estudios..."
                        className="w-full px-6 py-5 bg-gray-50/50 border-2 border-gray-100 rounded-3xl focus:border-atu-blue-vibrant focus:bg-white transition-all outline-none resize-none font-medium text-atu-blue-deep"
                        onChange={handleChange}
                    ></textarea>
                </div>
            </div>

            {status === 'error' && (
                <div className="mb-8 p-6 bg-red-50 border-2 border-red-100 text-red-600 rounded-[2rem] text-sm font-bold animate-in fade-in slide-in-from-top-4">
                    <div className="flex items-center gap-4">
                        <div className="w-10 h-10 bg-red-100 rounded-xl flex items-center justify-center shrink-0">
                            <Icon name="alert-circle" className="w-6 h-6" />
                        </div>
                        <div>
                            <p className="mb-1">No se pudo enviar el formulario:</p>
                            <p className="text-xs opacity-80 font-medium">{formData.lastError || "Error de conexión con el servidor CRM."}</p>
                        </div>
                    </div>
                </div>
            )}

            <div className="space-y-5 mb-12">
                <label className="flex items-center gap-4 cursor-pointer group">
                    <input 
                        type="checkbox" name="consent_policy" required
                        className="w-6 h-6 rounded-lg border-2 border-gray-200 text-atu-blue-vibrant focus:ring-atu-blue-vibrant transition-all"
                        onChange={handleChange}
                    />
                    <span className="text-sm text-gray-500 font-medium group-hover:text-atu-blue-deep transition-colors leading-tight">
                        Acepto la <a href="#" className="text-atu-blue-vibrant font-black underline">política de privacidad</a>.
                    </span>
                </label>
                <label className="flex items-center gap-4 cursor-pointer group">
                    <input 
                        type="checkbox" name="consent_contact" required
                        className="w-6 h-6 rounded-lg border-2 border-gray-200 text-atu-blue-vibrant focus:ring-atu-blue-vibrant transition-all"
                        onChange={handleChange}
                    />
                    <span className="text-sm text-gray-500 font-medium group-hover:text-atu-blue-deep transition-colors leading-tight">
                        Autorizo a Grupo ATU a contactarme por WhatsApp/Email.
                    </span>
                </label>
            </div>

            <button 
                type="submit"
                disabled={status === 'loading'}
                className="w-full py-6 button-shimmer text-white rounded-[2rem] text-2xl font-black shadow-2xl shadow-atu-blue-vibrant/30 hover:scale-[1.02] active:scale-98 transition-all disabled:opacity-70 flex items-center justify-center gap-4 group"
            >
                {status === 'loading' ? (
                    <>
                        <div className="w-6 h-6 border-4 border-white/30 border-t-white rounded-full animate-spin"></div>
                        Procesando...
                    </>
                ) : (
                    <>
                        Completar Solicitud
                        <Icon name="chevron-right" className="w-8 h-8 group-hover:translate-x-2 transition-transform" />
                    </>
                )}
            </button>
            
            <p className="text-center mt-8 text-[10px] text-gray-400 font-black uppercase tracking-[0.1em]">
                Registro seguro y privado · Grupo ATU 2026
            </p>
        </form>
    );
};
