{% extends "base.html" %}

{% block title %}Editar Lead{% endblock %}

{% block content %}
<div id="admin-content" class="container-fluid">
    <div class="row">
        <div class="col-12 mb-4 admin-header">
            <h1>Editar Lead #{{ lead.id }}</h1>
        </div>
    </div>
    
    <div class="row">
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-edit me-2"></i>Información del Lead</h5>
                </div>
                <div class="card-body">
                    <form id="editLeadForm">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="name" class="form-label">Nombre *</label>
                                    <input type="text" class="form-control" id="name" name="name" value="{{ lead.name or '' }}" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="email" class="form-label">Email *</label>
                                    <input type="email" class="form-control" id="email" name="email" value="{{ lead.email or '' }}" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="phone" class="form-label">Teléfono</label>
                                    <input type="text" class="form-control" id="phone" name="phone" value="{{ lead.phone or '' }}">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="cups" class="form-label">CUPS</label>
                                    <input type="text" class="form-control" id="cups" name="cups" value="{{ lead.cups or '' }}">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="status" class="form-label">Estado</label>
                                    <select class="form-select" id="status" name="status">
                                        <option value="pending" {% if lead.status == 'pending' %}selected{% endif %}>Pendiente</option>
                                        <option value="in_progress" {% if lead.status == 'in_progress' %}selected{% endif %}>En progreso</option>
                                        <option value="contacted" {% if lead.status == 'contacted' %}selected{% endif %}>Contactado</option>
                                        <option value="completed" {% if lead.status == 'completed' %}selected{% endif %}>Completado</option>
                                        <option value="closed" {% if lead.status == 'closed' %}selected{% endif %}>Cerrado</option>
                                        <option value="cancelled" {% if lead.status == 'cancelled' %}selected{% endif %}>Cancelado</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="message" class="form-label">Mensaje del cliente</label>
                            <textarea class="form-control" id="message" name="message" rows="3">{{ lead.message or '' }}</textarea>
                        </div>
                        
                        <hr>
                        
                        <h6><i class="fas fa-user-tie me-2"></i>Información Comercial</h6>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="selected_plan" class="form-label">Plan Seleccionado</label>
                                    <input type="text" class="form-control" id="selected_plan" name="selected_plan" value="{{ lead.selected_plan or '' }}">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="recommended_supplier" class="form-label">Comercializadora Recomendada</label>
                                    <input type="text" class="form-control" id="recommended_supplier" name="recommended_supplier" value="{{ lead.recommended_supplier or '' }}">
                                </div>
                            </div>
                        </div>
                        
                        <hr>
                        
                        <h6><i class="fas fa-comments me-2"></i>Sistema de Comentarios CRM</h6>
                        
                        <div class="mb-3">
                            <label for="new_comment" class="form-label">Añadir nuevo comentario</label>
                            <textarea class="form-control" id="new_comment" name="new_comment" rows="3" placeholder="Escribe tu comentario aquí..."></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <button type="button" class="btn btn-outline-primary btn-sm" id="addCommentBtn">
                                <i class="fas fa-plus me-1"></i> Añadir Comentario
                            </button>
                        </div>
                        
                        <div id="commentsHistory" class="border rounded p-3" style="max-height: 300px; overflow-y: auto;">
                            <p class="text-muted">Cargando comentarios...</p>
                        </div>
                        
                        <div class="d-flex justify-content-between">
                            <a href="{{ url_for('admin.list_leads') }}" class="btn btn-secondary">
                                <i class="fas fa-arrow-left me-1"></i> Volver
                            </a>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-1"></i> Guardar Cambios
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0"><i class="fas fa-history me-2"></i>Histórico de Estudios</h6>
                </div>
                <div class="card-body">
                    <div id="historyContainer">
                        <p class="text-muted">Cargando histórico...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('editLeadForm');
    const leadId = "{{ lead.id }}";
    
    // Cargar histórico y comentarios
    loadHistory();
    loadComments();
    
    // Manejar botón de añadir comentario
    document.getElementById('addCommentBtn').addEventListener('click', function() {
        const commentText = document.getElementById('new_comment').value.trim();
        if (!commentText) {
            alert('Por favor, escribe un comentario');
            return;
        }
        
        addComment(commentText);
    });
    
    // Manejar envío del formulario
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());
        
        fetch(`{{ url_for('admin.edit_lead', lead_id=lead.id) }}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token() }}'
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Lead actualizado correctamente');
                window.location.href = "{{ url_for('admin.list_leads') }}";
            } else {
                alert('Error: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error al actualizar el lead');
        });
    });
    
    function loadHistory() {
        fetch(`{{ url_for('admin.get_lead_history', lead_id=lead.id) }}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayHistory(data.history);
                } else {
                    document.getElementById('historyContainer').innerHTML = 
                        '<p class="text-muted">Error al cargar histórico</p>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('historyContainer').innerHTML = 
                    '<p class="text-muted">Error al cargar histórico</p>';
            });
    }
    
    function displayHistory(history) {
        const container = document.getElementById('historyContainer');
        
        if (!history || history.length === 0) {
            container.innerHTML = '<p class="text-muted">No hay estudios previos</p>';
            return;
        }
        
        let html = '';
        history.forEach((study, index) => {
            const date = new Date(study.timestamp).toLocaleDateString('es-ES', {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
            
            const userName = study.user_name || study.created_by || 'Sistema';
            const actionText = getActionText(study.action);
            
            html += `
                <div class="border-bottom pb-2 mb-2">
                    <div class="d-flex justify-content-between align-items-start">
                        <small class="text-primary fw-bold">${actionText}</small>
                        <small class="text-muted">${date}</small>
                    </div>
                    <small class="text-muted d-block mb-1">Por: ${userName}</small>
                    <div class="mt-1">
                        ${getActionDetails(study)}
                    </div>
                </div>
            `;
        });
        
        container.innerHTML = html;
    }
    
    function getActionText(action) {
        const actions = {
            'estudio_inicial': '📊 Estudio inicial generado',
            'recalculo_con_precios_actualizados': '🔄 Recálculo con precios actualizados',
            'edicion_comentarios': '💬 Comentarios comerciales editados',
            'comentario_añadido': '➕ Comentario añadido',
            'plan_actualizado': '📋 Plan actualizado',
            'comercializadora_actualizada': '🏢 Comercializadora actualizada'
        };
        return actions[action] || '📝 Modificación realizada';
    }
    
    function getActionDetails(study) {
        let details = '';
        
        if (study.action === 'estudio_inicial') {
            details = `
                <strong>Ahorro estimado:</strong> ${study.estimated_savings || 0}€ anuales<br>
                <strong>Plan recomendado:</strong> ${study.best_plan || 'No disponible'}<br>
                <strong>Tarifa:</strong> ${study.tariff_type || 'No especificada'}
            `;
        } else if (study.action === 'recalculo_con_precios_actualizados') {
            details = `
                <strong>Nuevo ahorro:</strong> ${study.estimated_savings || 0}€ anuales<br>
                <strong>Plan recomendado:</strong> ${study.best_plan || 'No disponible'}<br>
                <strong>Fuente de datos:</strong> ${study.data_source === 'reextraccion' ? 'Re-extracción de PDF' : 'Datos existentes'}
            `;
        } else if (study.action === 'edicion_comentarios') {
            details = '';
            if (study.commercial_comments) {
                details += `<strong>Comentarios:</strong> ${study.commercial_comments}<br>`;
            }
            if (study.selected_plan) {
                details += `<strong>Plan seleccionado:</strong> ${study.selected_plan}<br>`;
            }
            if (study.recommended_supplier) {
                details += `<strong>Comercializadora:</strong> ${study.recommended_supplier}`;
            }
        } else {
            // Mostrar campos disponibles
            if (study.commercial_comments) {
                details += `<strong>Comentarios:</strong> ${study.commercial_comments}<br>`;
            }
            if (study.selected_plan) {
                details += `<strong>Plan:</strong> ${study.selected_plan}<br>`;
            }
            if (study.recommended_supplier) {
                details += `<strong>Comercializadora:</strong> ${study.recommended_supplier}`;
            }
        }
        
        return details || '<em class="text-muted">Sin detalles adicionales</em>';
    }
    
    function loadComments() {
        fetch(`{{ url_for('admin.get_lead_comments', lead_id=lead.id) }}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayComments(data.comments);
                } else {
                    document.getElementById('commentsHistory').innerHTML = 
                        '<p class="text-muted">Error al cargar comentarios</p>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('commentsHistory').innerHTML = 
                    '<p class="text-muted">Error al cargar comentarios</p>';
            });
    }
    
    function displayComments(comments) {
        const container = document.getElementById('commentsHistory');
        
        if (!comments || comments.length === 0) {
            container.innerHTML = '<p class="text-muted">No hay comentarios aún</p>';
            return;
        }
        
        let html = '';
        comments.forEach((comment, index) => {
            const date = new Date(comment.timestamp).toLocaleDateString('es-ES', {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
            
            html += `
                <div class="comment-item mb-3 p-2 border-start border-primary border-3">
                    <div class="d-flex justify-content-between align-items-start mb-1">
                        <small class="text-primary fw-bold">${comment.user_name}</small>
                        <small class="text-muted">${date}</small>
                    </div>
                    <div class="comment-text">
                        ${comment.comment}
                    </div>
                </div>
            `;
        });
        
        container.innerHTML = html;
        // Scroll al final para mostrar el comentario más reciente
        container.scrollTop = container.scrollHeight;
    }
    
    function addComment(commentText) {
        fetch(`{{ url_for('admin.add_lead_comment', lead_id=lead.id) }}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                comment: commentText
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Limpiar el textarea
                document.getElementById('new_comment').value = '';
                // Recargar comentarios
                loadComments();
                // Recargar histórico para mostrar la nueva entrada
                loadHistory();
            } else {
                alert('Error: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error al añadir el comentario');
        });
    }
});
</script>
{% endblock %}
