<div class="container mx-auto">
    <x-dashboard.breadcrumb :items="[
        'Dashboard' => route('home'),
        'Prescriptions' => null,
    ]" />

    @if ($errorMessage)
        <x-basics.alert class="mt-6" :type="$offlineMode ? 'warning' : 'danger'" :message="$errorMessage" />
    @endif

    <div class="shadow border border-gray-300 bg-white rounded p-4 mb-6 mt-6">
        <form wire:submit.prevent="refreshPrescriptions" class="flex flex-wrap gap-4 items-end">
            <div class="flex-1 min-w-[220px]">
                <x-basics.input name="search" label="Rechercher" placeholder="Référence ou nom du client"
                    wire:model.live.debounce.500ms="search" mb="0" />
            </div>

            <div class="flex-1 min-w-[220px]">
                <x-basics.select name="status" label="Statut" placeholder="Tous" :options="$statusOptions" optionLabel="label"
                    optionValue="value" wire:model="status" mb="0" />
            </div>

            <div class="flex-none min-w-[150px]">
                <x-basics.select name="perPage" label="Éléments par page" :options="$perPageOptions" optionLabel="label"
                    optionValue="value" wire:model="perPage" mb="0" />
            </div>

            <div class="flex gap-2 flex-none">
                <x-basics.button type="submit" wire:loading.attr="disabled">
                    <i class="ph ph-arrows-clockwise mr-2"></i>
                    Actualiser
                </x-basics.button>

                <x-basics.button type="button" variant="outline" wire:click="resetFilters"
                    wire:loading.attr="disabled">
                    <i class="ph ph-arrow-counter-clockwise mr-2"></i>
                    Réinitialiser
                </x-basics.button>
            </div>
        </form>
    </div>

    <div class="bg-white border border-gray-300 rounded overflow-hidden shadow relative">
        <div wire:loading.flex class="absolute inset-0 bg-white/70 backdrop-blur-sm z-10 items-center justify-center">
            <x-basics.spinner size="lg" text="Chargement des prescriptions..." />
        </div>

        <div class="p-4 border-b flex flex-col md:flex-row md:items-center md:justify-between gap-2">
            <div>
                <h4 class="font-semibold text-gray-800">Liste des prescriptions</h4>                
            </div>
            <div class="text-sm text-gray-500">
                {{ $prescriptions->total() }} résultat{{ $prescriptions->total() > 1 ? 's' : '' }}
            </div>
        </div>

        <div class="overflow-x-auto">
            @if ($prescriptions->count() > 0)
                <table class="min-w-full text-sm">
                    <thead class="bg-gray-100">
                        <tr class="text-left text-gray-700 font-medium">
                            <th class="p-3 w-10">#</th>
                            <th class="p-3">Référence</th>
                            <th class="p-3">Client</th>
                            <th class="p-3">Produits</th>
                            <th class="p-3">Distance</th>
                            <th class="p-3">Statut</th>
                            <th class="p-3">Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($prescriptions as $prescription)
                            <tr class="border-t hover:bg-gray-50 transition-colors">
                                <td class="px-3 py-2">
                                    {{ $loop->iteration + ($prescriptions->currentPage() - 1) * $prescriptions->perPage() }}.
                                </td>
                                <td class="px-3 py-2 font-semibold text-gray-800">
                                    @php
                                        $reference = $prescription['reference'] ?? ($prescription->reference ?? '—');
                                    @endphp
                                    <x-basics.link href="{{ route('prescriptions.show', $reference) }}" wire:navigate
                                        size="md">
                                        {{ $reference }}
                                    </x-basics.link>
                                </td>
                                <td class="px-3 py-2 text-gray-700">
                                    {{ $prescription['customer_name'] ?? ($prescription->customer_name ?? 'Client inconnu') }}
                                </td>
                                <td class="px-3 py-2 text-gray-600">
                                    {{ $prescription['products_count'] ?? ($prescription->products_count ?? 0) }}
                                </td>
                                <td class="px-3 py-2 text-gray-600">
                                    @php
                                        $distance = $prescription['distance'] ?? ($prescription->distance ?? null);
                                    @endphp
                                    {{ $distance ? number_format($distance, 2, ',', ' ') . ' km' : '—' }}
                                </td>
                                <td class="px-3 py-2">
                                    @php
                                        $status = $prescription['status'] ?? ($prescription->status ?? null);
                                    @endphp
                                    {!! \App\Models\Prescription::getStatusBadge($status) !!}
                                </td>
                                <td class="px-3 py-2 text-gray-600">
                                    @php
                                        $createdAt = $prescription['created_at'] ?? ($prescription->created_at ?? null);
                                        if (is_string($createdAt)) {
                                            $createdAt = \Carbon\Carbon::parse($createdAt);
                                        }
                                    @endphp
                                    {{ $createdAt ? $createdAt->format('d/m/Y H:i') : '—' }}
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            @else
                <div class="text-center py-12">
                    @if ($offlineMode)
                        <div class="text-gray-500">
                            <i class="ph ph-wifi-slash text-4xl mb-4"></i>
                            <p class="text-lg font-medium">Mode hors ligne</p>
                            <p class="text-sm">
                                Vous ne pouvez pas voir les prescriptions car vous êtes hors ligne. Veuillez vous
                                connecter à internet pour accéder aux prescriptions.
                            </p>
                        </div>
                    @elseif ($errorMessage)
                        <div class="text-gray-500">
                            <i class="ph ph-prescription text-4xl mb-4"></i>
                            <p class="text-lg font-medium">Erreur de récupération</p>
                            <p class="text-sm">
                                {{ $errorMessage }}
                            </p>
                            <p class="text-xs mt-2 text-gray-400">
                                Si le problème persiste, vérifiez votre connexion internet et réessayez.
                            </p>
                        </div>
                    @else
                        <div class="text-gray-500">
                            <i class="ph ph-prescription text-4xl mb-4"></i>
                            <p class="text-lg font-medium">Aucune prescription trouvée</p>
                            <p class="text-sm">
                                Aucune prescription n'est disponible pour le moment. Les prescriptions apparaîtront ici
                                lorsqu'elles seront créées.
                            </p>
                        </div>
                    @endif
                </div>
            @endif
        </div>

        @if ($prescriptions->hasPages())
            <div class="px-4 py-4 border-t">
                {{ $prescriptions->withQueryString()->links() }}
            </div>
        @endif
    </div>
</div>
