{% extends "base.html" %}

{% block title %}Gestión de Usuarios - IP Manager{% endblock %}
{% block header_title %}Gestión de Usuarios{% endblock %}

{% block content %}
<div class="page-header d-flex justify-content-between align-items-center">
    <div>
        <h1 class="page-title">Gestión de Usuarios</h1>
        <p class="page-subtitle">Administra usuarios del sistema y sus permisos</p>
    </div>
    <a href="{{ url_for('admin_create_user') }}" class="btn btn-primary">
        <i class="fas fa-plus me-2"></i>Crear Usuario
    </a>
</div>

<!-- Filtros y búsqueda -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-8">
                        <div class="search-box">
                            <i class="fas fa-search search-icon"></i>
                            <input type="text"
                                   class="form-control search-input"
                                   name="search"
                                   placeholder="Buscar por nombre, usuario, email o departamento..."
                                   value="{{ search_query or '' }}">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-search me-1"></i>Buscar
                        </button>
                    </div>
                    <div class="col-md-2">
                        <a href="{{ url_for('admin_users') }}" class="btn btn-outline-secondary w-100">
                            <i class="fas fa-times me-1"></i>Limpiar
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Lista de usuarios -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-users me-2"></i>
                    Lista de Usuarios
                    <span class="badge bg-secondary ms-2">{{ users.total }}</span>
                </h5>
                <div class="btn-group btn-group-sm">
                    <button type="button" class="btn btn-outline-secondary active" onclick="setView('table')">
                        <i class="fas fa-list"></i>
                    </button>
                    <button type="button" class="btn btn-outline-secondary" onclick="setView('cards')">
                        <i class="fas fa-th-large"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                {% if users.items %}
                <!-- Vista de tabla -->
                <div id="table-view">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Usuario</th>
                                    <th>Información</th>
                                    <th>Estado</th>
                                    <th>Último Acceso</th>
                                    <th>Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for user in users.items %}
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="user-avatar me-3">
                                                {{ user.full_name[0] }}
                                            </div>
                                            <div>
                                                <h6 class="mb-0">{{ user.full_name }}</h6>
                                                <small class="text-muted">@{{ user.username }}</small>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div>
                                            <small class="d-block">
                                                <i class="fas fa-envelope me-1"></i>{{ user.email }}
                                            </small>
                                            {% if user.department %}
                                            <small class="d-block text-muted">
                                                <i class="fas fa-building me-1"></i>{{ user.department }}
                                            </small>
                                            {% endif %}
                                        </div>
                                    </td>
                                    <td>
                                        <div class="d-flex flex-column gap-1">
                                            <span class="badge bg-{{ 'success' if user.is_active else 'secondary' }}">
                                                {{ 'Activo' if user.is_active else 'Inactivo' }}
                                            </span>
                                            {% if user.is_admin %}
                                            <span class="badge bg-warning">
                                                <i class="fas fa-crown me-1"></i>Admin
                                            </span>
                                            {% endif %}
                                        </div>
                                    </td>
                                    <td>
                                        {% if user.last_login %}
                                        <small class="text-muted">
                                            {{ user.last_login.strftime('%d/%m/%Y %H:%M') }}
                                        </small>
                                        {% else %}
                                        <small class="text-muted">Nunca</small>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <a href="{{ url_for('admin_edit_user', user_id=user.id) }}"
                                               class="btn btn-outline-primary"
                                               title="Editar usuario">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <button type="button"
                                                    class="btn btn-outline-{{ 'warning' if user.is_active else 'success' }}"
                                                    onclick="toggleUser({{ user.id }}, '{{ user.username }}')"
                                                    title="{{ 'Desactivar' if user.is_active else 'Activar' }} usuario">
                                                <i class="fas fa-{{ 'pause' if user.is_active else 'play' }}"></i>
                                            </button>
                                            <button type="button"
                                                    class="btn btn-outline-danger"
                                                    onclick="confirmDelete({{ user.id }}, '{{ user.username }}')"
                                                    title="Eliminar usuario"
                                                    {% if user.is_admin and users.items|selectattr('is_admin')|list|length <= 1 %}disabled{% endif %}>
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Vista de tarjetas -->
                <div id="cards-view" class="d-none">
                    <div class="row">
                        {% for user in users.items %}
                        <div class="col-md-6 col-lg-4 mb-4">
                            <div class="card h-100 user-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center mb-3">
                                        <div class="user-avatar me-3" style="width: 48px; height: 48px; font-size: 1.2rem;">
                                            {{ user.full_name[0] }}
                                        </div>
                                        <div class="flex-grow-1">
                                            <h6 class="mb-0">{{ user.full_name }}</h6>
                                            <small class="text-muted">@{{ user.username }}</small>
                                        </div>
                                        <div class="dropdown">
                                            <button class="btn btn-sm btn-outline-secondary" data-bs-toggle="dropdown">
                                                <i class="fas fa-ellipsis-v"></i>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <li>
                                                    <a class="dropdown-item" onclick="toggleUser({{ user.id }}, '{{ user.username }}')">
                                                        <i class="fas fa-{{ 'pause' if user.is_active else 'play' }} me-2"></i>
                                                        {{ 'Desactivar' if user.is_active else 'Activar' }}
                                                    </a>
                                                </li>
                                                <li>
                                                    <a class="dropdown-item" onclick="viewUserDetails({{ user.id }})">
                                                        <i class="fas fa-eye me-2"></i>Ver detalles
                                                    </a>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>

                                    <div class="mb-3">
                                        <small class="d-block">
                                            <i class="fas fa-envelope me-1 text-muted"></i>{{ user.email }}
                                        </small>
                                        {% if user.department %}
                                        <small class="d-block">
                                            <i class="fas fa-building me-1 text-muted"></i>{{ user.department }}
                                        </small>
                                        {% endif %}
                                        <small class="d-block">
                                            <i class="fas fa-calendar me-1 text-muted"></i>
                                            Registrado: {{ user.created_at.strftime('%d/%m/%Y') }}
                                        </small>
                                    </div>

                                    <div class="d-flex justify-content-between align-items-center">
                                        <div class="d-flex gap-1">
                                            <span class="badge bg-{{ 'success' if user.is_active else 'secondary' }}">
                                                {{ 'Activo' if user.is_active else 'Inactivo' }}
                                            </span>
                                            {% if user.is_admin %}
                                            <span class="badge bg-warning">
                                                <i class="fas fa-crown me-1"></i>Admin
                                            </span>
                                            {% endif %}
                                        </div>
                                        <small class="text-muted">
                                            {% if user.last_login %}
                                            Último: {{ user.last_login.strftime('%d/%m') }}
                                            {% else %}
                                            Sin accesos
                                            {% endif %}
                                        </small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>

                <!-- Paginación -->
                {% if users.pages > 1 %}
                <div class="d-flex justify-content-center mt-4">
                    <nav>
                        <ul class="pagination">
                            {% if users.has_prev %}
                            <li class="page-item">
                                <a class="page-link" href="{{ url_for('admin_users', page=users.prev_num, search=search_query) }}">
                                    <i class="fas fa-chevron-left"></i>
                                </a>
                            </li>
                            {% endif %}

                            {% for page_num in users.iter_pages() %}
                                {% if page_num %}
                                    {% if page_num != users.page %}
                                    <li class="page-item">
                                        <a class="page-link" href="{{ url_for('admin_users', page=page_num, search=search_query) }}">{{ page_num }}</a>
                                    </li>
                                    {% else %}
                                    <li class="page-item active">
                                        <span class="page-link">{{ page_num }}</span>
                                    </li>
                                    {% endif %}
                                {% else %}
                                    <li class="page-item disabled">
                                        <span class="page-link">…</span>
                                    </li>
                                {% endif %}
                            {% endfor %}

                            {% if users.has_next %}
                            <li class="page-item">
                                <a class="page-link" href="{{ url_for('admin_users', page=users.next_num, search=search_query) }}">
                                    <i class="fas fa-chevron-right"></i>
                                </a>
                            </li>
                            {% endif %}
                        </ul>
                    </nav>
                </div>
                {% endif %}
                {% else %}
                <div class="text-center py-5">
                    <div class="mb-4">
                        <i class="fas fa-users fa-3x text-muted"></i>
                    </div>
                    <h5 class="mb-3">No se encontraron usuarios</h5>
                    <p class="text-muted mb-4">
                        {% if search_query %}
                        No hay usuarios que coincidan con tu búsqueda "{{ search_query }}".
                        {% else %}
                        Aún no hay usuarios registrados en el sistema.
                        {% endif %}
                    </p>
                    <a href="{{ url_for('admin_create_user') }}" class="btn btn-primary">
                        <i class="fas fa-plus me-2"></i>Crear Primer Usuario
                    </a>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- Modal de confirmación -->
