@extends('admin.layouts.app')

@section('title', 'Shipment Details')

<link href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" rel="stylesheet"/>

<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<script>
function initMap() {
    const shipment = @json($shipment);
    const path = @json($shipment->getLocationHistory());

    // Initialize map
    const map = L.map('tracking-map').setView([0, 0], 2);
    
    // Add OpenStreetMap tiles
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    if (!path || path.length === 0) {
        document.getElementById('tracking-map').innerHTML = 
            '<div class="flex items-center justify-center h-full bg-gray-100 text-gray-500">No tracking data available</div>';
        return;
    }

    // Convert and filter valid locations
    const validLocations = path.filter(location => {
        const lat = parseFloat(location.lat);
        const lng = parseFloat(location.lng);
        return !isNaN(lat) && !isNaN(lng) && lat !== 0 && lng !== 0;
    }).map(location => ({
        ...location,
        lat: parseFloat(location.lat),
        lng: parseFloat(location.lng)
    }));

    // Create route line if we have valid points
    if (validLocations.length >= 2) {
        const routeLine = L.polyline(validLocations.map(loc => [loc.lat, loc.lng]), {
            color: '#4F46E5',
            weight: 3,
            opacity: 0.7
        }).addTo(map);
    }

    // Add markers for locations
    let bounds = L.latLngBounds();
    let hasValidMarkers = false;

    path.forEach((location, index) => {
        const lat = parseFloat(location.lat);
        const lng = parseFloat(location.lng);
        
        if (isNaN(lat) || isNaN(lng) || (lat === 0 && lng === 0)) {
            return;
        }

        hasValidMarkers = true;
        const markerPosition = [lat, lng];
        
        // Create custom icon with number
        const icon = L.divIcon({
            className: 'custom-div-icon',
            html: `<div style="background-color: #4F46E5; color: white; width: 24px; height: 24px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 12px;">${index + 1}</div>`,
            iconSize: [24, 24],
            iconAnchor: [12, 12]
        });

        const marker = L.marker(markerPosition, { icon: icon }).addTo(map);
        
        // Add popup
        marker.bindPopup(`
            <div class="p-2">
                <h3 class="font-bold">${location.name}</h3>
                <p>${location.date}</p>
                <p>${location.status}</p>
            </div>
        `);

        bounds.extend(markerPosition);
    });

    // Adjust map view
    if (hasValidMarkers) {
        map.fitBounds(bounds, { padding: [50, 50] });
    } else {
        map.setView([0, 0], 2);
    }
}

window.addEventListener('load', initMap);
</script>

