"use client"

import { useState, useEffect } from "react"
import { View, Text, StyleSheet, TouchableOpacity, Dimensions, Animated, FlatList, Platform, Alert } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { Ionicons } from "@expo/vector-icons"
import { useNavigation } from "@react-navigation/native"
import { LinearGradient } from "expo-linear-gradient"
import { COLORS, SHADOWS } from "../../constants/theme"
import { useAuth } from "../../contexts/AuthContext"
import { useDeliveries } from "../../contexts/DeliveriesContext"
import { api } from "../../services/api"
import type { Delivery } from "../../types"
import { mockDeliveries } from "../../config/mockData"
import DeliveryMap from "../../components/DeliveryMap"

import { StatusBar } from "expo-status-bar"
import React, { useRef } from "react";

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

const RoutesScreen = () => {
  const navigation = useNavigation()
  const { user } = useAuth()
  const { deliveries, loading, error, refreshDeliveries } = useDeliveries()
  const [showRoute, setShowRoute] = useState(true)
  const [isFullscreen, setIsFullscreen] = useState(false)
  const [viewMode, setViewMode] = useState<"map" | "list">("map")
  const [statsAnimation] = useState(new Animated.Value(1))
  const deliveryMapRef = useRef(null);

  // Ordenação simplificada: SEMPRE respeitar deliverySeq primeiro
  const getOrderedDeliveries = (deliveries: Delivery[]) => {
    console.log('=== 🎯 ORDENANDO ENTREGAS NA ROUTESSCREEN ===')
    console.log('📊 Total de entregas para ordenar:', deliveries.length)
    
    const ordered = [...deliveries].sort((a, b) => {
      // PRIMEIRO: Sempre ordenar por deliverySeq (sequência de entrega)
      if (a.deliverySeq !== b.deliverySeq) {
        return a.deliverySeq - b.deliverySeq
      }
      
      // SEGUNDO: Se deliverySeq for igual, ordenar por status
      const getStatusOrder = (status: Delivery["status"]): number => {
        switch (status) {
          case "in_progress":
            return 0
          case "pending":
            return 1
          case "delivered":
            return 2
          case "failed":
            return 3
          default:
            return 4
        }
      }
      
      const statusDiff = getStatusOrder(a.status) - getStatusOrder(b.status)
      if (statusDiff !== 0) return statusDiff
      
      // TERCEIRO: Se status for igual, ordenar por distância
      if (a.distance !== b.distance) {
        return (a.distance || 0) - (b.distance || 0)
      }
      
      // QUARTO: Por último, ordenar por data
      return new Date(a.outDate).getTime() - new Date(b.outDate).getTime()
    })
    
    console.log('📊 Entregas ordenadas:')
    ordered.slice(0, 5).forEach((delivery, index) => {
      console.log(`  ${index + 1}. ${delivery.customerName} - Seq:${delivery.deliverySeq}, Status:${delivery.status}`)
    })
    
    return ordered
  }



  const handleDeliveryPress = (delivery: Delivery) => {
    console.log('=== DEBUG: NAVEGANDO PARA DETALHES DA ENTREGA ===');
    console.log('Delivery:', {
      id: delivery.id,
      outId: delivery.outId,
      customerName: delivery.customerName,
      status: delivery.status
    });
    
    // @ts-ignore
    navigation.navigate("DeliveriesStack", {
      screen: "DeliveryDetail",
      params: { 
        deliveryId: delivery.outId || delivery.id,
        deliveryData: delivery // Passar os dados completos da entrega
      },
    })
  }

  // Callback para quando a rota for calculada pelo DeliveryMap
  const handleRouteCalculated = async (optimizedDeliveries: Delivery[]) => {
    try {
      console.log('=== DEBUG: ROTA CALCULADA - ENVIANDO PARA API ===');
      console.log('Entregas otimizadas recebidas:', optimizedDeliveries.length);
      
      // Enviar roteamento para a API
      const result = await api.sendRoutingAfterMapRoute(optimizedDeliveries);
      console.log('=== DEBUG: ROTEAMENTO ENVIADO COM SUCESSO ===');
      console.log('Resultado:', result);
      
      // Recarregar a HomeScreen para mostrar a próxima entrega de acordo com as novas ordens
      console.log('=== DEBUG: RECARREGANDO HOMESCREEN APÓS ROTEAMENTO ===');
      
      // Navegar de volta para a HomeScreen com flag de recarregamento
      // @ts-ignore
      navigation.navigate('Home', { 
        refreshDeliveries: true,
        routingUpdated: true 
      });
      
      // Mostrar feedback para o usuário
      /*Alert.alert(
        "Roteamento Atualizado",
        "A ordem das entregas foi atualizada com sucesso! A próxima entrega foi recalculada.",
        [{ text: "OK" }]
      );*/
      
    } catch (error) {
      console.error('=== DEBUG: ERRO AO ENVIAR ROTEAMENTO ===');
      console.error('Erro:', error);
      
      // Mostrar erro para o usuário
      /*Alert.alert(
        "Erro no Roteamento",
        "Não foi possível atualizar a ordem das entregas. Tente novamente.",
        [{ text: "OK" }]
      );*/
    }
  }

  const toggleRoute = () => {
    setShowRoute(!showRoute)
  }

  const toggleFullscreen = () => {
    setIsFullscreen(!isFullscreen)
  }

  const toggleViewMode = () => {
    if (viewMode === "map") {
      setViewMode("list")
      setIsFullscreen(false)
    } else {
      setViewMode("map")
    }
  }

  const getStatusCount = (status: string) => {
    return deliveries.filter((d) => d.status === status).length
  }

  const getTotalDistance = () => {
    return deliveries
      .reduce((total, delivery) => {
        return total + (delivery.distance || 0)
      }, 0)
      .toFixed(1);
  };

  const getTotalDuration = () => {
    return Math.ceil(Number.parseFloat(getTotalDistance().toString()) * 2.4); // 25 km/h média
  };

  const getTotalStops = () => {
    return deliveries.length;
  }

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

  const getStatusText = (status: string) => {
    switch (status) {
      case "in_progress":
        return "Em rota"
      case "pending":
        return "Aguardando"
      case "delivered":
        return "Entregue"
      case "failed":
        return "Falhou"
      default:
        return "Aguardando"
    }
  }

  const renderDeliveryCard = ({ item, index }: { item: Delivery; index: number }) => {
    console.log(`🔍 Renderizando entrega ${index + 1}: ${item.customerName}, deliverySeq: ${item.deliverySeq}`)
    
    return (
      <TouchableOpacity style={styles.deliveryCard} onPress={() => handleDeliveryPress(item)}>
        <View style={styles.deliveryHeader}>
          <View style={styles.deliverySequence}>
            <Text style={styles.sequenceNumber}>
              {item.deliverySeq || index + 1}
            </Text>
          </View>

          <View style={styles.deliveryInfo}>
            <Text style={styles.customerName}>{item.customerName}</Text>
            <Text style={styles.deliveryAddress}>
              {item.street}, {item.streetNumber}
            </Text>
            <Text style={styles.deliveryNeighborhood}>
              {item.neighborhood}, {item.city}
            </Text>
          </View>

          <View style={styles.deliveryMeta}>
            <View style={[styles.statusBadge, { backgroundColor: `${getStatusColor(item.status)}20` }]}>
              <Text style={[styles.statusText, { color: getStatusColor(item.status) }]}>
                {getStatusText(item.status)}
              </Text>
            </View>
          </View>
        </View>

        <View style={styles.deliveryFooter}>
          <View style={styles.deliveryStats}>
            <View style={styles.statItem}>
              <Ionicons name="location" size={16} color={COLORS.textLight} />
              <Text style={styles.statText}>{item.distance?.toFixed(1) || "0.0"} km</Text>
            </View>
            <View style={styles.statItem}>
              <Ionicons name="time" size={16} color={COLORS.textLight} />
              <Text style={styles.statText}>{item.distance ? Math.ceil((item.distance / 25) * 60) : 0} min</Text>
            </View>
          </View>

          <TouchableOpacity style={styles.actionButton}>
            <Ionicons name="chevron-forward" size={20} color={COLORS.primary} />
          </TouchableOpacity>
        </View>
      </TouchableOpacity>
    )
  }

  const renderMapView = () => (
    <View style={styles.mapContainer}>
      <DeliveryMap
        ref={deliveryMapRef}
        deliveries={deliveries}
        onDeliveryPress={handleDeliveryPress}
        showRoute={showRoute}
        centerOnUser={false}
        // onRouteCalculated={handleRouteCalculated}
      />

      {/* Card único de informações da rota - Estilo Uber */}
      {showRoute && (
        <View style={styles.routeInfoFloating}>
          <View style={styles.routeCard}>
            <View style={styles.routeHeader}>
              <Ionicons name="map" size={20} color={COLORS.primary} />
              <Text style={styles.routeTitle}>Rota de Entregas</Text>
            </View>
            <View style={styles.routeStats}>
              <View style={styles.routeStat}>
                <Ionicons name="location" size={18} color={COLORS.primary} />
                <View style={styles.routeStatContent}>
                  <Text style={styles.routeStatValue}>{getTotalDistance()}</Text>
                  <Text style={styles.routeStatLabel}>km</Text>
                </View>
              </View>
              <View style={styles.routeStatDivider} />
              <View style={styles.routeStat}>
                <Ionicons name="time" size={18} color={COLORS.primary} />
                <View style={styles.routeStatContent}>
                  <Text style={styles.routeStatValue}>{getTotalDuration()}</Text>
                  <Text style={styles.routeStatLabel}>min</Text>
                </View>
              </View>
              <View style={styles.routeStatDivider} />
              <View style={styles.routeStat}>
                <Ionicons name="car" size={18} color={COLORS.primary} />
                <View style={styles.routeStatContent}>
                  <Text style={styles.routeStatValue}>{getTotalStops()}</Text>
                  <Text style={styles.routeStatLabel}>paradas</Text>
                </View>
              </View>
            </View>
          </View>
        </View>
      )}

      {/* Controles Flutuantes para Fullscreen */}
      {isFullscreen && (
        <View style={styles.fullscreenControls}>
          <SafeAreaView edges={["top"]} style={styles.fullscreenSafeArea}>
            <View style={styles.fullscreenHeaderSpacing}>
              <View style={styles.fullscreenHeader}>
                <TouchableOpacity style={styles.fullscreenButton} onPress={toggleFullscreen}>
                  <Ionicons name="contract" size={20} color="white" />
                </TouchableOpacity>

                <View style={styles.fullscreenInfo}>
                  <Text style={styles.fullscreenTitle}>Rotas de Entrega</Text>
                  <Text style={styles.fullscreenSubtitle}>
                    {getTotalStops()} entregas • {getTotalDistance()} km • {getTotalDuration()} min
                  </Text>
                </View>

                <TouchableOpacity style={styles.fullscreenButton} onPress={toggleRoute}>
                  <Ionicons name={showRoute ? "eye" : "eye-off"} size={20} color="white" />
                </TouchableOpacity>
              </View>
            </View>
          </SafeAreaView>


        </View>
      )}
    </View>
  )

  const renderListView = () => {
    const orderedDeliveries = getOrderedDeliveries(deliveries);
    
    // Log da ordenação para debug
    console.log('=== 🎯 ORDENAÇÃO DAS ENTREGAS NO ROUTESSCREEN ===');
    console.log('📊 Total de entregas:', orderedDeliveries.length);
    console.log('🔍 Entregas com routing === 1:', orderedDeliveries.filter(d => d.routing === 1).length);
    console.log('🔍 Entregas com routing === 0:', orderedDeliveries.filter(d => d.routing === 0).length);
    
    orderedDeliveries.slice(0, 5).forEach((delivery, index) => {
      console.log(`📦 Entrega ${index + 1}: ${delivery.customerName} (deliverySeq: ${delivery.deliverySeq}, routing: ${delivery.routing}, status: ${delivery.status})`);
    });
    if (orderedDeliveries.length > 5) {
      console.log(`📊 ... e mais ${orderedDeliveries.length - 5} entregas`);
    }
    
    return (
      <View style={styles.listContainer}>
        <FlatList
          data={orderedDeliveries}
          renderItem={renderDeliveryCard}
          keyExtractor={(item, index) => {
            // Garantir que sempre tenha uma chave única
            if (item.id && item.id !== 'null-null' && item.id !== 'undefined-undefined') {
              return item.id;
            }
            // Fallback para garantir unicidade
            return `delivery-${item.outId || 'unknown'}-${item.customerId || 'unknown'}-${index}`;
          }}
          showsVerticalScrollIndicator={false}
          contentContainerStyle={styles.listContent}
        />
      </View>
    );
  }

  if (loading) {
    return (
      <>
        <StatusBar style="light" backgroundColor={COLORS.primary} translucent={false} />
        <SafeAreaView style={styles.container}>
          <LinearGradient colors={[COLORS.primary, "#3B82F6"]} style={styles.loadingContainer}>
            <Ionicons name="map" size={48} color="white" />
            <Text style={styles.loadingText}>Carregando rotas...</Text>
            <Text style={styles.loadingSubtext}>Organizando entregas...</Text>
          </LinearGradient>
        </SafeAreaView>
      </>
    )
  }

  if (error) {
    return (
      <>
        <StatusBar style="light" backgroundColor={COLORS.primary} translucent={false} />
        <SafeAreaView style={styles.container}>
          <View style={styles.errorContainer}>
            <Ionicons name="alert-circle" size={48} color={COLORS.danger} />
            <Text style={styles.errorText}>{error}</Text>
                            <TouchableOpacity style={styles.retryButton} onPress={refreshDeliveries}>
              <LinearGradient
                colors={[COLORS.primary, "#3B82F6"]}
                style={styles.retryButtonGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <Ionicons name="refresh" size={16} color="white" />
                <Text style={styles.retryButtonText}>Tentar Novamente</Text>
              </LinearGradient>
            </TouchableOpacity>
          </View>
        </SafeAreaView>
      </>
    )
  }

  return (
    <>
      {/* StatusBar Global - sempre visível */}
      <StatusBar style="light" backgroundColor={COLORS.primary} translucent={false} />

      <View style={styles.container}>
        {/* Header Azul Otimizado com Controles */}
        {!isFullscreen && (
          <LinearGradient colors={[COLORS.primary, "#3B82F6"]} style={styles.headerGradient}>
            <SafeAreaView edges={["top"]} style={styles.safeAreaHeader}>
              <View style={styles.headerSpacing}>
                <View style={styles.optimizedHeader}>
                  <TouchableOpacity style={styles.headerControlButton} onPress={() => navigation.goBack()}>
                    <Ionicons name="arrow-back" size={22} color="white" />
                  </TouchableOpacity>

                  <TouchableOpacity style={styles.headerControlButton} onPress={toggleRoute}>
                    <Ionicons name={showRoute ? "eye" : "eye-off"} size={22} color="white" />
                  </TouchableOpacity>

                  <View style={styles.headerCenterInfo}>
                    <Text style={styles.headerMainTitle}>
                      {deliveries.length} entregas • {getTotalDistance()} km
                    </Text>
                    <Text style={styles.headerSubInfo}>
                      {getTotalDuration()} min • Rotas organizadas
                    </Text>
                  </View>

                  <TouchableOpacity style={styles.headerControlButton} onPress={toggleViewMode}>
                    <Ionicons name={viewMode === "map" ? "list" : "map"} size={22} color="white" />
                  </TouchableOpacity>

                  {!isFullscreen && viewMode === "map" && (
                    <TouchableOpacity style={styles.headerControlButton} onPress={toggleFullscreen}>
                      <Ionicons name="expand" size={22} color="white" />
                    </TouchableOpacity>
                  )}
                </View>
              </View>
            </SafeAreaView>
          </LinearGradient>
        )}

        {/* Estatísticas Compactas Otimizadas */}
        {!isFullscreen && (
          <View style={styles.optimizedStatsContainer}>
            <View style={styles.optimizedStatCard}>
              <View style={[styles.statDot, { backgroundColor: COLORS.warning }]} />
              <Text style={styles.optimizedStatNumber}>{getStatusCount("pending")}</Text>
              <Text style={styles.optimizedStatLabel}>Pendentes</Text>
            </View>

            <View style={styles.statDivider} />

            <View style={styles.optimizedStatCard}>
              <View style={[styles.statDot, { backgroundColor: COLORS.info }]} />
              <Text style={styles.optimizedStatNumber}>{getStatusCount("in_progress")}</Text>
              <Text style={styles.optimizedStatLabel}>Andamento</Text>
            </View>

            <View style={styles.statDivider} />

            <View style={styles.optimizedStatCard}>
              <View style={[styles.statDot, { backgroundColor: COLORS.success }]} />
              <Text style={styles.optimizedStatNumber}>{getStatusCount("delivered")}</Text>
              <Text style={styles.optimizedStatLabel}>Entregues</Text>
            </View>
          </View>
        )}

        {/* Conteúdo Principal Otimizado */}
        <View style={styles.optimizedContent}>
          {viewMode === "map" ? renderMapView() : renderListView()}
        </View>
      </View>
    </>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  headerGradient: {
    paddingBottom: 8,
  },
  safeAreaHeader: {
    backgroundColor: "transparent",
  },
  headerSpacing: {
    // Espaçamento adicional para evitar o notch/status bar
    paddingTop: Platform.OS === "ios" ? 20 : 16,
  },
  optimizedHeader: {
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 16,
    paddingVertical: 12,
    justifyContent: "space-between",
  },
  headerControlButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: "rgba(255, 255, 255, 0.2)",
    alignItems: "center",
    justifyContent: "center",
    marginHorizontal: 2,
  },
  headerCenterInfo: {
    flex: 1,
    alignItems: "center",
    marginHorizontal: 12,
  },
  headerMainTitle: {
    fontSize: 16,
    fontWeight: "bold",
    color: "white",
    textAlign: "center",
  },
  headerSubInfo: {
    fontSize: 12,
    color: "rgba(255, 255, 255, 0.8)",
    marginTop: 2,
    textAlign: "center",
  },
  optimizedStatsContainer: {
    flexDirection: "row",
    backgroundColor: COLORS.card,
    paddingVertical: 12,
    paddingHorizontal: 20,
    alignItems: "center",
    justifyContent: "space-around",
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border,
  },
  optimizedStatCard: {
    flex: 1,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
  },
  statDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    marginRight: 8,
  },
  optimizedStatNumber: {
    fontSize: 18,
    fontWeight: "bold",
    color: COLORS.text,
    marginRight: 4,
  },
  optimizedStatLabel: {
    fontSize: 12,
    color: COLORS.textLight,
  },
  statDivider: {
    width: 1,
    height: 20,
    backgroundColor: COLORS.border,
    marginHorizontal: 8,
  },
  optimizedContent: {
    flex: 1,
  },
  mapContainer: {
    flex: 1,
    position: "relative",
    paddingBottom: 80,
  },
  listContainer: {
    flex: 1,
  },
  listContent: {
    paddingHorizontal: 16,
    paddingTop: 16,
    paddingBottom: 20,
  },
  deliveryCard: {
    backgroundColor: COLORS.card,
    borderRadius: 16,
    padding: 16,
    marginBottom: 12,
    ...SHADOWS.medium,
  },
  deliveryHeader: {
    flexDirection: "row",
    alignItems: "flex-start",
    marginBottom: 12,
  },
  deliverySequence: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: COLORS.primary,
    alignItems: "center",
    justifyContent: "center",
    marginRight: 12,
  },
  sequenceNumber: {
    fontSize: 14,
    fontWeight: "bold",
    color: "white",
  },
  deliveryInfo: {
    flex: 1,
  },
  customerName: {
    fontSize: 16,
    fontWeight: "600",
    color: COLORS.text,
    marginBottom: 4,
  },
  deliveryAddress: {
    fontSize: 14,
    color: COLORS.text,
    marginBottom: 2,
  },
  deliveryNeighborhood: {
    fontSize: 12,
    color: COLORS.textLight,
  },
  deliveryMeta: {
    alignItems: "flex-end",
  },
  statusBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 8,
  },
  statusText: {
    fontSize: 10,
    fontWeight: "500",
  },
  deliveryFooter: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
  },
  deliveryStats: {
    flexDirection: "row",
  },
  statItem: {
    flexDirection: "row",
    alignItems: "center",
    marginRight: 16,
  },
  statText: {
    fontSize: 12,
    color: COLORS.textLight,
    marginLeft: 4,
  },
  actionButton: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: `${COLORS.primary}20`,
    alignItems: "center",
    justifyContent: "center",
  },
  routeInfoFloating: {
    position: "absolute",
    bottom: Platform.OS === "ios" ? 40 : 20,
    left: 16,
    right: 16,
    zIndex: 1000,
  },

  fullscreenControls: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    pointerEvents: "box-none",
  },
  fullscreenSafeArea: {
    backgroundColor: "transparent",
  },
  fullscreenHeaderSpacing: {
    paddingTop: Platform.OS === "ios" ? 20 : 16,
  },
  fullscreenHeader: {
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 16,
    paddingVertical: 12,
    backgroundColor: "rgba(37, 99, 235, 0.9)",
    marginHorizontal: 16,
    borderRadius: 12,
    ...SHADOWS.medium,
  },
  fullscreenButton: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: "rgba(255, 255, 255, 0.2)",
    alignItems: "center",
    justifyContent: "center",
    marginHorizontal: 4,
  },
  fullscreenInfo: {
    flex: 1,
    alignItems: "center",
    marginHorizontal: 12,
  },
  fullscreenTitle: {
    fontSize: 16,
    fontWeight: "bold",
    color: "white",
  },
  fullscreenSubtitle: {
    fontSize: 12,
    color: "rgba(255, 255, 255, 0.8)",
    marginTop: 2,
  },
  routeInfoFullscreen: {
    position: "absolute",
    bottom: 20,
    left: 16,
    right: 16,
    backgroundColor: "rgba(255, 255, 255, 0.95)",
    borderRadius: 16,
    padding: 16,
    ...SHADOWS.medium,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  loadingText: {
    fontSize: 18,
    color: "white",
    marginTop: 16,
    fontWeight: "600",
  },
  loadingSubtext: {
    fontSize: 14,
    color: "rgba(255, 255, 255, 0.8)",
    marginTop: 8,
  },
  errorContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    paddingHorizontal: 20,
  },
  errorText: {
    fontSize: 16,
    color: COLORS.danger,
    textAlign: "center",
    marginVertical: 16,
  },
  retryButton: {
    borderRadius: 12,
    overflow: "hidden",
    ...SHADOWS.medium,
  },
  retryButtonGradient: {
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 20,
    paddingVertical: 12,
    gap: 8,
  },
  retryButtonText: {
    color: "white",
    fontSize: 14,
    fontWeight: "600",
  },
  // Novos estilos para o card de rota estilo Uber
  routeCard: {
    backgroundColor: 'white',
    borderRadius: 16,
    padding: 16,
    ...SHADOWS.medium,
    borderWidth: 1,
    borderColor: 'rgba(0, 0, 0, 0.05)',
  },
  routeHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 12,
    gap: 8,
  },
  routeTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: COLORS.text,
  },
  routeStats: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  routeStat: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
  },
  routeStatContent: {
    alignItems: 'flex-start',
  },
  routeStatValue: {
    fontSize: 18,
    fontWeight: '700',
    color: COLORS.text,
    lineHeight: 20,
  },
  routeStatLabel: {
    fontSize: 12,
    color: COLORS.textLight,
    fontWeight: '500',
  },
  routeStatDivider: {
    width: 1,
    height: 32,
    backgroundColor: 'rgba(0, 0, 0, 0.1)',
    marginHorizontal: 8,
  },
})

RoutesScreen.navigationOptions = {
  headerShown: false,
}

export default RoutesScreen