<div class="modal fade" id="confirmModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Confirmar Acción</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p id="confirmMessage"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <button type="button" class="btn btn-primary" id="confirmButton">Confirmar</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
function setView(viewType) {
    const tableView = document.getElementById('table-view');
    const cardsView = document.getElementById('cards-view');
    const tableBtn = document.querySelector('button[onclick="setView(\'table\')"]');
    const cardsBtn = document.querySelector('button[onclick="setView(\'cards\')"]');

    if (viewType === 'table') {
        tableView.classList.remove('d-none');
        cardsView.classList.add('d-none');
        tableBtn.classList.add('active');
        cardsBtn.classList.remove('active');
    } else {
        tableView.classList.add('d-none');
        cardsView.classList.remove('d-none');
        tableBtn.classList.remove('active');
        cardsBtn.classList.add('active');
    }

    // Guardar preferencia
    localStorage.setItem('usersViewMode', viewType);
}

// Cargar preferencia de vista
document.addEventListener('DOMContentLoaded', function() {
    const savedViewMode = localStorage.getItem('usersViewMode') || 'table';
    setView(savedViewMode);
});

function toggleUser(userId, username) {
    const modal = new bootstrap.Modal(document.getElementById('confirmModal'));
    const message = document.getElementById('confirmMessage');
    const confirmBtn = document.getElementById('confirmButton');

    message.textContent = `¿Estás seguro de que quieres cambiar el estado del usuario "${username}"?`;

    confirmBtn.onclick = function() {
        fetch(`/admin/users/${userId}/toggle`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => {
            if (response.ok) {
                location.reload();
            } else {
                alert('Error al cambiar el estado del usuario');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error al cambiar el estado del usuario');
        });

        modal.hide();
    };

    modal.show();
}

function viewUserDetails(userId) {
    // Por ahora mostrar alerta, en el futuro se puede implementar un modal con detalles
    alert(`Ver detalles del usuario ${userId} - Funcionalidad en desarrollo`);
}

function confirmDelete(userId, username) {
    const modal = new bootstrap.Modal(document.getElementById('confirmModal'));
    const message = document.getElementById('confirmMessage');
    const confirmBtn = document.getElementById('confirmButton');

    message.textContent = `¿Estás seguro de que quieres eliminar al usuario "${username}"? Esta acción no se puede deshacer.`;

    confirmBtn.onclick = function() {
        fetch(`/admin/users/${userId}/delete`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => {
            if (response.ok) {
                location.reload();
            } else {
                alert('Error al eliminar el usuario');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error al eliminar el usuario');
        });

        modal.hide();
    };

    modal.show();
}

// Auto-submit del formulario de búsqueda
let searchTimeout;
document.querySelector('input[name="search"]').addEventListener('input', function() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => {
        this.form.submit();
    }, 500);
});
</script>
{% endblock %}

{% block extra_css %}
<style>
.user-card {
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.user-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.user-avatar {
    background: var(--primary-color);
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    width: 40px;
    height: 40px;
}
</style>
{% endblock %}
