@extends('layouts.app')

@section('title', 'Équipements')
@section('page-title', 'Équipements')

@section('content')
<div class="space-y-6">
    <!-- En-tête -->
    <div class="flex justify-between items-center">
        <div>
            <h1 class="text-2xl font-bold text-gray-900">Équipements</h1>
            <p class="mt-1 text-sm text-gray-600">{{ auth()->user()->hasRole('Responsable du département') ? 'Équipements de votre département' : 'Gérez les équipements de l\'hôpital' }}</p>
        </div>
        @unless(auth()->user()->hasRole('Responsable du département'))
        <button type="button" data-modal-toggle="modal-new-equipment" class="inline-flex items-center px-5 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg shadow-sm hover:shadow-md transition-all">
            <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
            </svg>
            Ajouter
        </button>
        @endunless
    </div>

    @unless(auth()->user()->hasRole('Responsable du département'))
    <x-modal-form id="modal-new-equipment" title="Nouvel équipement">
        @include('components.modals.equipment', ['modalId' => 'modal-new-equipment', 'departments' => $departments, 'products' => $products ?? []])
    </x-modal-form>
    @endunless

    <!-- Filtres -->
    <div class="bg-white shadow-sm border border-gray-200 rounded-xl p-4">
        <form method="GET" action="{{ route('equipment.index') }}">
            <div class="grid grid-cols-1 md:grid-cols-{{ auth()->user()->hasRole('Responsable du département') ? '2' : '3' }} gap-4">
                <div>
                    <input type="text" name="search" value="{{ request('search') }}" placeholder="Rechercher..." class="w-full px-4 py-2.5 border border-gray-200 rounded-lg bg-white text-gray-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all">
                </div>
                @unless(auth()->user()->hasRole('Responsable du département'))
                <div>
                    <div class="relative searchable-select-filter-department" data-options='@json(collect($departments)->map(fn($d) => ["id" => (string)$d->id, "name" => $d->name])->prepend(["id" => "", "name" => "Tous les départements"])->values())' data-selected-id="{{ request('department_id') ?? '' }}">
                        <input type="hidden" name="department_id" value="{{ request('department_id') }}">
                        <button type="button" class="w-full px-4 py-2.5 border border-gray-200 rounded-lg bg-white text-gray-900 text-left flex items-center justify-between focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all searchable-select-trigger">
                            <span class="searchable-select-label truncate">{{ $departments->firstWhere('id', request('department_id'))?->name ?? 'Tous les départements' }}</span>
                            <svg class="w-4 h-4 text-gray-400 shrink-0 ml-2 searchable-select-chevron transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                            </svg>
                        </button>
                        <div class="hidden absolute z-50 mt-1 w-full bg-white border border-gray-200 rounded-lg shadow-lg overflow-hidden searchable-select-dropdown">
                            <div class="p-2 border-b border-gray-100">
                                <input type="text" placeholder="Rechercher un département..." class="searchable-select-search w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                            </div>
                            <div class="max-h-48 overflow-y-auto py-1 searchable-select-options"></div>
                        </div>
                    </div>
                </div>
                @endunless
                <div>
                    <select name="etats" onchange="this.form.submit()" class="w-full px-4 py-2.5 border border-gray-200 rounded-lg bg-white text-gray-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all">
                        <option value="">Tous les statuts</option>
                        <option value="neuf" {{ request('etats') === 'neuf' ? 'selected' : '' }}>Neuf</option>
                        <option value="bon" {{ request('etats') === 'bon' ? 'selected' : '' }}>Bon</option>
                        <option value="defectueux" {{ request('etats') === 'defectueux' ? 'selected' : '' }}>Défectueux</option>
                        <option value="hors_service" {{ request('etats') === 'hors_service' ? 'selected' : '' }}>Hors service</option>
                    </select>
                </div>
            </div>
        </form>
    </div>

    <!-- Tableau des équipements -->
    <div class="bg-white shadow-sm border border-gray-200 rounded-xl overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                            Référence
                        </th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                            Équipement
                        </th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                            Numéro de série
                        </th>
                        @unless(auth()->user()->hasRole('Responsable du département'))
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                            Département
                        </th>
                        @endunless
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                            Statut
                        </th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                            Date d'acquisition
                        </th>
                        @unless(auth()->user()->hasRole('Responsable du département'))
                        <th class="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase tracking-wider">
                            Actions
                        </th>
                        @endunless
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    @forelse($equipments as $equipment)
                    <tr class="hover:bg-blue-50/50 transition-colors">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="text-sm font-medium text-gray-700">{{ $equipment->reference ?? '-' }}</span>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm font-medium text-gray-900">{{ $equipment->product?->name ?? '-' }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="text-sm text-gray-700">{{ $equipment->serial_number ?? '-' }}</span>
                        </td>
                        @unless(auth()->user()->hasRole('Responsable du département'))
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="text-sm text-gray-700">{{ $equipment->department?->name ?? '-' }}</span>
                        </td>
                        @endunless
                        <td class="px-6 py-4 whitespace-nowrap">
                            @php
                            $etatLabels = [
                            'neuf' => 'Neuf',
                            'bon' => 'Bon',
                            'defectueux' => 'Défectueux',
                            'hors_service' => 'Hors service',
                            ];
                            $etatClasses = [
                            'neuf' => 'bg-green-100 text-green-800',
                            'bon' => 'bg-blue-100 text-blue-800',
                            'defectueux' => 'bg-amber-100 text-amber-800',
                            'hors_service' => 'bg-red-100 text-red-800',
                            ];
                            @endphp
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {{ $etatClasses[$equipment->etats] ?? 'bg-gray-100 text-gray-800' }}">
                                {{ $etatLabels[$equipment->etats] ?? $equipment->etats }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="text-sm text-gray-600">{{ $equipment->created_at?->format('d/m/Y') ?? '-' }}</span>
                        </td>
                        @unless(auth()->user()->hasRole('Responsable du département'))
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <div class="flex items-center justify-end gap-2">
                                <button type="button" data-id="{{ $equipment->id }}" data-product-id="{{ $equipment->product_id }}" data-department-id="{{ $equipment->department_id }}" data-serial-number="{{ $equipment->serial_number ?? '' }}" data-brand="{{ $equipment->brand ?? '' }}" data-etats="{{ $equipment->etats }}" onclick="openEditEquipmentModal(this)" class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-gradient-to-br from-blue-50 to-blue-100 text-blue-600 hover:from-blue-500 hover:to-blue-600 hover:text-white transform hover:scale-110 transition-all duration-200 shadow-sm hover:shadow-md" title="Modifier">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                    </svg>
                                </button>
                                <form method="POST" action="{{ route('equipment.destroy', $equipment->id) }}" class="inline-block" id="delete-form-{{ $equipment->id }}">
                                    @csrf
                                    @method('DELETE')
                                    <button type="button" onclick="openDeleteEquipmentModal('{{ $equipment->id }}')" class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-gradient-to-br from-red-50 to-red-100 text-red-600 hover:from-red-500 hover:to-red-600 hover:text-white transform hover:scale-110 transition-all duration-200 shadow-sm hover:shadow-md" title="Supprimer">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                        </svg>
                                    </button>
                                </form>
                            </div>
                        </td>
                        @endunless
                    </tr>
                    @empty
                    <tr class="hover:bg-blue-50/50 transition-colors">
                        <td colspan="{{ auth()->user()->hasRole('Responsable du département') ? 4 : 6 }}" class="px-6 py-12 text-center">
                            <div class="flex flex-col items-center">
                                <svg class="w-16 h-16 text-gray-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z" />
                                </svg>
                                <p class="text-sm font-medium text-gray-600 mb-1">Aucun équipement enregistré</p>
                            </div>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        @if($equipments->hasPages())
        <div class="px-6 py-4 border-t border-gray-200">
            {{ $equipments->links() }}
        </div>
        @endif
    </div>
</div>

@unless(auth()->user()->hasRole('Responsable du département'))
<!-- Modal d'édition de l'équipement -->
<x-modal-form id="modal-edit-equipment" title="Modifier l'équipement">
    <form method="POST" id="edit-equipment-form" class="space-y-6">
        @csrf
        @method('PUT')
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-5">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Produit / Type d'équipement <span class="text-red-500">*</span></label>
                <select name="product_id" id="edit_product_id" required class="w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    <option value="">Choisir un produit</option>
                    @foreach($products ?? [] as $p)
                    <option value="{{ $p->id }}">{{ $p->name }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Numéro de série</label>
                <input type="text" name="serial_number" id="edit_serial_number" class="w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500" placeholder="Optionnel">
            </div>
        </div>
        <div class="grid grid-cols-1 sm:grid-cols-12 gap-5">
            <div class="sm:col-span-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">Marque</label>
                <input type="text" name="brand" id="edit_brand" class="w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500" placeholder="Optionnel">
            </div>
            <div class="sm:col-span-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">Département <span class="text-red-500">*</span></label>
                <select name="department_id" id="edit_department_id" required class="w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    <option value="">Choisir un département</option>
                    @foreach($departments ?? [] as $d)
                    <option value="{{ $d->id }}">{{ $d->name }}</option>
                    @endforeach
                </select>
            </div>
            <div class="sm:col-span-12">
                <label class="block text-sm font-medium text-gray-700 mb-2">Statut</label>
                <select name="etats" id="edit_etats" class="w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    <option value="neuf">Neuf</option>
                    <option value="bon">Bon</option>
                    <option value="defectueux">Défectueux</option>
                    <option value="hors_service">Hors service</option>
                </select>
            </div>
        </div>
        @include('components.modals.modal-actions', ['modalId' => 'modal-edit-equipment', 'submitLabel' => 'Enregistrer les modifications'])
    </form>
</x-modal-form>

<!-- Composant modal de confirmation de suppression -->
<x-delete-confirmation-modal modalId="delete-equipment-modal" title="Confirmer la suppression" message="Êtes-vous sûr de vouloir supprimer cet équipement ? Cette action est irréversible." />

<script src="{{ asset('js/equipment.js') }}"></script>
@endunless
<script>
    (function() {
        function initFilterDepartmentSelect() {
            var container = document.querySelector('.searchable-select-filter-department');
            if (!container || container.dataset.initialized) return;
            container.dataset.initialized = '1';

            var options = JSON.parse(container.dataset.options || '[]');
            var hiddenInput = container.querySelector('input[type="hidden"]');
            var trigger = container.querySelector('.searchable-select-trigger');
            var label = container.querySelector('.searchable-select-label');
            var chevron = container.querySelector('.searchable-select-chevron');
            var dropdown = container.querySelector('.searchable-select-dropdown');
            var searchInput = container.querySelector('.searchable-select-search');
            var optionsContainer = container.querySelector('.searchable-select-options');
            var form = container.closest('form');
            var selectedId = container.dataset.selectedId || '';

            var selected = options.find(function(d) {
                return String(d.id) === String(selectedId);
            }) || (selectedId === '' ? options[0] : null);

            function renderOptions(filter) {
                var filtered = options.filter(function(d) {
                    return !filter || d.name.toLowerCase().indexOf(filter.toLowerCase()) >= 0;
                });
                optionsContainer.innerHTML = filtered.length ? filtered.map(function(d) {
                    var active = selected && String(selected.id) === String(d.id) ? ' bg-blue-50 text-blue-700' : '';
                    var name = (d.name || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
                    return '<button type="button" class="w-full px-4 py-2.5 text-left text-sm hover:bg-blue-50 transition-colors' + active + '" data-id="' + d.id + '">' + name + '</button>';
                }).join('') : '<p class="px-4 py-3 text-sm text-gray-500">Aucun résultat</p>';
            }

            function select(opt) {
                selected = opt;
                hiddenInput.value = opt.id;
                label.textContent = opt.name;
                label.classList.remove('text-gray-500');
                dropdown.classList.add('hidden');
                searchInput.value = '';
                renderOptions('');
                if (form) form.submit();
            }

            trigger.addEventListener('click', function(e) {
                e.preventDefault();
                var isOpen = !dropdown.classList.contains('hidden');
                dropdown.classList.toggle('hidden');
                chevron.classList.toggle('rotate-180', !isOpen);
                if (!dropdown.classList.contains('hidden')) {
                    renderOptions('');
                    searchInput.value = '';
                    setTimeout(function() {
                        searchInput.focus();
                    }, 10);
                }
            });

            searchInput.addEventListener('input', function() {
                renderOptions(this.value);
            });
            searchInput.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    dropdown.classList.add('hidden');
                    chevron.classList.remove('rotate-180');
                }
            });

            optionsContainer.addEventListener('click', function(e) {
                var btn = e.target.closest('button[data-id]');
                if (btn) select({
                    id: btn.dataset.id
                    , name: btn.textContent
                });
            });

            document.addEventListener('click', function(e) {
                if (!container.contains(e.target)) {
                    dropdown.classList.add('hidden');
                    chevron.classList.remove('rotate-180');
                }
            });

            renderOptions('');
        }
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initFilterDepartmentSelect);
        } else {
            initFilterDepartmentSelect();
        }
    })();

</script>
@endsection
