"use client"

import React, { useState, useRef, useEffect, useMemo } from "react";
import { View, Text, StyleSheet, TouchableOpacity, Dimensions, ActivityIndicator, Platform } from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { AppleMaps, GoogleMaps } from 'expo-maps';
import { COLORS, SHADOWS } from "../constants/theme";
import { Delivery } from "../types";

interface DeliveryMapProps {
  deliveries: Delivery[];
  onDeliveryPress?: (delivery: Delivery) => void;
  showRoute?: boolean;
  centerOnUser?: boolean;
}

const DeliveryMapComponent: React.FC<DeliveryMapProps> = ({
  deliveries,
  onDeliveryPress,
  showRoute = true,
  centerOnUser = true,
}) => {
  const mapRef = useRef<any>(null);
  const [mapReady, setMapReady] = useState(false);
  const [mapError, setMapError] = useState<string | null>(null);

  // Memoizar entregas válidas
  const validDeliveries = useMemo(() => deliveries.filter(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;
    }
  }), [deliveries]);

  // Preparar marcadores para o mapa
  const mapMarkers = useMemo(() => {
    const distributionCenter = { latitude: -1.3654, longitude: -48.3722 };
    
    const markers = [];
    
    // Adicionar centro de distribuição
    if (Platform.OS === 'ios') {
      markers.push({
        id: 'distribution-center',
        coordinates: distributionCenter,
        title: 'Centro de Distribuição',
        subtitle: 'Ponto de partida das entregas',
        color: '#3B82F6'
      });
    } else {
      markers.push({
        id: 'distribution-center',
        coordinates: distributionCenter,
        title: 'Centro de Distribuição',
        snippet: 'Ponto de partida das entregas',
        color: '#3B82F6'
      });
    }
    
    // Adicionar marcadores das entregas
    validDeliveries.forEach((delivery, index) => {
      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';
      
      if (Platform.OS === 'ios') {
        markers.push({
          id: delivery.id || index.toString(),
          coordinates,
          title: delivery.customerName,
          subtitle: `Pedido #${delivery.outId} • Ordem: ${delivery.deliverySeq || index + 1}`,
          color: statusColor
        });
      } else {
        markers.push({
          id: delivery.id || index.toString(),
          coordinates,
          title: delivery.customerName,
          snippet: `Pedido #${delivery.outId} • Ordem: ${delivery.deliverySeq || index + 1}`,
          color: statusColor
        });
      }
    });
    
    return markers;
  }, [validDeliveries]);

  // Preparar polylines para a rota
  const mapPolylines = useMemo(() => {
    if (!showRoute || validDeliveries.length === 0) return [];
    
    const distributionCenter = { latitude: -1.3654, longitude: -48.3722 };
    const routeCoordinates = [
      distributionCenter,
      ...validDeliveries.map(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((coord): coord is { latitude: number; longitude: number } => coord !== null)
    ];
    
    return [{
      id: 'delivery-route',
      coordinates: routeCoordinates,
      color: '#6B7280',
      width: 4,
      pattern: [5, 5]
    }];
  }, [showRoute, validDeliveries]);

  // Posição inicial da câmera
  const initialCameraPosition = useMemo(() => {
    const distributionCenter = { latitude: -1.3654, longitude: -48.3722 };
    
    if (validDeliveries.length === 0) {
      return {
        coordinates: distributionCenter,
        zoom: 12
      };
    }
    
    // Calcular bounds para incluir todas as entregas
    const allCoordinates = [
      distributionCenter,
      ...validDeliveries.map(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 {
        coordinates: distributionCenter,
        zoom: 12
      };
    }
    
    // Calcular centro médio
    const avgLat = allCoordinates.reduce((sum, coord) => sum + coord!.latitude, 0) / allCoordinates.length;
    const avgLng = allCoordinates.reduce((sum, coord) => sum + coord!.longitude, 0) / allCoordinates.length;
    
    return {
      coordinates: { latitude: avgLat, longitude: avgLng },
      zoom: 11
    };
  }, [validDeliveries]);

  const renderMapControls = () => (
    <View style={styles.mapControls}>
      <TouchableOpacity style={styles.controlButton}>
        <Ionicons name="locate" size={20} color={COLORS.primary} />
      </TouchableOpacity>
      <TouchableOpacity style={styles.controlButton}>
        <Ionicons name="layers" size={20} color={COLORS.primary} />
      </TouchableOpacity>
    </View>
  );

  const renderRouteInfo = () => (
    <View style={styles.routeInfo}>
      <View style={styles.routeStats}>
        <View style={styles.routeStat}>
          <Ionicons name="location" size={16} color={COLORS.primary} />
          <Text style={styles.routeStatText}>12.5 km</Text>
        </View>
        <View style={styles.routeStat}>
          <Ionicons name="time" size={16} color={COLORS.primary} />
          <Text style={styles.routeStatText}>25 min</Text>
        </View>
        <View style={styles.routeStat}>
          <Ionicons name="car" size={16} color={COLORS.primary} />
          <Text style={styles.routeStatText}>{validDeliveries.length} paradas</Text>
        </View>
      </View>
      <TouchableOpacity style={styles.optimizeButton}>
        <Ionicons name="flash" size={16} color="white" />
        <Text style={styles.optimizeButtonText}>Otimizar Rota</Text>
      </TouchableOpacity>
    </View>
  );

  // 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
  const renderMap = () => {
    if (Platform.OS === 'ios') {
      return (
        <AppleMaps.View
          ref={mapRef}
          style={styles.map}
          cameraPosition={initialCameraPosition}
          markers={mapMarkers}
          polylines={mapPolylines}
          onMapClick={() => {}}
          onMarkerClick={(marker) => {
            const delivery = deliveries.find(d => d.id?.toString() === marker.id);
            if (delivery && onDeliveryPress) {
              onDeliveryPress(delivery);
            }
          }}
          properties={{}}
        />
      );
    } else {
      return (
        <GoogleMaps.View
          ref={mapRef}
          style={styles.map}
          cameraPosition={initialCameraPosition}
          markers={mapMarkers}
          polylines={mapPolylines}
          onMapLoaded={() => setMapReady(true)}
          onMapClick={() => {}}
          onMarkerClick={(marker) => {
            const delivery = deliveries.find(d => d.id?.toString() === marker.id);
            if (delivery && onDeliveryPress) {
              onDeliveryPress(delivery);
            }
          }}
          properties={{}}
        />
      );
    }
  };

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

      {/* Indicador de carregamento */}
      {!mapReady && (
        <View style={styles.loadingOverlay}>
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color={COLORS.primary} />
            <Text style={styles.loadingText}>Carregando mapa...</Text>
          </View>
        </View>
      )}

      {mapReady && renderMapControls()}
      {mapReady && showRoute && renderRouteInfo()}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    position: 'relative',
  },
  map: {
    flex: 1,
  },
  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',
  },
  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,
  },
  fallbackContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: COLORS.background,
    padding: 20,
  },
  fallbackText: {
    fontSize: 18,
    color: COLORS.text,
    marginTop: 16,
    textAlign: 'center',
    fontWeight: '600',
  },
  retryButton: {
    marginTop: 20,
    backgroundColor: COLORS.primary,
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderRadius: 8,
  },
  retryButtonText: {
    color: 'white',
    fontSize: 14,
    fontWeight: '600',
  },
  mapControls: {
    position: 'absolute',
    top: 20,
    right: 16,
    gap: 8,
  },
  controlButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: 'white',
    alignItems: 'center',
    justifyContent: 'center',
    ...SHADOWS.medium,
  },
  routeInfo: {
    position: 'absolute',
    bottom: 20,
    left: 16,
    right: 16,
    backgroundColor: 'white',
    borderRadius: 16,
    padding: 16,
    ...SHADOWS.medium,
  },
  routeStats: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 12,
  },
  routeStat: {
    alignItems: 'center',
  },
  routeStatText: {
    fontSize: 12,
    color: COLORS.text,
    marginTop: 4,
  },
  optimizeButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: COLORS.primary,
    borderRadius: 12,
    paddingVertical: 12,
    gap: 8,
  },
  optimizeButtonText: {
    color: 'white',
    fontSize: 14,
    fontWeight: '600',
  },
});

export default DeliveryMapComponent;
