{% extends "base.html" %}
{# % from "_macros.html" import render_pagination % #}

{% block title %}Gestión de Usuarios{% endblock %}

{% block content %}
<div id="admin-content" class="container-fluid admin-users-list">
    <div class="row">
        <div class="col-12 mb-4 admin-header">
            <h1>Gestión de Usuarios</h1>
        </div>
    </div>
    
    <div class="row mb-4">
        <div class="col-md-6">
            <p class="mb-0">Aquí puedes ver y gestionar todos los usuarios del sistema.</p>
        </div>
        <div class="col-md-6 text-md-end">
            <button id="toggleFiltersBtn" class="btn btn-outline-secondary me-2" type="button"
                    data-bs-toggle="collapse" data-bs-target="#filtersCollapse" aria-expanded="false"
                    aria-controls="filtersCollapse">
                <i class="fas fa-filter me-1"></i>
                <span class="toggle-text">Mostrar filtros</span>
            </button>
            <a href="{{ url_for('admin.add_user') }}" class="btn btn-primary">
                <i class="fas fa-plus me-2"></i>Crear Usuario
            </a>
        </div>
    </div>

    <!-- Filtros (formato unificado con tarifas) -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="collapse" id="filtersCollapse">
                <div class="card shadow-sm filters-card">
                    <div class="card-body py-3">
                        <form method="get" id="userFiltersForm">
                            <div class="row g-3">
                                <!-- Columna izquierda: ID arriba, Username abajo -->
                                <div class="col-md-5">
                                    <div class="mb-2">
                                        <label for="filter_user_id" class="form-label fw-bold small text-muted mb-1">ID</label>
                                        <input type="text" class="form-control" id="filter_user_id" name="id" placeholder="ID" value="{{ filter_id or '' }}">
                                    </div>
                                    <div>
                                        <label for="filter_username" class="form-label fw-bold small text-muted mb-1">Nombre de usuario</label>
                                        <input type="text" class="form-control" id="filter_username" name="username" placeholder="Nombre de usuario" value="{{ filter_username or '' }}">
                                    </div>
                                </div>

                                <!-- Columna derecha: Email arriba, Rol abajo -->
                                <div class="col-md-5">
                                    <div class="mb-2">
                                        <label for="filter_email" class="form-label fw-bold small text-muted mb-1">Email</label>
                                        <input type="text" class="form-control" id="filter_email" name="email" placeholder="Email" value="{{ filter_email or '' }}">
                                    </div>
                                    <div>
                                        <label for="filter_role" class="form-label fw-bold small text-muted mb-1">Rol</label>
                                        <div class="input-group input-group-sm">
                                            <span class="input-group-text"><i class="fas fa-user-shield"></i></span>
                                            <input type="text" name="role" id="filter_role" class="form-control" placeholder="Rol (p.ej., Super Admin)" value="{{ filter_role or '' }}">
                                        </div>
                                    </div>
                                    <div class="mt-2">
                                        <label for="filter_is_active" class="form-label fw-bold small text-muted mb-1">Estado</label>
                                        <select name="is_active" id="filter_is_active" class="form-select form-select-sm">
                                            <option value="" {% if not filter_is_active %}selected{% endif %}>Todos</option>
                                            <option value="1" {% if filter_is_active in ['1','true','True'] %}selected{% endif %}>Activos</option>
                                            <option value="0" {% if filter_is_active in ['0','false','False'] %}selected{% endif %}>Inactivos</option>
                                        </select>
                                    </div>
                                </div>

                                <!-- Rango de fechas de registro -->
                                <div class="col-md-2 col-sm-12">
                                    <div class="row g-2">
                                        <div class="col-sm-6 col-md-12">
                                            <label for="filter_created_from" class="form-label fw-bold small text-muted mb-1">Desde</label>
                                            <div class="input-group input-group-sm">
                                                <span class="input-group-text"><i class="fas fa-calendar-alt"></i></span>
                                                <input type="date" name="created_from" id="filter_created_from" class="form-control" value="{{ filter_created_from or '' }}">
                                            </div>
                                        </div>
                                        <div class="col-sm-6 col-md-12">
                                            <label for="filter_created_until" class="form-label fw-bold small text-muted mb-1">Hasta</label>
                                            <div class="input-group input-group-sm">
                                                <span class="input-group-text"><i class="fas fa-calendar-alt"></i></span>
                                                <input type="date" name="created_until" id="filter_created_until" class="form-control" value="{{ filter_created_until or '' }}">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Botones de acción -->
                            <div class="row mt-3">
                                <div class="col-12 d-flex flex-wrap align-items-center justify-content-between">
                                    <div class="d-flex align-items-center mb-2 mb-md-0">
                                        <label for="per_page" class="form-label fw-bold small text-muted mb-0 me-2">Resultados por página</label>
                                        <select name="per_page" id="per_page" class="form-select form-select-sm" style="width: auto;">
                                            <option value="15" {% if per_page == 15 %}selected{% endif %}>15</option>
                                            <option value="25" {% if per_page == 25 %}selected{% endif %}>25</option>
                                            <option value="50" {% if per_page == 50 %}selected{% endif %}>50</option>
                                            <option value="100" {% if per_page == 100 %}selected{% endif %}>100</option>
                                        </select>
                                    </div>
                                    <div class="d-flex">
                                        <a href="{{ url_for('admin.list_users') }}" class="btn btn-sm btn-outline-secondary me-2">
                                            <i class="fas fa-sync-alt me-1"></i> Limpiar
                                        </a>
                                        <button type="submit" class="btn btn-sm btn-primary">
                                            <i class="fas fa-search me-1"></i> Buscar
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Estadísticas y conteo -->
    <div class="row mb-3">
        <div class="col-12 text-end">
            <span class="text-muted small">Mostrando {{ users|length }} de {{ pagination.total if pagination else 0 }} usuarios</span>
        </div>
    </div>
    
    <div class="card shadow mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">Lista de Usuarios</h5>
        </div>
        <div class="card-body">
            <!-- CSRF global para peticiones AJAX -->
            <input type="hidden" id="csrf_token" value="{{ global_csrf_form.csrf_token._value() }}">
            {# Ya no necesitamos un token global aquí, cada formulario tiene su propio token #}
            {% include '_flash_messages.html' %}
            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="dataTableUsers" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Nombre de Usuario</th>
                            <th>Email</th>
                            <th>Roles</th>
                            <th>Fecha de Registro</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% if users %}
                            {% for user in users %}
                                <tr>
                                    <td>{{ user.id }}</td>
                                    <td>{{ user.username }}</td>
                                    <td>{{ user.email }}</td>
                                    <td>
                                        {% for role in user.roles %}
                                            <span class="badge bg-info text-dark me-1">{{ role.name }}</span>
                                        {% else %}
                                            <span class="badge bg-secondary">Sin roles</span>
                                        {% endfor %}
                                    </td>
                                    <td>{{ user.created_at.strftime('%Y-%m-%d %H:%M') if user.created_at else 'N/A' }}</td>
                                    <td class="d-flex align-items-center">
                                        <!-- Botón Editar -->
                                        <a href="{{ url_for('admin.edit_user', user_id=user.id) }}" class="btn btn-edit-custom btn-sm me-1" title="Editar usuario">
                                            <i class="fas fa-edit"></i>
                                        </a>

                                        <!-- Botón Activar/Desactivar -->
                                        <button type="button" class="btn {{ 'btn-active-custom' if user.is_active else 'btn-inactive-custom' }} btn-sm me-1 toggle-status" data-user-id="{{ user.id }}" title="{{ 'Desactivar' if user.is_active else 'Activar' }} usuario">
                                            <i class="fas {{ 'fa-toggle-on' if user.is_active else 'fa-toggle-off' }}"></i>
                                        </button>

                                        <!-- Botón Eliminar -->
                                        <button type="button" class="btn btn-delete-custom btn-sm" data-bs-toggle="modal" data-bs-target="#deleteUserModal-{{ user.id }}" data-user-id="{{ user.id }}" data-username="{{ user.username }}" title="Eliminar usuario">
                                            <i class="fas fa-trash-alt"></i>
                                        </button>
                                    </td>
                                </tr>
                                
                                <!-- Modal de confirmación para eliminar usuario -->
                                <div class="modal fade" id="deleteUserModal-{{ user.id }}" tabindex="-1" aria-labelledby="deleteUserModalLabel-{{ user.id }}" aria-hidden="true">
                                    <div class="modal-dialog">
                                        <div class="modal-content">
                                            <div class="modal-header bg-danger text-white">
                                                <h5 class="modal-title" id="deleteUserModalLabel-{{ user.id }}">Confirmar eliminación</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                                            </div>
                                            <div class="modal-body">
                                                <p>¿Está seguro de que desea eliminar al usuario <strong>{{ user.username }}</strong>?</p>
                                                <p class="text-danger"><i class="fas fa-exclamation-triangle"></i> Esta acción no se puede deshacer.</p>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                                                <form action="{{ url_for('admin.delete_user', user_id=user.id) }}" method="POST" class="d-inline">
                                                    {{ csrf_forms[user.id].csrf_token }}
                                                    <button type="submit" class="btn btn-danger">Eliminar</button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            {% endfor %}
                        {% else %}
                            <tr>
                                <td colspan="6" class="text-center">No se encontraron usuarios.</td>
                            </tr>
                        {% endif %}
                    </tbody>
                </table>
            </div>
            {% if pagination and pagination.total > 0 %}
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center mt-3">{% if pagination.has_prev %}<li class="page-item">
                        <a class="page-link" href="{{ url_for('admin.list_users', page=pagination.prev_num, per_page=per_page, id=filter_id, username=filter_username, email=filter_email, role=filter_role, created_from=filter_created_from, created_until=filter_created_until, is_active=filter_is_active) }}" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    {% endif %}
                    {% for p in pagination.iter_pages() %}
                    {% if p %}
                        {% if p == pagination.page %}
                        <li class="page-item active" aria-current="page"><a class="page-link" href="#">{{ p }}</a></li>
                        {% else %}
                        <li class="page-item"><a class="page-link" href="{{ url_for('admin.list_users', page=p, per_page=per_page, id=filter_id, username=filter_username, email=filter_email, role=filter_role, created_from=filter_created_from, created_until=filter_created_until, is_active=filter_is_active) }}">{{ p }}</a></li>
                        {% endif %}
                    {% else %}
                    <li class="page-item disabled"><a class="page-link" href="#">...</a></li>
                    {% endif %}
                    {% endfor %}
                    {% if pagination.has_next %}
                    <li class="page-item">
                        <a class="page-link" href="{{ url_for('admin.list_users', page=pagination.next_num, per_page=per_page, id=filter_id, username=filter_username, email=filter_email, role=filter_role, created_from=filter_created_from, created_until=filter_created_until, is_active=filter_is_active) }}" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                    {% endif %}
                </ul>
            </nav>
            {% endif %}
        </div>
    </div>
</div>

{# TODO: Modales de eliminación #}

{% endblock %}

{% block scripts %}
<script>
$(document).ready(function() {
    // Función para mostrar alertas de Bootstrap dinámicamente
    function showAlert(type, message) {
        const alertDiv = $('<div class="alert alert-' + type + ' alert-dismissible fade show" role="alert">' +
                          message +
                          '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>' +
                          '</div>');
        $('#dataTableUsers').before(alertDiv);
        setTimeout(() => alertDiv.alert('close'), 5000);
    }

    // Sincronizar texto del botón Mostrar/Ocultar filtros (mismo comportamiento que tarifas)
    const filtersCollapseEl = document.getElementById('filtersCollapse');
    const toggleFiltersBtn = document.getElementById('toggleFiltersBtn');
    if (filtersCollapseEl && toggleFiltersBtn) {
        filtersCollapseEl.addEventListener('shown.bs.collapse', function () {
            const span = toggleFiltersBtn.querySelector('.toggle-text');
            if (span) span.textContent = 'Ocultar filtros';
        });
        filtersCollapseEl.addEventListener('hidden.bs.collapse', function () {
            const span = toggleFiltersBtn.querySelector('.toggle-text');
            if (span) span.textContent = 'Mostrar filtros';
        });
    }

    // Auto-enviar formulario al cambiar "Resultados por página"
    $('#per_page').on('change', function () {
        $('#userFiltersForm').trigger('submit');
    });

    const csrf_token = $('#csrf_token').val();
    console.log('Documento listo. Token CSRF encontrado:', csrf_token);
    if (!csrf_token) {
        console.error('¡Error Crítico! No se encontró el token CSRF. Las acciones POST fallarán.');
        showAlert('danger', 'Error de configuración: No se pudo encontrar el token de seguridad. Contacte al administrador.');
    }

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && csrf_token) {
                xhr.setRequestHeader("X-CSRFToken", csrf_token);
            }
        }
    });

    $('.toggle-status').on('click', function() {
        console.log('Botón de toggle presionado.');
        const button = $(this);
        const userId = button.data('user-id');
        const originalContent = button.html();

        button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i>');
        console.log(`Enviando petición AJAX para usuario ID: ${userId}`);

        $.ajax({
            url: `{{ url_for("admin.toggle_user_status", user_id=0) }}`.replace('0', userId),
            type: 'POST',
            dataType: 'json',
            success: function(response) {
                console.log('Respuesta recibida:', response);
                button.prop('disabled', false).html(originalContent);
                
                if (response.success) {
                    const newIcon = button.find('i');
                    if (response.is_active) {
                        button.removeClass('btn-inactive-custom').addClass('btn-active-custom');
                        newIcon.attr('class', 'fas fa-toggle-on');
                        button.attr('title', 'Desactivar usuario');
                    } else {
                        button.removeClass('btn-active-custom').addClass('btn-inactive-custom');
                        newIcon.attr('class', 'fas fa-toggle-off');
                        button.attr('title', 'Activar usuario');
                    }
                    showAlert('success', response.message);
                } else {
                    showAlert('danger', response.message || 'Ocurrió un error inesperado.');
                }
            },
            error: function(xhr, status, error) {
                console.error("Error en la petición AJAX:", status, error);
                console.error("Respuesta del servidor:", xhr.responseText);
                button.prop('disabled', false).html(originalContent);
                showAlert('danger', 'Error al cambiar el estado: ' + (xhr.responseJSON ? xhr.responseJSON.message : 'El servidor no respondió correctamente.'));
            }
        });
    });

    $('#deleteUserModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget);
        var userId = button.data('user-id');
        var username = button.data('username');
        var modal = $(this);
        modal.find('.modal-body #username-to-delete').text(username);
        var deleteUrl = "{{ url_for('admin.delete_user', user_id=0) }}".replace('0', userId);
        modal.find('#deleteUserForm').attr('action', deleteUrl);
    });
});</script>
{% endblock %}
