{% extends 'backoffice/base.html' %}
{% load static %}

{% block title %}{{ page_title }} - ECOLUX Dashboard{% endblock %}

{% block content %}
<section class="section is-main-section">
    <div class="level">
        <div class="level-left">
            <div class="level-item">
                <div class="title">
                    <h1 class="title is-5 has-text-ecolux-primary">
                        <span class="icon-text">
                            
                            <span>{{ page_title }}</span>
                        </span>
                    </h1>
                </div>
            </div>
        </div>
        <div class="level-right">
            <div class="level-item">
                <div class="buttons">
                    <a href="{% url 'app:dashboard_home' %}" class="button is-light">
                        <span class="icon">
                            <i class="fas fa-arrow-left"></i>
                        </span>
                        <span>Retour au tableau de bord</span>
                    </a>
                    <button class="button is-ecolux-primary" onclick="openAddUserModal()">
                        <span class="icon">
                            <i class="fas fa-plus"></i>
                        </span>
                        <span>Nouvel utilisateur</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Statistiques rapides -->
    <div class="columns is-multiline mb-5">
        <div class="column is-3">
            <div class="card ecolux-primary-light">
                <div class="card-content">
                    <div class="media">
                        <div class="media-left">
                            <span class="icon is-large has-text-ecolux-primary">
                                <i class="fas fa-users fa-2x"></i>
                            </span>
                        </div>
                        <div class="media-content">
                            <p class="title is-4 has-text-ecolux-primary">{{ total_users }}</p>
                            <p class="subtitle is-6 has-text-grey-dark">Utilisateurs Total</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="column is-3">
            <div class="card ecolux-secondary-light">
                <div class="card-content">
                    <div class="media">
                        <div class="media-left">
                            <span class="icon is-large has-text-ecolux-secondary">
                                <i class="fas fa-user-tie fa-2x"></i>
                            </span>
                        </div>
                        <div class="media-content">
                            <p class="title is-4 has-text-ecolux-primary">{{ drh_count }}</p>
                            <p class="subtitle is-6 has-text-grey-dark">DRH</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="column is-3">
            <div class="card ecolux-primary-light">
                <div class="card-content">
                    <div class="media">
                        <div class="media-left">
                            <span class="icon is-large has-text-ecolux-primary">
                                <i class="fas fa-handshake fa-2x"></i>
                            </span>
                        </div>
                        <div class="media-content">
                            <p class="title is-4 has-text-ecolux-primary">{{ client_count }}</p>
                            <p class="subtitle is-6 has-text-grey-dark">Clients</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="column is-3">
            <div class="card ecolux-secondary-light">
                <div class="card-content">
                    <div class="media">
                        <div class="media-left">
                            <span class="icon is-large has-text-ecolux-secondary">
                                <i class="fas fa-hard-hat fa-2x"></i>
                            </span>
                        </div>
                        <div class="media-content">
                            <p class="title is-4 has-text-ecolux-primary">{{ technicien_count }}</p>
                            <p class="subtitle is-6 has-text-grey-dark">Techniciens</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filtres -->
    <div class="card ecolux-card mb-5">
        <div class="card-content">
            <form method="GET" class="field is-grouped is-grouped-multiline">
                <div class="control">
                    <div class="field has-addons">
                        <div class="control">
                            <span class="button is-static ecolux-primary">
                                <i class="fas fa-filter"></i>
                            </span>
                        </div>
                        <div class="control">
                            <div class="select">
                                <select name="type" onchange="this.form.submit()">
                                    <option value="">Tous les types</option>
                                    {% for value, label in user_types %}
                                        <option value="{{ value }}" {% if current_type == value %}selected{% endif %}>
                                            {{ label }}
                                        </option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="control is-expanded">
                    <div class="field has-addons">
                        <div class="control is-expanded">
                            <input class="input" type="text" name="search" placeholder="Rechercher par nom, email, username..." 
                                   value="{{ search_query }}" style="border-radius: 8px;">
                        </div>
                        <div class="control">
                            <button type="submit" class="button is-ecolux-primary">
                                <span class="icon">
                                    <i class="fas fa-search"></i>
                                </span>
                            </button>
                        </div>
                    </div>
                </div>
                
                {% if current_type or search_query %}
                <div class="control">
                    <a href="{% url 'app:dashboard_users_management' %}" class="button is-light">
                        <span class="icon">
                            <i class="fas fa-times"></i>
                        </span>
                        <span>Effacer</span>
                    </a>
                </div>
                {% endif %}
            </form>
        </div>
    </div>

    <!-- Liste des utilisateurs -->
    <div class="card ecolux-card">
        <header class="card-header ecolux-primary">
            <p class="card-header-title has-text-ecolux-secondary">
                <span class="icon">
                    <i class="fas fa-users"></i>
                </span>
                Liste des utilisateurs
            </p>
        </header>
        
        <div class="card-content p-0">
            {% if page_obj %}
                <div class="table-container">
                    <table class="table is-fullwidth is-hoverable" style="border-radius: 0;">
                        <thead class="ecolux-secondary-light">
                            <tr>
                                <th style="border: none; padding: 1rem;">
                                    <span class="icon-text">
                                        <span class="icon has-text-ecolux-primary">
                                            <i class="fas fa-user"></i>
                                        </span>
                                        <span class="has-text-ecolux-primary">Utilisateur</span>
                                    </span>
                                </th>
                                <th style="border: none; padding: 1rem;" class="has-text-ecolux-primary">Type</th>
                                <th style="border: none; padding: 1rem;" class="has-text-ecolux-primary">Contact</th>
                                <th style="border: none; padding: 1rem;" class="has-text-ecolux-primary">Statut</th>
                                <th style="border: none; padding: 1rem;" class="has-text-ecolux-primary">Inscription</th>
                                <th style="border: none; padding: 1rem;" class="has-text-ecolux-primary">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for cuser in page_obj %}
                            <tr style="border-bottom: 1px solid #f1f3f4;">
                                <td style="border: none; padding: 1rem;">
                                    <div class="media">
                                        {% comment %} <div class="media-left">
                                            <figure class="image is-48x48">
                                                {% if cuser.image %}
                                                    <img src="{{ cuser.image.url }}" alt="Avatar" class="is-rounded" style="object-fit: cover;">
                                                {% else %}
                                                    <div class="avatar-placeholder is-rounded ecolux-primary" style="color: #e6c252; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 1.2rem;">
                                                        {{ cuser.user.first_name|first|default:cuser.user.username|first|upper }}
                                                    </div>
                                                {% endif %}
                                            </figure>
                                        </div> {% endcomment %}
                                        <div class="media-content">
                                            <p class="title is-6 mb-1 has-text-ecolux-primary">
                                                {% if cuser.user.first_name or cuser.user.last_name %}
                                                    {{ cuser.user.get_full_name }}
                                                {% else %}
                                                    {{ cuser.user.username }}
                                                {% endif %}
                                            </p>
                                            {% comment %} <p class="subtitle is-7 has-text-grey">@{{ cuser.user.username }}</p> {% endcomment %}
                                        </div>
                                    </div>
                                </td>
                                <td style="border: none; padding: 1rem;">
                                    {% if cuser.type == 'DRH' %}
                                        <span class="tag is-ecolux-primary">
                                            <span class="icon">
                                                <i class="fas fa-user-tie"></i>
                                            </span>
                                            <span>{{ cuser.get_type_display }}</span>
                                        </span>
                                    {% elif cuser.type == 'CLIENT' %}
                                        <span class="tag is-ecolux-secondary">
                                            <span class="icon">
                                                <i class="fas fa-handshake"></i>
                                            </span>
                                            <span>{{ cuser.get_type_display }}</span>
                                        </span>
                                    {% elif cuser.type == 'TECHNICIEN' %}
                                        <span class="tag is-ecolux-primary">
                                            <span class="icon">
                                                <i class="fas fa-hard-hat"></i>
                                            </span>
                                            <span>{{ cuser.get_type_display }}</span>
                                        </span>
                                    {% else %}
                                        <span class="tag is-ecolux-secondary">
                                            <span class="icon">
                                                <i class="fas fa-user-shield"></i>
                                            </span>
                                            <span>{{ cuser.get_type_display }}</span>
                                        </span>
                                    {% endif %}
                                </td>
                                <td style="border: none; padding: 1rem;">
                                    <div class="content is-small">
                                        <p class="mb-1">
                                            <span class="icon-text">
                                                <span class="icon has-text-grey">
                                                    <i class="fas fa-envelope"></i>
                                                </span>
                                                <span>{{ cuser.user.email|default:"Non renseigné" }}</span>
                                            </span>
                                        </p>
                                        {% if cuser.phone %}
                                        <p>
                                            <span class="icon-text">
                                                <span class="icon has-text-grey">
                                                    <i class="fas fa-phone"></i>
                                                </span>
                                                <span>{{ cuser.phone }}</span>
                                            </span>
                                        </p>
                                        {% endif %}
                                    </div>
                                </td>
                                <td style="border: none; padding: 1rem;">
                                    {% if cuser.user.is_active %}
                                        <span class="tag is-success is-light">
                                            <span class="icon">
                                                <i class="fas fa-check-circle"></i>
                                            </span>
                                            <span>Actif</span>
                                        </span>
                                    {% else %}
                                        <span class="tag is-danger is-light">
                                            <span class="icon">
                                                <i class="fas fa-times-circle"></i>
                                            </span>
                                            <span>Inactif</span>
                                        </span>
                                    {% endif %}
                                </td>
                                <td style="border: none; padding: 1rem;">
                                    <div class="content is-small has-text-grey">
                                        <p class="has-text-ecolux-primary">{{ cuser.user.date_joined|date:"d/m/Y" }}</p>
                                        <p>{{ cuser.user.date_joined|timesince }} ago</p>
                                    </div>
                                </td>
                                <td style="border: none; padding: 1rem;">
                                    {% comment %} <div class="buttons are-small">
                                        <button class="button is-ecolux-secondary is-light" onclick="viewUser({{ cuser.id }})">
                                            <span class="icon">
                                                <i class="fas fa-eye"></i>
                                            </span>
                                        </button>
                                        <button class="button is-ecolux-primary is-light" onclick="editUser({{ cuser.id }})">
                                            <span class="icon">
                                                <i class="fas fa-edit"></i>
                                            </span>
                                        </button>
                                        {% if cuser.user.is_active %}
                                        <button class="button is-danger is-light" onclick="toggleUserStatus({{ cuser.id }}, false)">
                                            <span class="icon">
                                                <i class="fas fa-user-slash"></i>
                                            </span>
                                        </button>
                                        {% else %}
                                        <button class="button is-success is-light" onclick="toggleUserStatus({{ cuser.id }}, true)">
                                            <span class="icon">
                                                <i class="fas fa-user-check"></i>
                                            </span>
                                        </button>
                                        {% endif %}
                                    </div> {% endcomment %}
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            {% else %}
                <div class="notification is-info is-light m-5">
                    <div class="content has-text-centered">
                        <span class="icon is-large has-text-info">
                            <i class="fas fa-users fa-3x"></i>
                        </span>
                        <p class="title is-5">Aucun utilisateur trouvé</p>
                        <p>{% if current_type or search_query %}Essayez de modifier vos critères de recherche.{% else %}Commencez par ajouter des utilisateurs à votre plateforme.{% endif %}</p>
                        {% if current_type or search_query %}
                            <a href="{% url 'app:dashboard_users_management' %}" class="button is-info is-light">
                                Effacer les filtres
                            </a>
                        {% endif %}
                    </div>
                </div>
            {% endif %}
        </div>
    </div>

    <!-- Pagination moderne -->
    {% if page_obj.has_other_pages %}
    <nav class="pagination is-centered mt-6" role="navigation" aria-label="pagination">
        {% if page_obj.has_previous %}
            <a class="pagination-previous button is-ecolux-primary" href="?page={{ page_obj.previous_page_number }}{% if current_type %}&type={{ current_type }}{% endif %}{% if search_query %}&search={{ search_query }}{% endif %}" style="border-radius: 8px;">
                <span class="icon">
                    <i class="fas fa-chevron-left"></i>
                </span>
                <span>Précédent</span>
            </a>
        {% endif %}
        
        {% if page_obj.has_next %}
            <a class="pagination-next button is-ecolux-primary" href="?page={{ page_obj.next_page_number }}{% if current_type %}&type={{ current_type }}{% endif %}{% if search_query %}&search={{ search_query }}{% endif %}" style="border-radius: 8px;">
                <span>Suivant</span>
                <span class="icon">
                    <i class="fas fa-chevron-right"></i>
                </span>
            </a>
        {% endif %}
        
        <ul class="pagination-list">
            {% for num in page_obj.paginator.page_range %}
                {% if page_obj.number == num %}
                    <li><a class="pagination-link is-current ecolux-primary" style="border-radius: 8px; border-color: transparent;">{{ num }}</a></li>
                {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                    <li><a class="pagination-link" href="?page={{ num }}{% if current_type %}&type={{ current_type }}{% endif %}{% if search_query %}&search={{ search_query }}{% endif %}" style="border-radius: 8px;">{{ num }}</a></li>
                {% endif %}
            {% endfor %}
        </ul>
    </nav>
    {% endif %}
</section>

<!-- Modal pour ajouter un utilisateur -->
<div class="modal" id="addUserModal">
    <div class="modal-background" onclick="closeAddUserModal()"></div>
    <div class="modal-card ecolux-card">
        <header class="modal-card-head ecolux-primary">
            <p class="modal-card-title has-text-ecolux-secondary">
                <span class="icon-text">
                    <span class="icon">
                        <i class="fas fa-user-plus"></i>
                    </span>
                    <span>Nouvel utilisateur</span>
                </span>
            </p>
            <button class="delete" aria-label="close" onclick="closeAddUserModal()"></button>
        </header>
        <section class="modal-card-body">
            <form id="addUserForm">
                <div class="field">
                    <label class="label has-text-ecolux-primary">Email</label>
                    <div class="control has-icons-left">
                        <input class="input" type="email" name="email" placeholder="email@example.com" required>
                        <span class="icon is-small is-left">
                            <i class="fas fa-envelope"></i>
                        </span>
                    </div>
                    <p class="help">L'email sera utilisé comme nom d'utilisateur. Un email de configuration du mot de passe sera envoyé.</p>
                </div>

                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Prénom</label>
                            <div class="control has-icons-left">
                                <input class="input" type="text" name="first_name" placeholder="Prénom">
                                <span class="icon is-small is-left">
                                    <i class="fas fa-user"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Nom</label>
                            <div class="control has-icons-left">
                                <input class="input" type="text" name="last_name" placeholder="Nom de famille">
                                <span class="icon is-small is-left">
                                    <i class="fas fa-user"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="field">
                    <label class="label has-text-ecolux-primary">Type d'utilisateur</label>
                    <div class="control has-icons-left">
                        <div class="select is-fullwidth">
                            <select name="user_type" required>
                                <option value="">Sélectionnez un type</option>
                                {% for value, label in user_types %}
                                    <option value="{{ value }}">{{ label }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <span class="icon is-small is-left">
                            <i class="fas fa-user-tag"></i>
                        </span>
                    </div>
                </div>

                <div class="field">
                    <label class="label has-text-ecolux-primary">Téléphone (optionnel)</label>
                    <div class="control has-icons-left">
                        <input class="input" type="tel" name="phone" placeholder="+225 01 02 03 04 05">
                        <span class="icon is-small is-left">
                            <i class="fas fa-phone"></i>
                        </span>
                    </div>
                </div>

                <div class="notification is-info is-light">
                    <div class="content">
                        <p><strong>Information importante :</strong></p>
                        <ul>
                            <li>L'utilisateur recevra un email pour configurer son mot de passe</li>
                            <li>Les champs prénom et nom sont optionnels mais recommandés</li>
                            <li>L'utilisateur peut compléter son profil après la première connexion</li>
                            <li>L'email sera utilisé comme nom d'utilisateur</li>
                        </ul>
                    </div>
                </div>
            </form>
        </section>
        <footer class="modal-card-foot">
            <button class="button is-ecolux-primary" onclick="submitAddUser()">
                <span class="icon">
                    <i class="fas fa-save"></i>
                </span>
                <span>Créer l'utilisateur</span>
            </button>
            <button class="button" onclick="closeAddUserModal()">Annuler</button>
        </footer>
    </div>
</div>

<style>
.avatar-placeholder {
    width: 48px;
    height: 48px;
}

.card {
    transition: all 0.3s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.15) !important;
}

.table tr:hover {
    background-color: #f8f9fa !important;
}

.pagination-link, .pagination-previous, .pagination-next {
    transition: all 0.3s ease;
}

.pagination-link:hover, .pagination-previous:hover, .pagination-next:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.button {
    transition: all 0.3s ease;
}

.button:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
</style>

<script>
function openAddUserModal() {
    document.getElementById('addUserModal').classList.add('is-active');
}

function closeAddUserModal() {
    document.getElementById('addUserModal').classList.remove('is-active');
    document.getElementById('addUserForm').reset();
}

function viewUser(userId) {
    // Logique pour voir les détails de l'utilisateur
    console.log('Voir utilisateur:', userId);
}

function editUser(userId) {
    // Logique pour éditer l'utilisateur
    console.log('Éditer utilisateur:', userId);
}

function toggleUserStatus(userId, activate) {
    // Logique pour activer/désactiver l'utilisateur
    console.log('Toggle status pour utilisateur:', userId, 'Activer:', activate);
}

function submitAddUser() {
    const form = document.getElementById('addUserForm');
    const formData = new FormData(form);
    
    const userData = {
        email: formData.get('email'),
        first_name: formData.get('first_name') || '',
        last_name: formData.get('last_name') || '',
        user_type: formData.get('user_type'),
        phone: formData.get('phone') || null,
    };
    
    // Validation
    if (!userData.email || !userData.user_type) {
        showNotification('Veuillez remplir tous les champs obligatoires (email et type)', 'is-warning');
        return;
    }
    
    // Validation email
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(userData.email)) {
        showNotification('Veuillez saisir une adresse email valide', 'is-warning');
        return;
    }
    
    // Désactiver le bouton pendant l'envoi
    const submitBtn = document.querySelector('#addUserModal .button.is-ecolux-primary');
    const originalText = submitBtn.innerHTML;
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="icon"><i class="fas fa-spinner fa-spin"></i></span><span>Création en cours...</span>';
    
    fetch('{% url "app:create_dashboard_user" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
        },
        body: JSON.stringify(userData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'is-success');
            closeAddUserModal();
            // Recharger la page pour voir le nouvel utilisateur
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            showNotification(data.error || 'Erreur lors de la création de l\'utilisateur', 'is-danger');
        }
    })
    .catch(error => {
        console.error('Erreur:', error);
        showNotification('Erreur lors de la création de l\'utilisateur', 'is-danger');
    })
    .finally(() => {
        // Réactiver le bouton
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    });
}

// Fonction pour afficher les notifications
function showNotification(message, type) {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.style.cssText = 'position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    notification.innerHTML = `
        <button class="delete" onclick="this.parentElement.remove()"></button>
        ${message}
    `;
    
    document.body.appendChild(notification);
    
    // Supprimer automatiquement après 5 secondes
    setTimeout(() => {
        if (notification.parentElement) {
            notification.remove();
        }
    }, 5000);
}

// Fermer la modal en appuyant sur Echap
document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
        closeAddUserModal();
    }
});
</script>

{% csrf_token %}
{% endblock %}
