{% extends 'app_base.html.twig' %}

{% block title %}Utilisateurs — Scan Inventaire{% endblock %}

{# formId : id d'un <form> externe à relier (attribut HTML form="…"), pour un usage
   dans une ligne de tableau où le <form> ne peut pas envelopper le <tr>. #}
{% macro concession_picker(user, concessions, formId = null) %}
    <details class="rounded-lg border border-gray-200 bg-white" data-controller="onboarding">
        <summary class="px-3 py-2 text-sm text-gray-600 cursor-pointer flex items-center justify-between gap-2">
            <span>Concessions <span data-onboarding-target="count"></span></span>
            <span class="text-xs text-gray-400 shrink-0">{{ user.concessions|length }} actuelle(s)</span>
        </summary>
        <div class="p-3 border-t border-gray-200 space-y-2">
            <input type="text" placeholder="Rechercher…" data-onboarding-target="search" data-action="input->onboarding#filter"
                   class="w-full px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-red-brand">
            <div class="h-44 overflow-y-auto rounded-lg border border-gray-200 divide-y divide-gray-100">
                {# Concessions demandées/attribuées (IDs) en tête de liste pour éviter de scroller. #}
                {% set ordered = user.concessions|merge(concessions|keys|filter(id => id not in user.concessions)) %}
                {% for id in ordered %}
                    {% set label = concessions[id]|default(id|concession_name) %}
                    <label data-onboarding-target="item" data-name="{{ label|lower }}"
                           class="flex items-center gap-2 px-3 py-1.5 cursor-pointer hover:bg-gray-50 has-[:checked]:bg-blue-50 {{ id in user.concessions ? 'bg-blue-50/60' }}">
                        <input type="checkbox" name="concessions[]" value="{{ id }}" class="accent-red-brand"
                               {% if formId %}form="{{ formId }}"{% endif %}
                               data-onboarding-target="checkbox" data-action="change->onboarding#updateCount"
                               {{ id in user.concessions ? 'checked' }}>
                        <span class="text-sm text-gray-700">{{ label }}</span>
                    </label>
                {% endfor %}
            </div>
        </div>
    </details>
{% endmacro %}

{% block content %}
<div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-10 space-y-8">
    <div>
        <h1 class="font-display font-bold text-3xl text-gray-900 mb-1">Utilisateurs</h1>
        <p class="text-gray-500 text-sm">Validation des demandes d'accès et gestion des comptes.</p>
    </div>

    {# ─── Demandes en attente ─── #}
    <section>
        <h2 class="text-sm font-semibold text-gray-900 uppercase tracking-wide mb-3">
            Demandes en attente
            {% if pending|length > 0 %}<span class="ml-1 inline-flex items-center justify-center px-2 py-0.5 text-xs rounded-full bg-amber-100 text-amber-800">{{ pending|length }}</span>{% endif %}
        </h2>
        {% if pending|length == 0 %}
            <p class="text-sm text-gray-400 bg-gray-50 border border-gray-200 rounded-xl px-4 py-6 text-center">Aucune demande en attente.</p>
        {% else %}
            <div class="space-y-4">
                {% for u in pending %}
                    <form method="post" action="{{ path('app_users_action', {id: u.id}) }}" class="bg-white border border-gray-200 rounded-2xl p-5 shadow-sm space-y-4">
                        <input type="hidden" name="_token" value="{{ csrf_token('user_' ~ u.id) }}">
                        <div class="flex flex-wrap items-center justify-between gap-2">
                            <div>
                                <p class="font-semibold text-gray-900">{{ u.email }}</p>
                                <p class="text-xs text-gray-500">Demande du {{ u.createdAt|date('d/m/Y H:i') }} · Groupe souhaité : <strong>{{ groupLabels[u.requestedRole] ?? '—' }}</strong></p>
                                <div class="mt-2 flex items-start gap-1.5 flex-wrap text-xs">
                                    <span class="text-gray-500 shrink-0 mt-0.5">Concessions demandées :</span>
                                    {% if u.concessions|length > 0 %}
                                        {% for c in u.concessions %}
                                            <span class="inline-flex items-center px-2 py-0.5 rounded-md bg-blue-50 text-blue-700 border border-blue-200 font-medium">{{ c|concession_name }}</span>
                                        {% endfor %}
                                    {% else %}
                                        <span class="text-amber-600 font-medium">aucune concession demandée</span>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1.5">Groupe attribué</label>
                                <select name="group" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-red-brand">
                                    {% for g in groups %}
                                        {% if g != 'ROLE_ADMIN' or canManageAdmin %}
                                            <option value="{{ g }}" {{ g == u.requestedRole ? 'selected' }}>{{ groupLabels[g] }}</option>
                                        {% endif %}
                                    {% endfor %}
                                </select>
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1.5">Concessions</label>
                                {{ _self.concession_picker(u, concessions) }}
                            </div>
                        </div>
                        <div class="flex items-center justify-end gap-2">
                            <button type="submit" name="action" value="refuse"
                                    class="px-4 py-2 text-sm font-medium text-red-700 border border-red-200 rounded-lg hover:bg-red-50 transition-colors">Refuser</button>
                            <button type="submit" name="action" value="validate"
                                    class="px-4 py-2 text-sm font-medium bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors">Valider</button>
                        </div>
                    </form>
                {% endfor %}
            </div>
        {% endif %}
    </section>

    {# ─── Comptes ─── #}
    <section>
        <h2 class="text-sm font-semibold text-gray-900 uppercase tracking-wide mb-3">Comptes</h2>
        {% if others|length == 0 %}
            <p class="text-sm text-gray-400 bg-gray-50 border border-gray-200 rounded-xl px-4 py-6 text-center">Aucun compte.</p>
        {% else %}
            {# Tableau compact : les contrôles de chaque ligne sont reliés à un <form> caché
               (déclaré sous le tableau) via l'attribut HTML form="…", car un <form> ne peut
               pas envelopper un <tr>. #}
            <div class="bg-white border border-gray-200 rounded-2xl shadow-sm overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="text-left text-xs text-gray-500 uppercase tracking-wide border-b border-gray-200">
                            <th class="px-4 py-2.5 font-medium">Compte</th>
                            <th class="px-4 py-2.5 font-medium whitespace-nowrap">Statut</th>
                            <th class="px-4 py-2.5 font-medium">Groupe</th>
                            <th class="px-4 py-2.5 font-medium min-w-[230px]">Concessions</th>
                            <th class="px-4 py-2.5 font-medium text-right whitespace-nowrap">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100">
                        {% for u in others %}
                            {% set formId = 'user-form-' ~ u.id %}
                            {% set statusBadge = {
                                'active':     {label: 'Actif',      cls: 'bg-green-50 text-green-700 border-green-200'},
                                'refused':    {label: 'Refusé',     cls: 'bg-red-50 text-red-700 border-red-200'},
                                'onboarding': {label: 'Inscription', cls: 'bg-gray-100 text-gray-600 border-gray-200'},
                            }[u.status] ?? {label: u.status, cls: 'bg-gray-100 text-gray-600 border-gray-200'} %}
                            <tr class="hover:bg-gray-50 align-top">
                                <td class="px-4 py-2.5">
                                    <p class="font-medium text-gray-900 break-all">{{ u.email }}</p>
                                    {% if u.validatedAt %}
                                        <p class="text-xs text-gray-400 mt-0.5">validé le {{ u.validatedAt|date('d/m/Y') }}{% if u.validatedBy %} par {{ u.validatedBy }}{% endif %}</p>
                                    {% endif %}
                                </td>
                                <td class="px-4 py-2.5 whitespace-nowrap">
                                    <span class="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium border {{ statusBadge.cls }}">{{ statusBadge.label }}</span>
                                </td>
                                <td class="px-4 py-2.5">
                                    <select name="group" form="{{ formId }}"
                                            class="w-40 px-2.5 py-1.5 border border-gray-300 rounded-lg text-sm bg-white focus:outline-none focus:ring-2 focus:ring-red-brand">
                                        {% for g in groups %}
                                            {% if g != 'ROLE_ADMIN' or canManageAdmin %}
                                                <option value="{{ g }}" {{ g == u.group ? 'selected' }}>{{ groupLabels[g] }}</option>
                                            {% endif %}
                                        {% endfor %}
                                    </select>
                                </td>
                                <td class="px-4 py-2.5">
                                    {{ _self.concession_picker(u, concessions, formId) }}
                                </td>
                                <td class="px-4 py-2.5">
                                    <div class="flex items-center justify-end gap-1.5 whitespace-nowrap">
                                        {% if u.email != app.user.userIdentifier and (u.group != 'ROLE_ADMIN' or canManageAdmin) %}
                                            <button type="submit" name="action" value="delete" form="{{ formId }}"
                                                    onclick="return confirm('Supprimer définitivement le compte {{ u.email|e('js') }} ? Ses inventaires existants seront conservés.')"
                                                    class="px-3 py-1.5 text-xs font-medium text-red-700 border border-red-200 rounded-lg hover:bg-red-50 transition-colors">Supprimer</button>
                                        {% endif %}
                                        {% if u.status != 'active' %}
                                            <button type="submit" name="action" value="validate" form="{{ formId }}"
                                                    class="px-3 py-1.5 text-xs font-medium bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors">Activer</button>
                                        {% else %}
                                            <button type="submit" name="action" value="update" form="{{ formId }}"
                                                    class="px-3 py-1.5 text-xs font-medium bg-red-brand text-white rounded-lg hover:bg-red-brand-dark transition-colors">Mettre à jour</button>
                                        {% endif %}
                                    </div>
                                </td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            {# Formulaires cachés des lignes du tableau (un par compte). #}
            {% for u in others %}
                <form id="user-form-{{ u.id }}" method="post" action="{{ path('app_users_action', {id: u.id}) }}">
                    <input type="hidden" name="_token" value="{{ csrf_token('user_' ~ u.id) }}">
                </form>
            {% endfor %}
        {% endif %}
    </section>
</div>
{% endblock %}