@section('content')
<div class="container mx-auto px-4">
    <div class="max-w-5xl mx-auto">
        @if(session('success'))
            <div class="mb-4 bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded">
                {{ session('success') }}
            </div>
        @endif

        <!-- Top Actions -->
        <div class="mb-6 flex justify-between items-center">
            <h1 class="text-2xl font-bold text-gray-900">
                Shipment #{{ $shipment->tracking_number }}
            </h1>
            <div class="flex space-x-3">
                <a href="{{ route('admin.shipments.edit', $shipment) }}" 
                   class="bg-indigo-600 text-white px-4 py-2 rounded-md hover:bg-indigo-700">
                    Edit Shipment
                </a>
                <a href="{{ route('admin.shipments.invoice', $shipment) }}" 
                   class="bg-gray-600 text-white px-4 py-2 rounded-md hover:bg-gray-700">
                    Download Invoice
                </a>
            </div>
        </div>

        <!-- Status Timeline -->
        <div class="bg-white rounded-lg shadow mb-6 p-6">
            <h2 class="text-lg font-medium text-gray-900 mb-4">Current Status</h2>
            <div class="relative">
                <div class="h-2 bg-gray-200">
                    <div class="h-2 bg-indigo-600" style="width: {{ $shipment->travel_progress }}%"></div>
                </div>
                <div class="flex justify-between mt-4">
                    <div class="text-center">
                        <div class="w-8 h-8 mx-auto rounded-full {{ $shipment->status == 'pending' ? 'bg-indigo-600' : 'bg-gray-200' }} flex items-center justify-center">
                            <span class="text-white text-sm">1</span>
                        </div>
                        <div class="mt-2 text-sm text-gray-600">Order Placed</div>
                    </div>
                    <div class="text-center">
                        <div class="w-8 h-8 mx-auto rounded-full {{ $shipment->status == 'in_transit' ? 'bg-indigo-600' : 'bg-gray-200' }} flex items-center justify-center">
                            <span class="text-white text-sm">2</span>
                        </div>
                        <div class="mt-2 text-sm text-gray-600">In Transit</div>
                    </div>
                    <div class="text-center">
                        <div class="w-8 h-8 mx-auto rounded-full {{ $shipment->status == 'delivered' ? 'bg-indigo-600' : 'bg-gray-200' }} flex items-center justify-center">
                            <span class="text-white text-sm">3</span>
                        </div>
                        <div class="mt-2 text-sm text-gray-600">Delivered</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main Information Grid -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- Sender Information -->
            <div class="bg-white rounded-lg shadow p-6">
                <h2 class="text-lg font-medium text-gray-900 mb-4">Sender Information</h2>
                <dl class="space-y-3">
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Name</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $shipment->sender_name }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Email</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $shipment->sender_email }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Contact</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $shipment->sender_contact }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Address</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $shipment->sender_address }}</dd>
                    </div>
                </dl>
            </div>

            <!-- Receiver Information -->
            <div class="bg-white rounded-lg shadow p-6">
                <h2 class="text-lg font-medium text-gray-900 mb-4">Receiver Information</h2>
                <dl class="space-y-3">
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Name</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $shipment->receiver_name }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Email</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $shipment->receiver_email }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Contact</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $shipment->receiver_contact }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Address</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $shipment->receiver_address }}</dd>
                    </div>
                </dl>
            </div>

            <!-- Shipment Details -->
            <div class="bg-white rounded-lg shadow p-6">
                <h2 class="text-lg font-medium text-gray-900 mb-4">Shipment Details</h2>
                <dl class="space-y-3">
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Description</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $shipment->pdesc }}</dd>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Weight</dt>
                            <dd class="mt-1 text-sm text-gray-900">{{ $shipment->weight }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Quantity</dt>
                            <dd class="mt-1 text-sm text-gray-900">{{ $shipment->quantity }}</dd>
                        </div>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Package Image</dt>
                        <dd class="mt-1">
                            @if($shipment->image)
                                <img src="{{ Storage::url($shipment->image) }}" 
                                     alt="Package Image" 
                                     class="h-32 w-auto rounded">
                            @else
                                <span class="text-sm text-gray-500">No image available</span>
                            @endif
                        </dd>
                    </div>
                </dl>
            </div>

            <!-- Delivery Information -->
            <div class="bg-white rounded-lg shadow p-6">
                <h2 class="text-lg font-medium text-gray-900 mb-4">Delivery Information</h2>
                <dl class="space-y-3">
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Status</dt>
                        <dd class="mt-1">
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full
                                {{ $shipment->status === 'delivered' ? 'bg-green-100 text-green-800' : 
                                   ($shipment->status === 'in_transit' ? 'bg-yellow-100 text-yellow-800' : 
                                   'bg-gray-100 text-gray-800') }}">
                                {{ ucfirst($shipment->status) }}
                            </span>
                        </dd>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Dispatch Date</dt>
                            <dd class="mt-1 text-sm text-gray-900">{{ $shipment->dispatch_date }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Delivery Date</dt>
                            <dd class="mt-1 text-sm text-gray-900">{{ $shipment->delivery_date }}</dd>
                        </div>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Current Location</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $shipment->current_location ?? 'Not available' }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Carrier</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $shipment->carrier }} (Ref: {{ $shipment->carrier_ref }})</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Payment Information</dt>
                        <dd class="mt-1 text-sm text-gray-900">
                            Mode: {{ ucfirst($shipment->payment_mode) }}<br>
                            Total: {{ $shipment->total_f }}
                        </dd>
                    </div>
                </dl>
            </div>
        </div>

        <!-- Map -->
        @if($shipment->show_map)
            <div class="mt-6 bg-white rounded-lg shadow p-6">
                <h2 class="text-lg font-medium text-gray-900 mb-4">Tracking Map</h2>
                <div id="tracking-map" class="h-96 w-full rounded-lg"></div>
            </div>
        @endif
    </div>
</div>
@endsection