import React, { useState, useEffect, useRef, forwardRef, useMemo, useCallback, useTransition } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ActivityIndicator,
  Platform,
  Dimensions,
  InteractionManager
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { COLORS, SHADOWS } from '../constants/theme';
import { Delivery } from '../types';
import { useMapboxDirections } from '../hooks/useMapboxDirections';
import { getCoordinatesFromAddress } from '../services/api';
import CustomPin from './CustomPin';

const { width, height } = Dimensions.get('window');

// Hook de debounce para otimizar operações
const useDebounce = (value: any, delay: number) => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  
  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);
    
    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);
  
  return debouncedValue;
};

interface DeliveryMapProps {
  deliveries: Delivery[];
  onDeliveryPress?: (delivery: Delivery) => void;
  showRoute?: boolean;
  centerOnUser?: boolean;
  showDeliveryPin?: boolean;
  onRouteCalculated?: (deliveries: Delivery[]) => void;
  customRouteCoordinates?: Array<{ latitude: number; longitude: number }>;
  driverLocation?: { latitude: number; longitude: number } | null;
}

const DeliveryMap = forwardRef((props: DeliveryMapProps, ref) => {
  const mapRef = useRef<any>(null);
  const [mapReady, setMapReady] = useState(false);
  const [mapError, setMapError] = useState<string | null>(null);
  const [selectedDelivery, setSelectedDelivery] = useState<Delivery | null>(null);
  const [optimizedDeliveries, setOptimizedDeliveries] = useState<Delivery[]>([]);
  const [routeCalculated, setRouteCalculated] = useState(false);
  const [realRouteCoordinates, setRealRouteCoordinates] = useState<Array<{latitude: number, longitude: number}>>([]);
  const [routeStats, setRouteStats] = useState({ distance: 0, duration: 0 });
  const [isLoadingRoute, setIsLoadingRoute] = useState(false);

  // Função para ajustar o mapa para mostrar toda a rota
  const fitMapToRoute = useCallback(() => {
    if (mapRef.current && realRouteCoordinates.length > 0) {
      const allCoordinates = [
        { latitude: -1.3654, longitude: -48.3722 }, // Centro de distribuição
        ...realRouteCoordinates
      ];
      
      const latValues = allCoordinates.map(coord => coord.latitude);
      const lngValues = allCoordinates.map(coord => coord.longitude);
      
      const minLat = Math.min(...latValues);
      const maxLat = Math.max(...latValues);
      const minLng = Math.min(...lngValues);
      const maxLng = Math.max(...lngValues);
      
      const region = {
        latitude: (minLat + maxLat) / 2,
        longitude: (minLng + maxLng) / 2,
        latitudeDelta: (maxLat - minLat) * 1.2,
        longitudeDelta: (maxLng - minLng) * 1.2
      };
      
      mapRef.current.animateToRegion(region, 1000);
    }
  }, [realRouteCoordinates]);

  const { getOptimizedRouteWithUpdatedDeliveries, loading: mapboxLoading, error: mapboxError } = useMapboxDirections();
  const [isPending, startTransition] = useTransition();

  // Debounce das entregas para evitar recálculos excessivos
  const debouncedDeliveries = useDebounce(props.deliveries, 300);
  
  // Memoizar entregas válidas para evitar recalculo a cada render
  const validDeliveries = useMemo(() => debouncedDeliveries.filter((delivery: Delivery) => {
    try {
      if (delivery.coordinates) {
        return typeof delivery.coordinates.latitude === 'number' && 
               typeof delivery.coordinates.longitude === 'number' &&
               !isNaN(delivery.coordinates.latitude) && 
               !isNaN(delivery.coordinates.longitude);
      }
      if (delivery.lat && delivery.lng) {
        let lat = delivery.lat;
        let lng = delivery.lng;
        if (typeof lat === 'string') lat = parseFloat((lat as string).replace(',', '.'));
        if (typeof lng === 'string') lng = parseFloat((lng as string).replace(',', '.'));
        return typeof lat === 'number' && !isNaN(lat) && 
               typeof lng === 'number' && !isNaN(lng);
      }
      return false;
    } catch (error) {
      console.error('Erro ao validar entrega:', error);
      return false;
    }
  }), [props.deliveries]);

  // Algoritmo do Caixeiro Viajante (TSP) - Nearest Neighbor
  const calculateTSPRoute = (deliveries: any[], startPoint: any) => {
    if (deliveries.length === 0) return [startPoint];

    const unvisited = [...deliveries];
    const route = [startPoint];
    let currentPoint = startPoint;

    while (unvisited.length > 0) {
      // Encontrar o ponto mais próximo
      let nearestIndex = 0;
      let minDistance = Infinity;

      unvisited.forEach((delivery, index) => {
        const deliveryPoint = {
          lat: delivery.coordinates?.latitude || delivery.lat,
          lng: delivery.coordinates?.longitude || delivery.lng
        };

        const distance = calculateDistance(currentPoint, deliveryPoint);
        if (distance < minDistance) {
          minDistance = distance;
          nearestIndex = index;
        }
      });

      // Adicionar o ponto mais próximo à rota
      const nearestDelivery = unvisited[nearestIndex];
      const nearestPoint = {
        lat: nearestDelivery.coordinates?.latitude || nearestDelivery.lat,
        lng: nearestDelivery.coordinates?.longitude || nearestDelivery.lng
      };

      route.push(nearestPoint);
      currentPoint = nearestPoint;
      unvisited.splice(nearestIndex, 1);
    }

    return route;
  };

  // Calcular distância entre dois pontos (fórmula de Haversine)
  const calculateDistance = (point1: any, point2: any) => {
    const R = 6371; // Raio da Terra em km
    const dLat = (point2.lat - point1.lat) * Math.PI / 180;
    const dLng = (point2.lng - point1.lng) * Math.PI / 180;
    const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
              Math.cos(point1.lat * Math.PI / 180) * Math.cos(point2.lat * Math.PI / 180) *
              Math.sin(dLng/2) * Math.sin(dLng/2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    return R * c;
  };

  // Obter coordenadas de endereços que não têm coordenadas
  const getMissingCoordinates = async (deliveries: Delivery[]) => {
    const deliveriesWithCoords = await Promise.all(
      deliveries.map(async (delivery) => {
        // Se já tem coordenadas, retorna como está
        if (delivery.coordinates || (delivery.lat && delivery.lng)) {
          return delivery;
        }

        // Se não tem coordenadas, tenta obter do endereço
        console.log(`=== DEBUG: OBTENDO COORDENADAS PARA ${delivery.customerName} ===`);
        const coords = await getCoordinatesFromAddress({
          address: delivery.street || '',
          addressNumber: delivery.streetNumber || '',
          neighborhood: delivery.neighborhood || '',
          city: delivery.city || '',
          state: delivery.state || ''
        });

        if (coords) {
          console.log(`Coordenadas obtidas para ${delivery.customerName}:`, coords);
          return {
            ...delivery,
            coordinates: coords,
            lat: coords.latitude,
            lng: coords.longitude
          };
        }

        console.warn(`Não foi possível obter coordenadas para ${delivery.customerName}`);
        return delivery;
      })
    );

    return deliveriesWithCoords.filter(delivery => 
      delivery.coordinates || (delivery.lat && delivery.lng)
    );
  };

  // Calcular rota otimizada com Mapbox (otimizado com lazy loading)
  useEffect(() => {
    let isMounted = true;
    
    const calculateRealRoute = async () => {
      if (props.showRoute && validDeliveries.length > 0) {
        setIsLoadingRoute(true);
        
        // Usar InteractionManager para não bloquear a UI
        InteractionManager.runAfterInteractions(async () => {
          try {
            console.log('=== DEBUG: CALCULANDO ROTA REAL COM MAPBOX ===');
            
            // Obter coordenadas para entregas que não têm
            const deliveriesWithCoords = await getMissingCoordinates(validDeliveries);
            console.log('Entregas com coordenadas:', deliveriesWithCoords.length);

          if (deliveriesWithCoords.length === 0) {
            console.warn('Nenhuma entrega com coordenadas válidas');
            if (!isMounted) return;
            setOptimizedDeliveries(validDeliveries);
            setRouteCalculated(false);
            setIsLoadingRoute(false);
            return;
          }

          const distributionCenter = { latitude: -1.3654, longitude: -48.3722 };
          
          // Calcular rota TSP primeiro para ordenar as entregas
          const tspRoute = calculateTSPRoute(deliveriesWithCoords, { lat: distributionCenter.latitude, lng: distributionCenter.longitude });
          
          // Atualizar entregas com a ordem otimizada
          const optimized = tspRoute.slice(1).map((point, index) => {
            const originalDelivery = deliveriesWithCoords.find(delivery => {
              const deliveryLat = delivery.coordinates?.latitude || delivery.lat;
              const deliveryLng = delivery.coordinates?.longitude || delivery.lng;
              return deliveryLat && deliveryLng && Math.abs(deliveryLat - point.lat) < 0.001 && Math.abs(deliveryLng - point.lng) < 0.001;
            });
            
            return originalDelivery ? {
              ...originalDelivery,
              deliverySeq: index + 1
            } : null;
          }).filter((delivery): delivery is Delivery => delivery !== null);

          if (!isMounted) return;
          setOptimizedDeliveries(optimized);
          setRouteCalculated(true);

          // Obter rota real do Mapbox com timeout
          console.log('=== DEBUG: OBTENDO ROTA DO MAPBOX ===');
          const mapboxPromise = getOptimizedRouteWithUpdatedDeliveries(optimized, distributionCenter);
          const timeoutPromise = new Promise((_, reject) => 
            setTimeout(() => reject(new Error('Mapbox timeout')), 10000)
          );
          
          const mapboxResult = await Promise.race([mapboxPromise, timeoutPromise]) as any;
          
          if (mapboxResult && mapboxResult.route) {
            console.log('Rota do Mapbox obtida:', {
              distance: mapboxResult.route.distance,
              duration: mapboxResult.route.duration,
              coordinates: mapboxResult.route.coordinates.length
            });

            // Converter coordenadas para formato react-native-maps
            const expoCoordinates = mapboxResult.route.coordinates.map((coord: any) => ({
              latitude: coord.latitude,
              longitude: coord.longitude
            }));

            if (!isMounted) return;
            setRealRouteCoordinates(expoCoordinates);
            setRouteStats({
              distance: mapboxResult.route.distance,
              duration: mapboxResult.route.duration
            });

            if (props.onRouteCalculated) {
              props.onRouteCalculated(mapboxResult.updatedDeliveries);
            }

            // Ajustar mapa para mostrar toda a rota após um pequeno delay
            setTimeout(() => {
              if (isMounted) {
                fitMapToRoute();
              }
            }, 500);
          } else {
            console.warn('Não foi possível obter rota do Mapbox, usando rota simples');
            // Fallback para rota simples
            const simpleRoute = [
              { latitude: distributionCenter.latitude, longitude: distributionCenter.longitude },
              ...optimized.map(d => ({
                latitude: d.coordinates?.latitude || d.lat || 0,
                longitude: d.coordinates?.longitude || d.lng || 0
              })).filter(coord => coord.latitude !== 0 && coord.longitude !== 0)
            ];
            if (!isMounted) return;
            setRealRouteCoordinates(simpleRoute);
          }

        } catch (error) {
          if (!isMounted) return;
          console.error('Erro ao calcular rota real:', error);
          // Em caso de erro, usar entregas simples sem otimização
          setOptimizedDeliveries(validDeliveries);
          setRouteCalculated(false);
          setRealRouteCoordinates([]);
        } finally {
          if (!isMounted) return;
          setIsLoadingRoute(false);
        }
      });
    } else {
      if (!isMounted) return;
      setOptimizedDeliveries(validDeliveries);
      setRouteCalculated(false);
      setRealRouteCoordinates([]);
    }
  };
  
  calculateRealRoute();
  return () => { isMounted = false; };
}, [props.showRoute, validDeliveries]);

  // Preparar marcadores para o mapa (otimizado com memoização)
  const mapMarkers = useMemo(() => {
    const distributionCenter = { latitude: -1.3654, longitude: -48.3722 };
    const deliveriesToShow = routeCalculated ? optimizedDeliveries : validDeliveries;
    
    const markers = [];
    
    // Adicionar centro de distribuição com pin especial
    markers.push({
      id: 'distribution-center',
      coordinate: distributionCenter,
      title: '🏢 Centro de Distribuição',
      description: 'Ponto de partida das entregas',
      pinColor: '#1E40AF',
      pinText: '🏢',
      isSpecial: true
    });
    
    // Adicionar marcadores das entregas
    deliveriesToShow.forEach((delivery: Delivery, index: number) => {
      let coordinates = null;
      
      if (delivery.coordinates) {
        coordinates = { latitude: delivery.coordinates.latitude, longitude: delivery.coordinates.longitude };
      } else if (delivery.lat && delivery.lng) {
        let lat = delivery.lat;
        let lng = delivery.lng;
        
        if (typeof lat === 'string') {
          lat = parseFloat((lat as string).replace(',', '.'));
        }
        if (typeof lng === 'string') {
          lng = parseFloat((lng as string).replace(',', '.'));
        }
        
        if (typeof lat === 'number' && !isNaN(lat) && typeof lng === 'number' && !isNaN(lng)) {
          coordinates = { latitude: lat, longitude: lng };
        }
      }
      
      if (!coordinates) return;
      
      const statusColor = delivery.status === 'delivered' ? '#10B981' :
                         delivery.status === 'in_progress' ? '#3B82F6' :
                         delivery.status === 'failed' ? '#EF4444' : '#F59E0B';
      
      const orderNumber = delivery.deliverySeq || index + 1;
      
      markers.push({
        id: delivery.id || index.toString(),
        coordinate: coordinates,
        title: `${orderNumber}. ${delivery.customerName}`,
        description: `Pedido #${delivery.outId} • ${delivery.street}, ${delivery.streetNumber}`,
        pinColor: '#F59E0B', // Amarelo para todos os pins
        pinText: orderNumber.toString()
      });
    });
    
    return markers;
  }, [validDeliveries, optimizedDeliveries, routeCalculated]);

  // Preparar polylines para a rota (otimizado com memoização)
  const mapPolylines = useMemo(() => {
    if (!props.showRoute || realRouteCoordinates.length === 0) return [];
    
    return [{
      id: 'delivery-route',
      coordinates: realRouteCoordinates,
      strokeColor: routeCalculated ? '#3B82F6' : '#6B7280',
      strokeWidth: 4,
      lineDashPattern: routeCalculated ? undefined : [5, 5]
    }];
  }, [props.showRoute, realRouteCoordinates, routeCalculated]);

  // Posição inicial da câmera com zoom otimizado para mostrar toda a rota (otimizado com memoização)
  const initialRegion = useMemo(() => {
    const distributionCenter = { latitude: -1.3654, longitude: -48.3722 };
    
    if (validDeliveries.length === 0) {
      return {
        latitude: distributionCenter.latitude,
        longitude: distributionCenter.longitude,
        latitudeDelta: 0.01,
        longitudeDelta: 0.01
      };
    }
    
    // Calcular bounds para incluir todas as entregas
    const allCoordinates = [
      distributionCenter,
      ...validDeliveries.map((delivery: Delivery) => {
        if (delivery.coordinates) {
          return { latitude: delivery.coordinates.latitude, longitude: delivery.coordinates.longitude };
        }
        if (delivery.lat && delivery.lng) {
          let lat = delivery.lat;
          let lng = delivery.lng;
          if (typeof lat === 'string') lat = parseFloat((lat as string).replace(',', '.'));
          if (typeof lng === 'string') lng = parseFloat((lng as string).replace(',', '.'));
          return { latitude: lat, longitude: lng };
        }
        return null;
      }).filter(Boolean)
    ];
    
    if (allCoordinates.length === 0) {
      return {
        latitude: distributionCenter.latitude,
        longitude: distributionCenter.longitude,
        latitudeDelta: 0.01,
        longitudeDelta: 0.01
      };
    }
    
    // Calcular centro médio (ponderado pelo centro de distribuição)
    const totalCoords = allCoordinates.length;
    const avgLat = allCoordinates.reduce((sum, coord) => sum + (coord?.latitude || 0), 0) / totalCoords;
    const avgLng = allCoordinates.reduce((sum, coord) => sum + (coord?.longitude || 0), 0) / totalCoords;
    
    // Calcular deltas para incluir todas as coordenadas com margem adequada
    const latValues = allCoordinates.map(coord => coord?.latitude || 0);
    const lngValues = allCoordinates.map(coord => coord?.longitude || 0);
    
    const minLat = Math.min(...latValues);
    const maxLat = Math.max(...latValues);
    const minLng = Math.min(...lngValues);
    const maxLng = Math.max(...lngValues);
    
    // Adicionar margem de 20% para melhor visualização
    const latDelta = (maxLat - minLat) * 1.2;
    const lngDelta = (maxLng - minLng) * 1.2;
    
    // Garantir zoom mínimo e máximo adequados
    const finalLatDelta = Math.max(Math.min(latDelta, 0.05), 0.008);
    const finalLngDelta = Math.max(Math.min(lngDelta, 0.05), 0.008);
    
    return {
      latitude: avgLat,
      longitude: avgLng,
      latitudeDelta: finalLatDelta,
      longitudeDelta: finalLngDelta
    };
  }, [validDeliveries]);

  // Se não há entregas válidas, mostrar mensagem
  if (validDeliveries.length === 0) {
    return (
      <View style={styles.emptyContainer}>
        <Ionicons name="map-outline" size={64} color={COLORS.textLight} />
        <Text style={styles.emptyText}>Nenhuma entrega disponível</Text>
        <Text style={styles.emptySubtext}>
          Não há entregas com coordenadas válidas para exibir no mapa
        </Text>
      </View>
    );
  }

  // Se houver erro no mapa, mostrar fallback
  if (mapError) {
    return (
      <View style={styles.fallbackContainer}>
        <Ionicons name="alert-circle" size={64} color={COLORS.danger} />
        <Text style={styles.fallbackText}>Erro ao carregar mapa</Text>
        <TouchableOpacity style={styles.retryButton} onPress={() => {
          setMapError(null);
          setMapReady(false);
        }}>
          <Text style={styles.retryButtonText}>Tentar Novamente</Text>
        </TouchableOpacity>
      </View>
    );
  }

  // Renderizar mapa baseado na plataforma (otimizado com lazy loading)
  const renderMap = useCallback(() => {
    // Importar react-native-maps dinamicamente
    let MapView: any = null;
    let Marker: any = null;
    let Polyline: any = null;
    let PROVIDER_GOOGLE: any = null;

    try {
      const Maps = require('react-native-maps');
      MapView = Maps.default;
      Marker = Maps.Marker;
      Polyline = Maps.Polyline;
      PROVIDER_GOOGLE = Maps.PROVIDER_GOOGLE;
    } catch (error) {
      console.error('react-native-maps não disponível:', error);
      return (
        <View style={styles.mapFallback}>
          <Ionicons name="map" size={48} color={COLORS.textLight} />
          <Text style={styles.mapFallbackText}>Mapa não disponível</Text>
          <Text style={styles.mapFallbackSubtext}>
            Instale react-native-maps para visualizar o mapa
          </Text>
        </View>
      );
    }

    return (
      <MapView
        ref={mapRef}
        style={styles.map}
        provider={Platform.OS === 'android' ? PROVIDER_GOOGLE : undefined}
        initialRegion={initialRegion}
        onMapReady={() => setMapReady(true)}
        showsUserLocation={props.centerOnUser}
        showsMyLocationButton={props.centerOnUser}
        showsCompass={true}
        showsScale={true}
        showsTraffic={false}
        showsBuildings={true}
        showsIndoors={true}
        onPress={() => setSelectedDelivery(null)}
      >
        {/* Marcadores */}
        {mapMarkers.map((marker) => (
          <Marker
            key={marker.id}
            coordinate={marker.coordinate}
            title={marker.title}
            description={marker.description}
            onPress={() => {
              if (marker.id !== 'distribution-center') {
                const delivery = props.deliveries.find(d => d.id?.toString() === marker.id);
                if (delivery && props.onDeliveryPress) {
                  props.onDeliveryPress(delivery);
                }
              }
            }}
          >
            <CustomPin
              number={marker.isSpecial ? marker.pinText : parseInt(marker.pinText) || 1}
              size={marker.isSpecial ? 36 : 32}
              color={marker.pinColor}
              isSpecial={marker.isSpecial}
            />
          </Marker>
        ))}

        {/* Rotas */}
        {mapPolylines.map((polyline) => (
          <Polyline
            key={polyline.id}
            coordinates={polyline.coordinates}
            strokeColor={polyline.strokeColor}
            strokeWidth={polyline.strokeWidth}
            lineDashPattern={polyline.lineDashPattern}
            geodesic={true}
          />
        ))}
      </MapView>
    );
  }, [mapMarkers, mapPolylines, initialRegion, mapRef, props.centerOnUser, props.deliveries, props.onDeliveryPress]);

  return (
    <View style={styles.container}>
      {renderMap()}

      {/* Indicador de carregamento (otimizado) */}
      {(!mapReady || isLoadingRoute || isPending) && (
        <View style={styles.loadingOverlay}>
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color={COLORS.primary} />
            <Text style={styles.loadingText}>
              {isLoadingRoute ? 'Calculando rota otimizada...' : 'Carregando mapa...'}
            </Text>
            {isLoadingRoute && (
              <Text style={styles.loadingSubtext}>
                Obtendo coordenadas e calculando rota real
              </Text>
            )}
          </View>
        </View>
      )}

      
      {/* Botão para centralizar mapa na rota */}
      {props.showRoute && realRouteCoordinates.length > 0 && (
        <TouchableOpacity 
          style={styles.centerRouteButton}
          onPress={fitMapToRoute}
        >
          <Ionicons name="locate" size={20} color="white" />
        </TouchableOpacity>
      )}

      {/* Informações da entrega selecionada */}
      {selectedDelivery && (
        <View style={styles.deliveryInfo}>
          <View style={styles.deliveryHeader}>
            <Text style={styles.deliveryTitle}>
              {selectedDelivery.customerName}
            </Text>
            <TouchableOpacity onPress={() => setSelectedDelivery(null)}>
              <Ionicons name="close" size={24} color={COLORS.text} />
            </TouchableOpacity>
          </View>
          
          <Text style={styles.deliveryAddress}>
            {selectedDelivery.street && selectedDelivery.streetNumber 
              ? `${selectedDelivery.street}, ${selectedDelivery.streetNumber}`
              : `${selectedDelivery.street}, ${selectedDelivery.streetNumber}, ${selectedDelivery.neighborhood}, ${selectedDelivery.city}`
            }
          </Text>
          
          <View style={styles.deliveryMeta}>
            <View style={[styles.statusBadge, { backgroundColor: getStatusColor(selectedDelivery.status) }]}>
              <Text style={styles.statusText}>
                {selectedDelivery.status === 'delivered' ? 'Entregue' :
                 selectedDelivery.status === 'in_progress' ? 'Em andamento' : 
                 selectedDelivery.status === 'failed' ? 'Falhou' : 'Pendente'}
              </Text>
            </View>
          </View>
        </View>
      )}
    </View>
  );
});

const getStatusColor = (status: string) => {
  switch (status) {
    case 'delivered':
      return COLORS.success;
    case 'in_progress':
      return COLORS.info;
    case 'failed':
      return COLORS.danger;
    default:
      return COLORS.warning;
  }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    position: 'relative',
  },
  map: {
    flex: 1,
  },
  mapFallback: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: COLORS.background,
    padding: 20,
  },
  mapFallbackText: {
    fontSize: 18,
    color: COLORS.text,
    marginTop: 16,
    textAlign: 'center',
    fontWeight: '600',
  },
  mapFallbackSubtext: {
    fontSize: 14,
    color: COLORS.textLight,
    marginTop: 8,
    textAlign: 'center',
  },
  emptyContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: COLORS.background,
    padding: 20,
  },
  emptyText: {
    fontSize: 18,
    color: COLORS.text,
    marginTop: 16,
    textAlign: 'center',
    fontWeight: '600',
  },
  emptySubtext: {
    fontSize: 14,
    color: COLORS.textLight,
    marginTop: 8,
    textAlign: 'center',
  },
  deliveryInfo: {
    position: 'absolute',
    bottom: 20,
    left: 16,
    right: 16,
    backgroundColor: 'white',
    borderRadius: 12,
    padding: 16,
    ...SHADOWS.medium,
  },
  deliveryHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  deliveryTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: COLORS.text,
    flex: 1,
  },
  deliveryAddress: {
    fontSize: 14,
    color: COLORS.textLight,
    marginBottom: 8,
  },
  deliveryMeta: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  statusBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 8,
  },
  statusText: {
    fontSize: 12,
    fontWeight: '500',
    color: 'white',
  },
  loadingOverlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(255, 255, 255, 0.8)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  loadingContainer: {
    backgroundColor: 'white',
    borderRadius: 12,
    padding: 20,
    alignItems: 'center',
    ...SHADOWS.medium,
  },
  loadingText: {
    marginTop: 8,
    fontSize: 14,
    color: COLORS.text,
  },
  loadingSubtext: {
    marginTop: 4,
    fontSize: 12,
    color: COLORS.textLight,
    textAlign: 'center',
  },
  fallbackContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: COLORS.background,
    padding: 20,
  },
  fallbackText: {
    fontSize: 18,
    color: COLORS.text,
    marginTop: 16,
    textAlign: 'center',
    fontWeight: '600',
  },
  fallbackSubtext: {
    fontSize: 14,
    color: COLORS.textLight,
    marginTop: 8,
    textAlign: 'center',
  },
  retryButton: {
    marginTop: 20,
    backgroundColor: COLORS.primary,
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderRadius: 8,
  },
  retryButtonText: {
    color: 'white',
    fontSize: 14,
    fontWeight: '600',
  },
  routeInfoFloating: {
    position: 'absolute',
    top: 20,
    left: 16,
    right: 16,
    backgroundColor: 'white',
    borderRadius: 12,
    padding: 16,
    ...SHADOWS.medium,
  },
  routeStats: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  routeStat: {
    alignItems: 'center',
  },
  routeStatText: {
    fontSize: 12,
    color: COLORS.text,
    marginTop: 4,
  },
  centerRouteButton: {
    position: 'absolute',
    bottom: 120,
    right: 20,
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: COLORS.primary,
    alignItems: 'center',
    justifyContent: 'center',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
});

DeliveryMap.displayName = 'DeliveryMap';

export default DeliveryMap; 