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

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

{% set statusColors = {
    'en_cours':  {bg: 'bg-blue-50',  text: 'text-blue-700',  border: 'border-blue-200'},
    'a_valider': {bg: 'bg-amber-50', text: 'text-amber-700', border: 'border-amber-200'},
    'valide':    {bg: 'bg-green-50', text: 'text-green-700', border: 'border-green-200'},
    'annule':    {bg: 'bg-gray-100', text: 'text-gray-600',  border: 'border-gray-200'},
} %}

{% block content %}
<div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-10 space-y-6">
    <div>
        <h1 class="font-display font-bold text-3xl text-gray-900 mb-2">Inventaires</h1>
        <p class="text-gray-500 text-sm">Liste de vos inventaires. Recherche par plaque, VIN, concession ou lieu.</p>
    </div>

    {# ─── Filtres ─── #}
    <form method="get" class="bg-white border border-gray-200 rounded-2xl p-4 shadow-sm grid grid-cols-1 sm:grid-cols-12 gap-3">
        <div class="sm:col-span-4">
            <label for="q" class="block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1">Recherche</label>
            <input id="q" name="q" type="search" value="{{ q }}" placeholder="Plaque, VIN, concession, lieu…"
                   class="w-full px-3 py-2 bg-white border border-gray-300 rounded-lg text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-red-brand focus:border-transparent text-sm">
        </div>
        <div class="sm:col-span-2">
            <label for="status" class="block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1">Statut</label>
            <select id="status" name="status" class="w-full px-3 py-2 bg-white border border-gray-300 rounded-lg text-gray-900 focus:outline-none focus:ring-2 focus:ring-red-brand focus:border-transparent text-sm">
                <option value="">Tous</option>
                {% for st in allStatuses %}
                    <option value="{{ st }}" {% if currentStatus == st %}selected{% endif %}>{{ statusLabels[st] }}</option>
                {% endfor %}
            </select>
        </div>
        <div class="sm:col-span-3">
            <label for="concession" class="block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1">Concession</label>
            <select id="concession" name="concession" class="w-full px-3 py-2 bg-white border border-gray-300 rounded-lg text-gray-900 focus:outline-none focus:ring-2 focus:ring-red-brand focus:border-transparent text-sm">
                <option value="">Toutes</option>
                {% for id, name in allConcessions %}
                    <option value="{{ id }}" {% if currentConcession == id %}selected{% endif %}>{{ name }}</option>
                {% endfor %}
            </select>
        </div>
        <div class="sm:col-span-3">
            <label for="creator" class="block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1">Créateur</label>
            <select id="creator" name="creator" class="w-full px-3 py-2 bg-white border border-gray-300 rounded-lg text-gray-900 focus:outline-none focus:ring-2 focus:ring-red-brand focus:border-transparent text-sm">
                <option value="">Tous</option>
                {% for email in allCreators %}
                    <option value="{{ email }}" {% if currentCreator == email %}selected{% endif %}>{{ email }}</option>
                {% endfor %}
            </select>
        </div>
        <div class="sm:col-span-2">
            <label for="archived" class="block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1">Affichage</label>
            <select id="archived" name="archived" class="w-full px-3 py-2 bg-white border border-gray-300 rounded-lg text-gray-900 focus:outline-none focus:ring-2 focus:ring-red-brand focus:border-transparent text-sm">
                <option value="active" {{ currentArchived == 'active' ? 'selected' }}>Actifs</option>
                <option value="archived" {{ currentArchived == 'archived' ? 'selected' }}>Archivés</option>
                <option value="all" {{ currentArchived == 'all' ? 'selected' }}>Tous</option>
            </select>
        </div>
        <div class="sm:col-span-1 flex items-end">
            <button type="submit" class="w-full px-4 py-2 bg-red-brand text-white text-sm font-medium rounded-lg hover:bg-red-brand-dark transition-colors">OK</button>
        </div>
    </form>

    <p class="text-sm text-gray-500">{{ total }} inventaire{{ total > 1 ? 's' }} trouvé{{ total > 1 ? 's' }}</p>

    {# ─── Liste ─── #}
    {% if sessions|length == 0 %}
        <div class="text-center py-16 bg-gray-50 border border-gray-200 rounded-2xl">
            <p class="text-gray-900 font-medium mb-1">Aucun inventaire correspondant</p>
            <p class="text-gray-500 text-sm">Modifiez vos critères ou lancez un nouveau scan.</p>
        </div>
    {% else %}
      <div data-controller="inventaires">
        {% if is_granted('SCAN_CREATE') %}
            {# Barre d'action de fusion : visible dès qu'au moins un inventaire est coché. #}
            <div data-inventaires-target="mergeBar" class="hidden items-center justify-between gap-3 bg-blue-50 border border-blue-200 rounded-2xl px-4 py-3 mb-3 text-sm">
                <span class="text-blue-900"><span data-inventaires-target="mergeCount">0</span> inventaire(s) sélectionné(s) — fusionnez-les en un nouvel inventaire.</span>
                <span class="flex items-center gap-2 shrink-0">
                    <button type="button" data-action="inventaires#merge"
                            class="px-3 py-1.5 text-xs font-medium bg-red-brand text-white rounded-lg hover:bg-red-brand-dark transition-colors">Fusionner la sélection</button>
                    <button type="button" data-action="inventaires#clearSelection"
                            class="px-3 py-1.5 text-xs font-medium text-blue-700 border border-blue-300 rounded-lg hover:bg-blue-100 transition-colors">Tout décocher</button>
                </span>
            </div>
        {% endif %}
        <ul class="space-y-3">
            {% for s in sessions %}
                {% set c = statusColors[s.status] %}
                <li data-inventaires-target="card" data-id="{{ s.id }}" class="bg-white border border-gray-200 rounded-2xl p-4 shadow-sm">
                    <div class="flex flex-col lg:flex-row lg:items-start justify-between gap-3">
                        {% if is_granted('SCAN_CREATE') %}
                            <input type="checkbox" data-action="inventaires#toggleSelect" data-inventaires-id-param="{{ s.id }}"
                                   class="mt-1 h-4 w-4 shrink-0 rounded border-gray-300 text-red-brand focus:ring-red-brand cursor-pointer"
                                   title="Sélectionner pour fusionner">
                        {% endif %}
                        <div class="min-w-0 flex-1">
                            <div class="flex items-center gap-2 flex-wrap mb-1">
                                <span class="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium border {{ c.bg }} {{ c.text }} {{ c.border }}" data-inventaires-target="statusBadge">{{ statusLabels[s.status] }}</span>
                                {% if s.scanType %}<span class="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-semibold border bg-indigo-50 text-indigo-700 border-indigo-200">{{ s.scanType|scan_type_label }}</span>{% endif %}
                                {% if s.archived %}<span class="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium border bg-gray-100 text-gray-500 border-gray-200">Archivé</span>{% endif %}
                                <a href="{{ path('app_inventaire_detail', {id: s.id}) }}" class="font-medium text-gray-900 text-sm truncate hover:text-red-brand hover:underline underline-offset-2 transition-colors">{{ s.label }}</a>
                            </div>
                            <p class="text-xs text-gray-500">
                                {{ s.count }} véhicule{{ s.count > 1 ? 's' }} · {{ s.totalFiles }} fichier{{ s.totalFiles > 1 ? 's' }}
                                · {{ s.createdAt|date('d/m/Y à H:i') }}
                                · par <span class="text-gray-700">{{ s.userEmail }}</span>
                                {% if s.locationNote %} · <span class="text-gray-700">📍 {{ s.locationNote }}</span>{% endif %}
                            </p>
                            {% if s.concessions|length > 0 %}
                                <p class="text-xs text-gray-500 mt-1 flex items-start gap-1.5">
                                    <svg class="w-3.5 h-3.5 text-gray-400 shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" /></svg>
                                    <span class="text-gray-700">{{ s.concessions|concession_names|join(' · ') }}</span>
                                </p>
                            {% endif %}
                        </div>
                        {# Boutons groupés par fonction : Consultation · Statut · Gestion #}
                        <div class="flex items-center gap-x-3 gap-y-2 shrink-0 flex-wrap">
                            {# ── Consultation / export ── #}
                            <div class="flex items-center gap-1.5">
                                <a href="{{ path('app_inventaire_detail', {id: s.id}) }}"
                                   class="px-3 py-1.5 text-xs font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">Voir</a>
                                <button data-action="inventaires#export" data-inventaires-id-param="{{ s.id }}"
                                        class="px-3 py-1.5 text-xs font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">Excel</button>
                                {# « PDF + photos » réservé aux inventaires validés. Si non validé : bouton grisé
                                   qui affiche le message d'indisponibilité au clic (au lieu d'être masqué). #}
                                {% if s.status == 'valide' %}
                                    {% if s.isOnS3 %}
                                        <a href="{{ path('app_report_photos_web', {id: s.id}) }}" target="_blank" rel="noopener"
                                           class="px-3 py-1.5 text-xs font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">PDF + photos</a>
                                    {% else %}
                                        <button data-action="inventaires#exportPdfPhotos" data-inventaires-id-param="{{ s.id }}"
                                                class="px-3 py-1.5 text-xs font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">PDF + photos</button>
                                    {% endif %}
                                {% else %}
                                    <button type="button" data-action="inventaires#reportPhotosBlocked"
                                            class="px-3 py-1.5 text-xs font-medium text-gray-400 border border-gray-200 bg-gray-50 rounded-lg cursor-not-allowed"
                                            title="Disponible uniquement lorsque l'inventaire est validé">PDF + photos</button>
                                {% endif %}
                            </div>

                            {# ── Statut (workflow) — SUBMIT ouvre « À valider » à l'opérateur sur un scan en cours ── #}
                            {% set canChangeStatus = is_granted('SCAN_CHANGE_STATUS', s) %}
                            {% set canSubmit = is_granted('SCAN_SUBMIT', s) %}
                            {% if canChangeStatus or canSubmit %}
                                <div class="flex items-center gap-1.5 sm:border-l sm:border-gray-200 sm:pl-3">
                                    {# Réouverture : « À valider » renvoyable en correction par SUPERVISEUR / AUDIT /
                                       ADMIN (SCAN_CHANGE_STATUS) ; « Validé »/« Annulé » → ADMIN uniquement. #}
                                    {% if (s.status == 'a_valider' and canChangeStatus) or (is_granted('ROLE_ADMIN') and s.status != 'en_cours') %}
                                        <button data-action="inventaires#setStatus" data-inventaires-id-param="{{ s.id }}" data-inventaires-status-param="en_cours"
                                                class="px-3 py-1.5 text-xs font-medium text-blue-700 border border-blue-200 rounded-lg hover:bg-blue-50 transition-colors">Rouvrir</button>
                                    {% endif %}
                                    {% if s.status == 'en_cours' %}
                                        {% if canSubmit %}
                                            <button data-action="inventaires#setStatus" data-inventaires-id-param="{{ s.id }}" data-inventaires-status-param="a_valider"
                                                    class="px-3 py-1.5 text-xs font-medium bg-amber-500 text-white rounded-lg hover:bg-amber-600 transition-colors">À valider</button>
                                        {% endif %}
                                    {% elseif canChangeStatus and s.status != 'valide' %}
                                        <button data-action="inventaires#setStatus" data-inventaires-id-param="{{ s.id }}" data-inventaires-status-param="valide"
                                                class="px-3 py-1.5 text-xs font-medium bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors">Valider</button>
                                    {% endif %}
                                    {% if canChangeStatus and s.status != 'annule' %}
                                        <button data-action="inventaires#setStatus" data-inventaires-id-param="{{ s.id }}" data-inventaires-status-param="annule"
                                                class="px-3 py-1.5 text-xs font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">Annuler</button>
                                    {% endif %}
                                </div>
                            {% endif %}

                            {# ── Gestion (cycle de vie) ── #}
                            {% if is_granted('SCAN_ARCHIVE', s) or is_granted('SCAN_DELETE', s) %}
                                <div class="flex items-center gap-1.5 sm:border-l sm:border-gray-200 sm:pl-3">
                                    {% if is_granted('SCAN_ARCHIVE', s) %}
                                        <button data-action="inventaires#archive" data-inventaires-id-param="{{ s.id }}"
                                                class="px-3 py-1.5 text-xs font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">{{ s.archived ? 'Désarchiver' : 'Archiver' }}</button>
                                    {% endif %}
                                    {% if is_granted('SCAN_DELETE', s) %}
                                        <button data-action="inventaires#remove" data-inventaires-id-param="{{ s.id }}"
                                                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">Suppr.</button>
                                    {% endif %}
                                </div>
                            {% endif %}
                        </div>
                    </div>
                </li>
            {% endfor %}
        </ul>
      </div>

        {# ─── Pagination ─── #}
        {% if totalPages > 1 %}
            <div class="flex items-center justify-center gap-1 pt-2">
                {% for p in 1..totalPages %}
                    <a href="{{ path('app_inventaires', {q: q, status: currentStatus, concession: currentConcession, creator: currentCreator, archived: currentArchived, page: p}) }}"
                       class="px-3 py-1.5 text-xs font-medium rounded-lg {{ p == page ? 'bg-red-brand text-white' : 'text-gray-600 hover:bg-gray-100 border border-gray-300' }}">{{ p }}</a>
                {% endfor %}
            </div>
        {% endif %}
    {% endif %}
</div>
{% endblock %}
