<div class="container mx-auto">
    @php
        $data = $prescription ?? [];
    @endphp

    <x-dashboard.breadcrumb :items="[
        'Dashboard' => route('home'),
        'Prescriptions' => route('prescriptions.index'),
        $reference => null,
    ]">
        <x-slot name="action">
            <div class="flex items-center gap-2">
                @if ($prescriptionObj)
                    <x-dashboard.prescriptions.dropdown :prescription="$prescriptionObj" :isOnline="!$offlineMode" />
                @endif
            </div>
        </x-slot>
    </x-dashboard.breadcrumb>

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

    <div class="flex flex-col lg:flex-row gap-6 mt-6">
        <!-- Main Content -->
        <div class="w-full lg:w-8/12 space-y-6">
            <!-- Prescription Details -->
            <x-basics.card title="Informations de la Prescription" subtitle="Détails complets de la prescription">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Reference -->
                    <div class="bg-gray-50 rounded-lg p-4">
                        <div class="flex items-center mb-3">
                            <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center mr-3">
                                <i class="ph ph-hash text-blue-600"></i>
                            </div>
                            <div>
                                <h3 class="font-semibold text-gray-900">Référence</h3>
                                <p class="text-sm text-gray-600">{{ data_get($data, 'reference', $reference) }}</p>
                            </div>
                        </div>
                    </div>

                    <!-- Status -->
                    <div class="bg-gray-50 rounded-lg p-4">
                        <div class="flex items-center mb-3">
                            <div class="w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center mr-3">
                                <i class="ph ph-info text-orange-600"></i>
                            </div>
                            <div>
                                <h3 class="font-semibold text-gray-900">Statut</h3>
                                <div class="text-sm mt-1">
                                    {!! \App\Models\Prescription::getStatusName(data_get($data, 'status')) !!}
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Customer Name -->
                    <div class="bg-gray-50 rounded-lg p-4">
                        <div class="flex items-center mb-3">
                            <div class="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center mr-3">
                                <i class="ph ph-user text-green-600"></i>
                            </div>
                            <div>
                                <h3 class="font-semibold text-gray-900">Client</h3>
                                <p class="text-sm text-gray-600">
                                    {{ data_get($data, 'customer_name', 'Client inconnu') }}
                                </p>
                            </div>
                        </div>
                    </div>


                    <!-- Doctor Information -->
                    @if (data_get($data, 'doctor.name'))
                        <div class="bg-gray-50 rounded-lg p-4">
                            <div class="flex items-center mb-3">
                                <div class="w-10 h-10 bg-indigo-100 rounded-lg flex items-center justify-center mr-3">
                                    <i class="ph ph-user-md text-indigo-600"></i>
                                </div>
                                <div>
                                    <h3 class="font-semibold text-gray-900">Médecin</h3>
                                    <p class="text-sm text-gray-600">{{ data_get($data, 'doctor.name') }}</p>
                                    @if (data_get($data, 'doctor.cnom'))
                                        <p class="text-xs text-gray-500 mt-1">CNOM: {{ data_get($data, 'doctor.cnom') }}
                                        </p>
                                    @endif
                                    @if (data_get($data, 'doctor.qualification'))
                                        <p class="text-xs text-gray-500 mt-1">
                                            Qualification:
                                            {{ ucfirst(str_replace('_', ' ', data_get($data, 'doctor.qualification'))) }}
                                        </p>
                                    @endif
                                </div>
                            </div>
                        </div>
                    @endif
                </div>

                <!-- Notes -->
                @if (data_get($data, 'notes'))
                    <div class="mt-6 bg-yellow-50 rounded-lg p-4">
                        <div class="flex items-start">
                            <div class="w-10 h-10 bg-yellow-100 rounded-lg flex items-center justify-center mr-3 mt-1">
                                <i class="ph ph-note text-yellow-600"></i>
                            </div>
                            <div>
                                <h3 class="font-semibold text-gray-900 mb-2">Notes</h3>
                                <p class="text-sm text-gray-600 whitespace-pre-line">{{ data_get($data, 'notes') }}</p>
                            </div>
                        </div>
                    </div>
                @endif
            </x-basics.card>

            <!-- Products -->
            <x-basics.card title="Produits Prescrits" subtitle="Liste des produits de la prescription">
                @if (!empty(data_get($data, 'products', [])))
                    <div class="space-y-4">
                        @foreach (data_get($data, 'products', []) as $product)
                            <div class="bg-gray-50 border border-gray-200 rounded-lg p-4">
                                <div class="flex items-start justify-between">
                                    <div class="flex items-start space-x-4 flex-1">
                                        <div
                                            class="w-12 h-12 bg-gradient-to-br from-blue-100 to-blue-200 rounded-lg flex items-center justify-center flex-shrink-0">
                                            <i class="ph ph-pill text-blue-600 text-lg"></i>
                                        </div>
                                        <div class="min-w-0 flex-1">
                                            <h3 class="font-semibold text-gray-900 text-lg">
                                                {{ $product['name'] ?? 'Produit sans nom' }}
                                            </h3>
                                            <div class="mt-2 space-y-1">
                                                <p class="text-sm text-gray-600">
                                                    <span class="font-medium">Quantité:</span>
                                                    {{ $product['quantity'] ?? '—' }}
                                                </p>
                                                @if (!empty($product['dosage']))
                                                    <p class="text-sm text-gray-600">
                                                        <span class="font-medium">Posologie:</span>
                                                        {{ $product['dosage'] }}
                                                    </p>
                                                @endif
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>

                    <!-- Summary -->
                    <div class="mt-6 pt-6 border-t border-gray-200">
                        <div class="flex flex-col sm:flex-row justify-between items-center gap-4">
                            <div class="text-center sm:text-right">
                                <p class="text-sm text-gray-500">Total des produits</p>
                                <p class="text-2xl font-bold text-gray-900">{{ count(data_get($data, 'products', [])) }}
                                </p>
                            </div>
                        </div>
                    </div>
                @else
                    <div class="text-center py-8">
                        <div class="text-gray-500">
                            <i class="ph ph-pill text-4xl mb-4"></i>
                            <p class="text-lg font-medium">Aucun produit renseigné</p>
                            <p class="text-sm">Aucun produit n'a été ajouté à cette prescription</p>
                        </div>
                    </div>
                @endif
            </x-basics.card>


            @if (data_get($data, 'location.latitude') && data_get($data, 'location.longitude'))
            <!-- Map -->
            <x-basics.card title="Carte" subtitle="Carte de la pharmacie">
                <div class="space-y-2">
                    <div class="border border-gray-300 rounded-lg overflow-hidden relative" wire:ignore>
                        <div id="customer-map" class="h-96 w-full bg-gray-100 flex items-center justify-center">
                            <div class="text-gray-500">
                                <div
                                    class="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600 mx-auto mb-2">
                                </div>
                                <p class="text-sm">Chargement de la carte...</p>
                            </div>
                        </div>
                    </div>
                    <p class="text-sm text-gray-500">Position estimée de l'établissement.</p>
                </div>
            </x-basics.card>
            @endif
        </div>

        <!-- Sidebar -->
        <div class="w-full lg:w-4/12 space-y-6">
            <x-dashboard.prescriptions.sidebar :prescription="$prescription" />
        </div>
    </div>

    @if (data_get($data, 'location.latitude') && data_get($data, 'location.longitude'))
        @push('scripts')
            <!-- Use local Leaflet files for offline compatibility -->
            <link rel="stylesheet" href="{{ asset('plugins/leaflet/leaflet.css') }}" />
            <script src="{{ asset('plugins/leaflet/leaflet.js') }}"></script>
            <script>
                window.customerMap = window.customerMap || {};
                window.customerMap.map = null;
                window.customerMap.marker = null;

                const defaultLat = @json(data_get($data, 'location.latitude') ?? -4.325);
                const defaultLng = @json(data_get($data, 'location.longitude') ?? 15.322);

                function initCustomerMap() {
                    const mapElement = document.getElementById('customer-map');
                    if (!mapElement) {
                        return;
                    }

                    if (typeof L === 'undefined') {
                        console.error('Leaflet library not loaded.');
                        mapElement.innerHTML =
                            '<div class="flex items-center justify-center h-full bg-gray-100 text-gray-500"><p>Impossible de charger la carte.</p></div>';
                        return;
                    }

                    if (window.customerMap.map) {
                        window.customerMap.map.remove();
                        window.customerMap.map = null;
                        window.customerMap.marker = null;
                    }

                    try {
                        mapElement.innerHTML = '';
                        mapElement.className = 'h-96 w-full';

                        window.customerMap.map = L.map('customer-map').setView([defaultLat, defaultLng], 13);
                        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                            attribution: '© OpenStreetMap contributors'
                        }).addTo(window.customerMap.map);

                        const markerIcon = L.divIcon({
                            html: `
                        <div style="
                            width: 32px;
                            height: 32px;
                            background-color: #4f46e5;
                            border-radius: 50%;
                            border: 2px solid white;
                            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            font-size: 16px;
                        ">
                            <i class="ph ph-map-pin text-white"></i>
                        </div>
                    `,
                            className: 'custom-marker-icon',
                            iconSize: [32, 32],
                            iconAnchor: [16, 16],
                        });

                        window.customerMap.marker = L.marker([defaultLat, defaultLng], {
                            icon: markerIcon,
                            draggable: false,
                        }).addTo(window.customerMap.map);

                        setTimeout(() => {
                            if (window.customerMap.map) {
                                window.customerMap.map.invalidateSize();
                            }
                        }, 100);
                    } catch (error) {
                        console.error('Error initializing map:', error);
                        mapElement.innerHTML =
                            '<div class="flex items-center justify-center h-full bg-gray-100 text-gray-500"><p>Erreur lors du chargement de la carte.</p></div>';
                    }
                }

                // Initialize on DOMContentLoaded
                document.addEventListener('DOMContentLoaded', function() {
                    console.log('DOMContentLoaded - initializing map');
                    initCustomerMap();
                });

                // Re-initialize on Livewire navigation
                document.addEventListener('livewire:navigate', function() {
                    console.log('Livewire navigate detected, reinitializing map...');
                    setTimeout(() => {
                        console.log('Attempting to reinitialize map after navigation');
                        initCustomerMap();
                    }, 200);
                });

                document.addEventListener('livewire:navigated', function() {
                    console.log('Livewire navigated detected, reinitializing map...');
                    setTimeout(() => {
                        console.log('Attempting to reinitialize map after navigation');
                        initCustomerMap();
                    }, 200);
                });

                // Listen for when Livewire is loaded
                document.addEventListener('livewire:initialized', function() {
                    console.log('Livewire initialized');
                });

                // Listen for Livewire load
                document.addEventListener('livewire:load', function() {
                    console.log('Livewire load - initializing map');
                    setTimeout(() => initCustomerMap(), 100);
                });
            </script>
        @endpush
    @endif

    <style>
        .leaflet-container {
            z-index: 0;
        }

        /* Custom Phosphor marker styling */
        .custom-phosphor-marker {
            background: transparent !important;
            border: none !important;
        }

        .custom-phosphor-marker div {
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
        }

        /* Ensure Phosphor icons are loaded */
        .ph {
            font-family: 'Phosphor', sans-serif;
        }
    </style>

</div>
