@extends('admin.layouts.app')

@section('title', 'Add Tracking Update')

@section('content')
<link href="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet-control-geocoder@2.4.0/dist/Control.Geocoder.min.css"/>
<style>
    #map {
        height: 400px;
        width: 100%;
        margin-top: 1rem;
    }
    .map-search-box {
        width: 100%;
        margin-bottom: 1rem;
    }
</style>
<div class="container mx-auto px-4">
    <div class="max-w-3xl mx-auto">
        <div class="mb-6">
            <h1 class="text-2xl font-bold text-gray-900">
                Add Tracking Update for Shipment #{{ $shipment->tracking_number }}
            </h1>
        </div>

        <div class="bg-white rounded-lg shadow-lg overflow-hidden">
            <form action="{{ route('admin.tracking-updates.store', $shipment) }}" method="POST" class="p-6">
                @csrf

                <!-- Map -->
                <div id="map" class="rounded-lg"></div>

                <!-- Hidden Location Fields -->
                <input type="hidden" name="latitude" id="latitude" value="">
                <input type="hidden" name="longitude" id="longitude" value="">

                <!-- Location Name -->
                <div class="mt-4">
                    <label for="location" class="block text-sm font-medium text-gray-700">Location Name</label>
                    <input type="text" name="location" id="location" required
                           class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    @error('location')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Status -->
                <div class="mt-4">
                    <label for="status" class="block text-sm font-medium text-gray-700">Status</label>
                    <select name="status" id="status" required
                            class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                        <option value="pending" {{ $shipment->status == 'pending' ? 'selected' : '' }}>Pending</option>
                        <option value="in_transit" {{ $shipment->status == 'in_transit' ? 'selected' : '' }}>In Transit</option>
                        <option value="delivered" {{ $shipment->status == 'delivered' ? 'selected' : '' }}>Delivered</option>
                    </select>
                    @error('status')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Description -->
                <div class="mt-4">
                    <label for="description" class="block text-sm font-medium text-gray-700">Description</label>
                    <textarea name="description" id="description" rows="3" required
                              class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"></textarea>
                    @error('description')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>

                <div class="mt-6 flex items-center justify-end">
                    <a href="{{ route('admin.shipments.show', $shipment) }}" 
                       class="bg-gray-100 text-gray-700 px-4 py-2 rounded-md mr-2">Cancel</a>
                    <button type="submit" 
                            class="bg-indigo-600 text-white px-4 py-2 rounded-md hover:bg-indigo-700">
                        Add Update
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet-control-geocoder@2.4.0/dist/Control.Geocoder.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    initMap();
});

function initMap() {
    // Check if map container exists
    const mapContainer = document.getElementById('map');
    if (!mapContainer) {
        console.error('Map container not found');
        return;
    }

    // Initialize map
    const map = L.map('map', {
        scrollWheelZoom: true,
        zoomControl: true,
        attributionControl: true
    }).setView([0, 0], 2);
    
    // Add OpenStreetMap tile layer
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        maxZoom: 19,
        errorTileUrl: 'https://cdn.jsdelivr.net/gh/leaflet/Leaflet@1.9.4/dist/images/marker-icon.png'
    }).addTo(map);

    // Add geocoding control - using defensive programming to check if L.Control.Geocoder exists
    let geocoder;
    try {
        geocoder = L.Control.Geocoder && L.Control.Geocoder.nominatim();
        
        // Create the control
        const geocoderControl = L.Control.geocoder({
            geocoder: geocoder,
            defaultMarkGeocode: false,
            position: 'topleft',
            placeholder: 'Search for location...',
            errorMessage: 'Nothing found.'
        }).addTo(map);
        
        // Listen to geocoding events
        geocoderControl.on('markgeocode', function(e) {
            const latlng = e.geocode.center;
            setMarker(latlng, e.geocode.name);
            map.fitBounds(e.geocode.bbox);
        });
    } catch (error) {
        console.error('Error initializing geocoder:', error);
        // Provide fallback - simple alert to inform the user
        const errorMsg = document.createElement('div');
        errorMsg.innerHTML = '<div class="bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 p-4 mb-4" role="alert">' +
                             '<p>Search functionality is unavailable. Please click on the map to set the location.</p></div>';
        mapContainer.parentNode.insertBefore(errorMsg, mapContainer);
    }

    let currentMarker = null;

    // Function to update form fields
    function updateFormFields(lat, lng, address) {
        document.getElementById('latitude').value = lat.toFixed(6);
        document.getElementById('longitude').value = lng.toFixed(6);
        if (address) {
            document.getElementById('location').value = address;
        }
    }

    // Function to handle marker placement
    function setMarker(latlng, address = '') {
        if (currentMarker) {
            map.removeLayer(currentMarker);
        }

        currentMarker = L.marker(latlng, { draggable: true }).addTo(map);
        updateFormFields(latlng.lat, latlng.lng, address);

        // Add popup to marker showing coordinates
        currentMarker.bindPopup(`Lat: ${latlng.lat.toFixed(6)}<br>Lng: ${latlng.lng.toFixed(6)}`).openPopup();

        // Handle marker drag
        currentMarker.on('dragend', function(event) {
            const marker = event.target;
            const position = marker.getLatLng();
            updateFormFields(position.lat, position.lng);

            // Update popup content
            marker.setPopupContent(`Lat: ${position.lat.toFixed(6)}<br>Lng: ${position.lng.toFixed(6)}`);
            
            // Try to reverse geocode if geocoder is available
            if (geocoder) {
                try {
                    geocoder.reverse(position, map.options.crs.scale(map.getZoom()), results => {
                        if (results && results.length > 0) {
                            document.getElementById('location').value = results[0].name;
                        }
                    });
                } catch (error) {
                    console.warn('Reverse geocoding failed:', error);
                }
            }
        });
    }

    // Handle map click
    map.on('click', function(e) {
        setMarker(e.latlng);
        
        // Try reverse geocoding if available
        if (geocoder) {
            try {
                geocoder.reverse(e.latlng, map.options.crs.scale(map.getZoom()), results => {
                    if (results && results.length > 0) {
                        document.getElementById('location').value = results[0].name;
                    }
                });
            } catch (error) {
                console.warn('Reverse geocoding failed:', error);
                // If geocoding fails, at least put in the coordinates as a fallback location name
                document.getElementById('location').value = `Location (${e.latlng.lat.toFixed(4)}, ${e.latlng.lng.toFixed(4)})`;
            }
        } else {
            // Fallback when geocoder is not available
            document.getElementById('location').value = `Location (${e.latlng.lat.toFixed(4)}, ${e.latlng.lng.toFixed(4)})`;
        }
    });

    // Form validation before submit
    document.querySelector('form').addEventListener('submit', function(e) {
        const lat = document.getElementById('latitude').value;
        const lng = document.getElementById('longitude').value;
        const location = document.getElementById('location').value;

        if (!lat || !lng) {
            e.preventDefault();
            alert('Please select a location on the map');
        } else if (!location) {
            // If location is empty but we have coordinates, use a generic name
            document.getElementById('location').value = `Location (${parseFloat(lat).toFixed(4)}, ${parseFloat(lng).toFixed(4)})`;
        }
    });
}
</script>
@endsection