/**
 * TaxiBook Partner - Map View
 * ============================
 * Map view with active rides
 */

const MapView = ({ bookings, setToast, onCancelBooking }) => {
    const mapContainerRef = useRef(null);
    const mapInstanceRef = useRef(null);
    const markersLayerRef = useRef(null);
    const [selectedBooking, setSelectedBooking] = useState(null);
    const [mapReady, setMapReady] = useState(false);

    const activeBookings = bookings.filter(b => ['pending', 'confirmed', 'in_progress'].includes(b.status));

    const statusColors = {
        pending: '#f59e0b',
        confirmed: '#3b82f6',
        in_progress: '#10b981'
    };

    const statusLabels = {
        pending: 'En attente',
        confirmed: 'Confirmée',
        in_progress: 'En cours'
    };

    // Load Leaflet CSS and JS
    useEffect(() => {
        // Add Leaflet CSS if not already present
        if (!document.querySelector('link[href*="leaflet"]')) {
            const link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
            document.head.appendChild(link);
        }

        // Load Leaflet JS if not already present
        const loadLeaflet = () => {
            return new Promise((resolve) => {
                if (window.L) {
                    resolve();
                    return;
                }
                
                if (document.querySelector('script[src*="leaflet"]')) {
                    const checkInterval = setInterval(() => {
                        if (window.L) {
                            clearInterval(checkInterval);
                            resolve();
                        }
                    }, 50);
                    return;
                }

                const script = document.createElement('script');
                script.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js';
                script.onload = () => resolve();
                document.head.appendChild(script);
            });
        };

        loadLeaflet().then(() => {
            // Small delay to ensure DOM is ready
            setTimeout(() => setMapReady(true), 100);
        });

        return () => {
            // Cleanup map on unmount
            if (mapInstanceRef.current) {
                mapInstanceRef.current.remove();
                mapInstanceRef.current = null;
            }
        };
    }, []);

    // Initialize map when ready
    useEffect(() => {
        if (!mapReady || !mapContainerRef.current || mapInstanceRef.current) return;

        const L = window.L;
        if (!L) return;

        // Create map
        const map = L.map(mapContainerRef.current, {
            center: [46.2044, 6.1432], // Genève
            zoom: 12,
            zoomControl: true
        });

        // Add OpenStreetMap tiles
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap'
        }).addTo(map);

        // Create markers layer group
        markersLayerRef.current = L.layerGroup().addTo(map);
        mapInstanceRef.current = map;

    }, [mapReady]);

    // Update markers when bookings change
    useEffect(() => {
        if (!mapInstanceRef.current || !markersLayerRef.current || !window.L) return;

        const L = window.L;
        
        // Clear existing markers
        markersLayerRef.current.clearLayers();

        const bounds = [];

        activeBookings.forEach(booking => {
            if (booking.pickup_latitude && booking.pickup_longitude) {
                const lat = parseFloat(booking.pickup_latitude);
                const lng = parseFloat(booking.pickup_longitude);
                bounds.push([lat, lng]);

                // Custom circle marker for pickup
                const pickupMarker = L.circleMarker([lat, lng], {
                    radius: 12,
                    fillColor: statusColors[booking.status],
                    color: '#ffffff',
                    weight: 3,
                    opacity: 1,
                    fillOpacity: 1
                });

                pickupMarker.bindPopup(`
                    <div style="min-width: 200px;">
                        <strong>#${booking.confirmation_code}</strong><br/>
                        <span style="color: ${statusColors[booking.status]}; font-weight: bold;">
                            ${statusLabels[booking.status]}
                        </span><br/>
                        <small>${booking.pickup_address || 'Départ'}</small>
                    </div>
                `);

                pickupMarker.on('click', () => setSelectedBooking(booking));
                markersLayerRef.current.addLayer(pickupMarker);

                // Destination marker if available
                if (booking.destination_latitude && booking.destination_longitude) {
                    const destLat = parseFloat(booking.destination_latitude);
                    const destLng = parseFloat(booking.destination_longitude);
                    bounds.push([destLat, destLng]);

                    // Destination marker
                    const destMarker = L.circleMarker([destLat, destLng], {
                        radius: 8,
                        fillColor: '#ef4444',
                        color: '#ffffff',
                        weight: 2,
                        opacity: 1,
                        fillOpacity: 1
                    });

                    destMarker.bindPopup(`<small>Destination: ${booking.destination_address || 'N/A'}</small>`);
                    markersLayerRef.current.addLayer(destMarker);

                    // Draw route line
                    const routeLine = L.polyline([[lat, lng], [destLat, destLng]], {
                        color: statusColors[booking.status],
                        weight: 3,
                        opacity: 0.7,
                        dashArray: '10, 10'
                    });
                    markersLayerRef.current.addLayer(routeLine);
                }
            }
        });

        // Fit bounds if we have markers
        if (bounds.length > 0) {
            try {
                mapInstanceRef.current.fitBounds(bounds, { padding: [50, 50], maxZoom: 14 });
            } catch (e) {
                console.log('Bounds fitting skipped');
            }
        }
    }, [activeBookings, mapReady]);

    const [viewFilter, setViewFilter] = useState('active'); // active, history

    const statusColorsUI = {
        pending: 'bg-amber-100 text-amber-700 border-amber-300',
        confirmed: 'bg-blue-100 text-blue-700 border-blue-300',
        driver_assigned: 'bg-indigo-100 text-indigo-700 border-indigo-300',
        in_progress: 'bg-emerald-100 text-emerald-700 border-emerald-300',
        completed: 'bg-gray-100 text-gray-600 border-gray-300',
        cancelled: 'bg-red-100 text-red-600 border-red-300'
    };

    const allStatusLabels = {
        ...statusLabels,
        driver_assigned: 'Chauffeur assigné',
        completed: 'Terminée',
        cancelled: 'Annulée'
    };

    const displayedBookings = viewFilter === 'active' 
        ? activeBookings 
        : bookings.filter(b => ['completed', 'cancelled'].includes(b.status));

    return (
        <div className="animate-fade-in h-[calc(100vh-120px)] flex flex-col">
            {/* Header compact */}
            <div className="flex items-center justify-between mb-4 flex-shrink-0">
                <div>
                    <h2 className="text-2xl font-bold text-dark-900">Vue Carte</h2>
                    <p className="text-dark-500">{activeBookings.length} course(s) active(s)</p>
                </div>
                <div className="flex items-center gap-4">
                    {/* Filtres */}
                    <div className="flex bg-dark-100 rounded-lg p-1">
                        <button
                            onClick={() => setViewFilter('active')}
                            className={`px-4 py-2 rounded-md text-sm font-medium transition ${
                                viewFilter === 'active' ? 'bg-white shadow text-dark-900' : 'text-dark-500 hover:text-dark-700'
                            }`}
                        >
                            <i className="fas fa-clock mr-2"></i>Actives
                        </button>
                        <button
                            onClick={() => setViewFilter('history')}
                            className={`px-4 py-2 rounded-md text-sm font-medium transition ${
                                viewFilter === 'history' ? 'bg-white shadow text-dark-900' : 'text-dark-500 hover:text-dark-700'
                            }`}
                        >
                            <i className="fas fa-history mr-2"></i>Historique
                        </button>
                    </div>
                    {/* Légende */}
                    <div className="flex items-center gap-3 text-xs">
                        <div className="flex items-center gap-1">
                            <div className="w-2.5 h-2.5 rounded-full bg-amber-500"></div>
                            <span className="text-dark-500">Attente</span>
                        </div>
                        <div className="flex items-center gap-1">
                            <div className="w-2.5 h-2.5 rounded-full bg-blue-500"></div>
                            <span className="text-dark-500">Confirmée</span>
                        </div>
                        <div className="flex items-center gap-1">
                            <div className="w-2.5 h-2.5 rounded-full bg-emerald-500"></div>
                            <span className="text-dark-500">En cours</span>
                        </div>
                    </div>
                </div>
            </div>

            {/* Layout principal: Courses au centre, Carte à droite */}
            <div className="flex flex-1 gap-0 overflow-hidden rounded-2xl border-2 border-dark-200 bg-white">
                {/* Courses - Centre (70%) */}
                <div className="w-[70%] overflow-y-auto">
                    {displayedBookings.length === 0 ? (
                        <div className="flex items-center justify-center h-full">
                            <div className="text-center p-12">
                                <div className="w-20 h-20 bg-dark-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                    <i className="fas fa-car text-3xl text-dark-300"></i>
                                </div>
                                <h3 className="text-lg font-semibold text-dark-700 mb-2">
                                    {viewFilter === 'active' ? 'Aucune course active' : 'Aucun historique'}
                                </h3>
                                <p className="text-dark-500">
                                    {viewFilter === 'active' 
                                        ? 'Les nouvelles courses apparaîtront ici' 
                                        : 'Vos courses terminées apparaîtront ici'}
                                </p>
                            </div>
                        </div>
                    ) : (
                        <div className="divide-y divide-dark-100">
                            {displayedBookings.map(booking => (
                                <div
                                    key={booking.id || booking.uid}
                                    onClick={() => setSelectedBooking(booking)}
                                    className={`p-5 cursor-pointer transition hover:bg-dark-50 ${
                                        selectedBooking?.id === booking.id ? 'bg-primary-50 border-l-4 border-primary-500' : ''
                                    }`}
                                >
                                    <div className="flex items-start justify-between gap-4">
                                        <div className="flex-1">
                                            <div className="flex items-center gap-2 flex-wrap mb-2">
                                                <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${statusColorsUI[booking.status] || statusColorsUI.pending}`}>
                                                    {allStatusLabels[booking.status] || booking.status}
                                                </span>
                                                <span className="text-sm text-dark-500">#{booking.confirmation_code || booking.uid?.slice(-8)}</span>
                                                {booking.source === 'minisite' && (
                                                    <span className="px-2 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-700">
                                                        <i className="fas fa-globe mr-1"></i>
                                                        {booking.minisite_name || booking.source_minisite_slug || 'Mini-site'}
                                                    </span>
                                                )}
                                            </div>
                                            
                                            <div className="flex items-start gap-3 mt-3">
                                                <div className="flex flex-col items-center">
                                                    <div className="w-3 h-3 rounded-full bg-emerald-500"></div>
                                                    <div className="w-0.5 h-5 bg-dark-200"></div>
                                                    <div className="w-3 h-3 rounded-full bg-primary-500"></div>
                                                </div>
                                                <div className="flex-1 min-w-0">
                                                    <p className="text-sm font-medium text-dark-800 truncate">
                                                        {booking.pickup_address || 'Départ'}
                                                    </p>
                                                    <p className="text-sm text-dark-500 truncate mt-3">
                                                        {booking.destination_address || 'Destination'}
                                                    </p>
                                                </div>
                                            </div>

                                            <div className="mt-3 flex items-center gap-4 text-sm text-dark-500 flex-wrap">
                                                <span>
                                                    <i className="far fa-calendar mr-1"></i>
                                                    {new Date(booking.pickup_datetime).toLocaleDateString('fr-CH', {
                                                        day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit'
                                                    })}
                                                </span>
                                                {booking.guest_name && <span><i className="fas fa-user mr-1"></i> {booking.guest_name}</span>}
                                                {booking.driver_name && <span className="text-emerald-600"><i className="fas fa-id-badge mr-1"></i> {booking.driver_name}</span>}
                                            </div>
                                        </div>
                                        
                                        <div className="text-right">
                                            <p className="text-xl font-bold text-dark-900">{booking.price || 0} CHF</p>
                                            <p className="text-xs text-dark-500 capitalize">{booking.vehicle_type || 'Standard'}</p>
                                            <span className="mt-2 text-xs text-primary-500 block">
                                                Voir détails <i className="fas fa-chevron-right ml-1"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>

                {/* Map - Droite (30%) */}
                <div className="w-[30%] relative border-l border-dark-200">
                    <div 
                        ref={mapContainerRef}
                        className="absolute inset-0"
                        style={{ zIndex: 1 }}
                    />
                    {!mapReady && (
                        <div className="absolute inset-0 flex items-center justify-center bg-dark-100">
                            <div className="text-center">
                                <Spinner size="lg" />
                                <p className="mt-4 text-dark-500 text-sm">Chargement...</p>
                            </div>
                        </div>
                    )}
                </div>
            </div>

            {/* Modal détails */}
            {selectedBooking && (
                <BookingDetailsModal 
                    booking={selectedBooking}
                    onClose={() => setSelectedBooking(null)}
                    onCancel={onCancelBooking}
                />
            )}
        </div>
    );
};
