"use client"

import React from "react"
import { View, Text, Image, StyleSheet, ScrollView, TouchableOpacity, Alert, Platform } from "react-native"
import { useNavigation } from "@react-navigation/native"
import type { NativeStackNavigationProp } from "@react-navigation/native-stack"
import { SafeAreaView } from "react-native-safe-area-context"
import { LinearGradient } from "expo-linear-gradient"
import { COLORS, SHADOWS } from "../../constants/theme"
import { useAuth } from "../../contexts/AuthContext"
import { useSync } from "../../contexts/SyncContext"
import { useDeliveries } from "../../contexts/DeliveriesContext"
import { useOfflineMode } from "../../contexts/OfflineModeContext"
import { offlineSyncService } from "../../services/offlineSyncService"
import { executeQuery } from "../../services/database"

import { useEffect, useState, useMemo, useCallback } from "react"
import { useFocusEffect, useRoute } from "@react-navigation/native"
import { Ionicons } from "@expo/vector-icons"
import type { Delivery } from "../../types"
import { mockDeliveries } from "../../config/mockData"
import { StatusBar } from "expo-status-bar"
import DebugPanel from "../../components/DebugPanel"

type RootStackParamList = {
  DeliveriesStack: {
    screen?: string
    params?: {
      deliveryId?: number
      screen?: "DeliveryDetail" | "CompleteDelivery" | "RescheduleDelivery"
    }
  }
  RoutesStack: undefined
  Home: {
    refreshDeliveries?: boolean
    routingUpdated?: boolean
  }
  Profile: undefined
}

type NavigationProp = NativeStackNavigationProp<RootStackParamList>

const logoBase64 = `data:image/png;base64, `;

const HomeScreen = () => {
  const navigation = useNavigation<NavigationProp>()
  const route = useRoute()
  const { user } = useAuth()
  const { isOnline, pendingSyncCount, lastSyncTime, syncNow, isSyncing } = useSync()
  const { 
    deliveries, 
    loading, 
    error, 
    hasNoDeliveries, 
    refreshDeliveries, 
    forceRefresh, 
    isRefreshing,
    updateDeliveriesWithRandomSeq,
    getNextDelivery
  } = useDeliveries()
  const { syncStats, isOfflineMode, refreshSyncStats, registerDeliveryStatusCallback } = useOfflineMode()

  const [hasOfflineDeliveries, setHasOfflineDeliveries] = useState(false)
  const [pendingDeliveriesCount, setPendingDeliveriesCount] = useState(0)
  
  // Verificar se há entregas pendentes para sincronizar
  const hasPendingDeliveries = useMemo(() => {
    return pendingDeliveriesCount > 0
  }, [pendingDeliveriesCount])
  const [showDebugPanel, setShowDebugPanel] = useState(false)

  // Ordenar entregas por sequência (deliverySeq) e status
  const sortedDeliveries = useMemo(() => {
    // console.log('=== HOMESCREEN: ORDENANDO ENTREGAS ===')
    // console.log('Total de entregas recebidas:', deliveries.length)
    // console.log('Primeiras 3 entregas:', deliveries.slice(0, 3).map(d => ({
    //   id: d.id,
    //   customerName: d.customerName,
    //   deliverySeq: d.deliverySeq,
    //   status: d.status,
    //   routing: d.routing
    // })))
    
    const sorted = [...deliveries].sort((a, b) => {
      // REGRA PRINCIPAL: Se routing === 1, SEMPRE respeitar deliverySeq primeiro
      if (a.routing === 1 && b.routing === 1) {
        // PRIMEIRO: Ordenar por deliverySeq (sequência de entrega otimizada pelo TSP)
        if (a.deliverySeq !== b.deliverySeq) {
          return a.deliverySeq - b.deliverySeq;
        }
      }
      
      // SEGUNDO: Se deliverySeq for igual ou routing !== 1, 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 deliverySeq
      if (a.deliverySeq !== b.deliverySeq) {
        return a.deliverySeq - b.deliverySeq;
      }

      // QUARTO: Se deliverySeq for igual, ordenar por distância
      if (a.distance !== b.distance) {
        return (a.distance || 0) - (b.distance || 0)
      }

      // QUINTO: Por último, ordenar por data
      return new Date(a.outDate).getTime() - new Date(b.outDate).getTime()
    });
    
    // Log da ordenação para debug
    // console.log('=== 🎯 ORDENAÇÃO DAS ENTREGAS NO HOMESCREEN ===');
    // console.log('📊 Total de entregas:', sorted.length);
    // console.log('🔍 Entregas com routing === 1:', sorted.filter(d => d.routing === 1).length);
    // console.log('🔍 Entregas com routing === 0:', sorted.filter(d => d.routing === 0).length);
    
    // sorted.slice(0, 5).forEach((delivery, index) => {
    //   console.log(`📦 Entrega ${index + 1}: ${delivery.customerName} (deliverySeq: ${delivery.deliverySeq}, routing: ${delivery.routing}, status: ${delivery.status})`);
    // });
    // if (sorted.length > 5) {
    //   console.log(`📊 ... e mais ${sorted.length - 5} entregas`);
    // }
    
    // console.log('Entregas ordenadas:', sorted.length)
    // console.log('Primeiras 3 entregas ordenadas:', sorted.slice(0, 3).map(d => ({
    //   id: d.id,
    //   customerName: d.customerName,
    //   deliverySeq: d.deliverySeq,
    //   status: d.status,
    //   routing: d.routing
    // })))
    
    return sorted;
  }, [deliveries])

  // Recarregar entregas sempre que a tela receber foco (exceto na primeira vez)
  const [hasInitialized, setHasInitialized] = useState(false)
  const [needsRouting, setNeedsRouting] = useState(false)
  const [hasCheckedRouting, setHasCheckedRouting] = useState(false)
  const [lastRefreshTime, setLastRefreshTime] = useState<number>(0)
  
  // Resetar verificação de roteirização quando necessário
  const resetRoutingCheck = () => {
    setHasCheckedRouting(false);
    setNeedsRouting(false);
  };
  
  // Função para carregar entregas pendentes (mesma lógica do CheckoutScreen)
  const loadPendingDeliveries = useCallback(async () => {
    try {
      const result = await executeQuery(
        "SELECT * FROM deliveries WHERE syncTimestamp IS NULL OR syncTimestamp < lastModified ORDER BY lastModified DESC"
      )
      const count = result.rows._array?.length || 0
      setPendingDeliveriesCount(count)
      setHasOfflineDeliveries(count > 0)
      console.log('📊 HomeScreen: Entregas pendentes carregadas:', count)
    } catch (error) {
      console.error("❌ HomeScreen: Erro ao carregar entregas pendentes:", error)
      setPendingDeliveriesCount(0)
    }
  }, [])
  
  // Função para gerar deliverySeq aleatória sequencial quando routing=0
  const generateRandomDeliverySeq = (deliveries: Delivery[]): Delivery[] => {
    const deliveriesWithoutSeq = deliveries.filter(delivery => 
      delivery.routing === 0 && delivery.deliverySeq === 0
    );
    
    if (deliveriesWithoutSeq.length === 0) {
      return deliveries;
    }
    
    
    // Gerar números aleatórios sequenciais únicos
    const totalDeliveries = deliveriesWithoutSeq.length;
    const randomSequences = Array.from({ length: totalDeliveries }, (_, i) => i + 1)
      .sort(() => Math.random() - 0.5); // Embaralhar array
    
    
    // Atualizar entregas com deliverySeq aleatória
    const updatedDeliveries = deliveries.map(delivery => {
      if (delivery.routing === 0 && delivery.deliverySeq === 0) {
        const randomSeq = randomSequences.pop() || 1;
        return { ...delivery, deliverySeq: randomSeq };
      }
      return delivery;
    });
    
    return updatedDeliveries;
  };

  // Verificar se precisa de roteirização - APENAS UMA VEZ quando as entregas mudarem
  useEffect(() => {
    // Evitar verificação múltipla
    if (hasCheckedRouting || deliveries.length === 0) {
      // console.log('=== 🏠 DEBUG: PULANDO VERIFICAÇÃO DE ROTEIRIZAÇÃO ===');
      // console.log('hasCheckedRouting:', hasCheckedRouting);
      // console.log('deliveries.length:', deliveries.length);
      return;
    }
    
    
    // Marcar que já verificou para evitar loops
    setHasCheckedRouting(true);
    
    
    // Verificar entregas que precisam de roteirização (routing !== 0 e deliverySeq === 0)
    const needsRoutingDeliveries = deliveries.filter(delivery => 
      delivery.routing !== 0 && delivery.deliverySeq === 0
    );
    
    // Verificar entregas com routing=0 que precisam de deliverySeq aleatória
    const routingZeroDeliveries = deliveries.filter(delivery => 
      delivery.routing === 0 && delivery.deliverySeq === 0
    );
    
    
    if (routingZeroDeliveries.length > 0) {
      
      // Gerar deliverySeq aleatória para entregas com routing=0
      const updatedDeliveries = generateRandomDeliverySeq(deliveries);
      
      // Atualizar o estado das entregas com as novas deliverySeq usando o contexto
      updateDeliveriesWithRandomSeq(updatedDeliveries);
      
      // Não navegar para tela de roteirização - ficar no Home
      setNeedsRouting(false);
      
    } else if (needsRoutingDeliveries.length > 0) {
      
      setNeedsRouting(true);
      
      // Usar setTimeout para evitar navegação durante renderização
      setTimeout(() => {
        try {
          // Usar reset para evitar voltar para Home
          navigation.reset({
            index: 0,
            routes: [{ name: 'Routing' as never }],
          });
        } catch (navError) {
          navigation.reset({
            index: 0,
            routes: [{ name: 'Main' as never }],
          });
        }
      }, 100);
    } else {
      setNeedsRouting(false);
    }
  }, [deliveries, hasCheckedRouting, navigation]);
  
  useFocusEffect(
    React.useCallback(() => {
      // Verificar se deve recarregar devido a parâmetros da rota
      const params = route.params as { refreshDeliveries?: boolean; routingUpdated?: boolean } | undefined
      const shouldRefresh = params?.refreshDeliveries
      const routingUpdated = params?.routingUpdated
      
      
      if (hasInitialized) {
        // Proteção contra chamadas muito frequentes (mínimo 2 segundos entre refreshes)
        const now = Date.now()
        const timeSinceLastRefresh = now - (lastRefreshTime || 0)
        
        if (timeSinceLastRefresh < 2000) {
          return
        }
        
        // SEMPRE recarregar quando a tela ganha foco para garantir próxima entrega atualizada
        setLastRefreshTime(now)
        
        // Se foi atualizado o roteamento, resetar verificação
        if (routingUpdated) {
          setHasCheckedRouting(false)
          setNeedsRouting(false)
        }
        
        // Usar o contexto para recarregar entregas
        refreshDeliveries()
        
        // Verificar se precisa gerar deliverySeq para routing=0
        const routingZeroDeliveries = deliveries.filter(delivery => 
          delivery.routing === 0 && delivery.deliverySeq === 0
        )
        
        if (routingZeroDeliveries.length > 0) {
          
          // Gerar deliverySeq aleatória para entregas com routing=0
          const updatedDeliveries = generateRandomDeliverySeq(deliveries)
          
          // Atualizar o estado das entregas com as novas deliverySeq
          updateDeliveriesWithRandomSeq(updatedDeliveries)
          
        }
        
        // Atualizar estatísticas de sincronização
        refreshSyncStats().catch(() => {})
        // Carregar entregas pendentes (mesma lógica do CheckoutScreen)
        loadPendingDeliveries()
        
        // Limpar os parâmetros após usar (se existirem)
        if (shouldRefresh || routingUpdated) {
          navigation.setParams({ 
            refreshDeliveries: undefined,
            routingUpdated: undefined 
          })
        }
      } else {
        setHasInitialized(true)
        // Atualizar estatísticas de sincronização na primeira vez
        refreshSyncStats().catch(() => {})
        // Carregar entregas pendentes na primeira vez
        loadPendingDeliveries()
      }
    }, [hasInitialized, route.params, lastRefreshTime, loadPendingDeliveries])
  )

  // Carregar entregas pendentes quando syncStats mudar ou quando entregas mudarem
  useEffect(() => {
    loadPendingDeliveries()
  }, [syncStats, deliveries.length, loadPendingDeliveries])

  // Registrar callback para atualizar contador quando uma entrega for finalizada
  useEffect(() => {
    const handleDeliveryStatusChange = async () => {
      console.log('🔄 HomeScreen: Entrega finalizada, atualizando contador...')
      // Aguardar um pouco para garantir que o banco foi atualizado
      await new Promise(resolve => setTimeout(resolve, 300))
      // Recarregar entregas pendentes usando a mesma query do CheckoutScreen
      await loadPendingDeliveries()
      console.log('✅ HomeScreen: Contador atualizado após finalização')
    }
    
    registerDeliveryStatusCallback(handleDeliveryStatusChange)
    
    return () => {
      // Limpar callback quando componente desmontar
      registerDeliveryStatusCallback(() => {})
    }
  }, [registerDeliveryStatusCallback])

  // Usar a função do contexto para obter a próxima entrega
  const nextDelivery = getNextDelivery()
  
  useEffect(() => {
    // Próxima entrega atualizada
  }, [nextDelivery?.id, nextDelivery?.status, deliveries.length])

  const formatDate = (date: string | number | null | undefined) => {
    if (!date) return "Hoje"
    const today = new Date()
    const deliveryDate = new Date(date)

    if (deliveryDate.toDateString() === today.toDateString()) {
      return "Hoje"
    }

    return deliveryDate.toLocaleDateString("pt-BR", {
      day: "2-digit",
      month: "short",
    })
  }

  const formatTime = (date: string | number | null | undefined) => {
    if (!date) return ""
    return new Date(date).toLocaleTimeString("pt-BR", {
      hour: "2-digit",
      minute: "2-digit",
    })
  }

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

  const handleSyncNow = async () => {
    if (!isOnline) {
      Alert.alert("Erro", "Você está offline. Conecte-se à internet para sincronizar.")
      return
    }

    const success = await syncNow()
    if (success) {
      Alert.alert("Sucesso", "Dados sincronizados com sucesso!")
      refreshDeliveries()
    }
  }

  const getStatusInfo = (status: string) => {
    switch (status) {
      case "in_progress":
        return {
          status: "Em rota",
          icon: "car-sport",
          color: COLORS.info,
        }
      case "pending":
        return {
          status: "Aguardando",
          icon: "time",
          color: COLORS.warning,
        }
      case "delivered":
        return {
          status: "Entregue",
          icon: "checkmark-circle",
          color: COLORS.success,
        }
      case "failed":
        return {
          status: "Falhou",
          icon: "close-circle",
          color: COLORS.danger,
        }
      default:
        return {
          status: "Aguardando",
          icon: "time",
          color: COLORS.warning,
        }
    }
  }

  const formatAddress = (delivery: Delivery) => {
    return `${delivery.street}, ${delivery.streetNumber} - ${delivery.neighborhood}`
  }

  const getUserInitials = () => {
    if (!user?.name) return "U"
    const names = user.name.trim().split(" ").filter(name => name.length > 0)
    if (names.length >= 2) {
      return `${names[0][0]}${names[names.length - 1][0]}`.toUpperCase()
    }
    return names[0][0].toUpperCase()
  }

  const getGreeting = () => {
    const hour = new Date().getHours()
    if (hour < 12) return "Bom dia"
    if (hour < 18) return "Boa tarde"
    return "Boa noite"
  }

  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="home" size={48} color="white" />
            <Text style={styles.loadingText}>Carregando painel...</Text>
            <Text style={styles.loadingSubtext}>Sincronizando entregas...</Text>
          </LinearGradient>
        </SafeAreaView>
      </>
    )
  }

  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="home" size={48} color="white" />
            <Text style={styles.loadingText}>Carregando painel...</Text>
            <Text style={styles.loadingSubtext}>Sincronizando entregas...</Text>
          </LinearGradient>
        </SafeAreaView>
      </>
    )
  }

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

      <View style={styles.container}>
        {/* Header com Espaçamento Adequado */}
        <LinearGradient colors={[COLORS.primary, "#3B82F6"]} style={styles.headerGradient}>
          <SafeAreaView edges={["top"]} style={styles.safeAreaHeader}>
            <View style={styles.header}>
              <View style={styles.headerLeft}>
                <Image source={{ uri: logoBase64 }} style={styles.logo} />
                <View style={styles.greetingContainer}>
                  <Text style={styles.greeting}>
                    {getGreeting()}, {user?.name?.split(" ")[0]}
                  </Text>
                  <View style={styles.statusContainer}>
                    <View
                      style={[styles.statusDot, { backgroundColor: isOnline ? COLORS.success : COLORS.warning }]}
                    />
                    <Text style={styles.statusText}>{isOnline ? "Online" : "Offline"}</Text>
                  </View>
                </View>
              </View>

              <TouchableOpacity
                style={styles.avatarButton}
                onPress={() => navigation.navigate("Profile")}
              >
                <Text style={styles.avatarText}>{getUserInitials()}</Text>
              </TouchableOpacity>
            </View>
          </SafeAreaView>
        </LinearGradient>



        {/* Estatísticas Compactas */}
        <View style={styles.statsContainer}>
          <View style={styles.statCard}>
            <Text style={styles.statNumber}>{deliveries.filter((d) => d.status === "pending").length}</Text>
            <Text style={styles.statLabel}>Pendentes</Text>
          </View>

          <View style={styles.statCard}>
            <Text style={styles.statNumber}>{deliveries.filter((d) => d.status === "in_progress").length}</Text>
            <Text style={styles.statLabel}>Em Rota</Text>
          </View>

          <View style={styles.statCard}>
            <Text style={styles.statNumber}>{deliveries.filter((d) => d.status === "delivered").length}</Text>
            <Text style={styles.statLabel}>Entregues</Text>
          </View>

          <View style={styles.statCard}>
            <Text style={styles.statNumber}>{deliveries.filter((d) => d.status === "failed").length}</Text>
            <Text style={styles.statLabel}>Falhas</Text>
          </View>
        </View>

        <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
          {/* Card de Sincronização Pendente */}
          {hasPendingDeliveries && (
            <View style={styles.syncCard}>
              <View style={styles.syncCardHeader}>
                <View style={styles.syncCardTitleContainer}>
                  <Ionicons name="cloud-upload" size={20} color={COLORS.warning} />
                  <Text style={styles.syncCardTitle}>Sincronização Pendente</Text>
                </View>
                {pendingDeliveriesCount > 0 && (
                  <View style={styles.syncBadge}>
                    <Text style={styles.syncBadgeText}>
                      {pendingDeliveriesCount}
                    </Text>
                  </View>
                )}
              </View>

              <View style={styles.syncCardButtons}>
                {/* <TouchableOpacity
                  style={[
                    styles.syncCardButton, 
                    (!isOnline || !hasPendingDeliveries) && styles.syncCardButtonDisabled
                  ]}
                  onPress={handleSyncNow}
                  disabled={!isOnline || isSyncing || !hasPendingDeliveries}
                >
                  <Ionicons name={isSyncing ? "sync" : "cloud-upload"} size={16} color="white" />
                  <Text style={styles.syncCardButtonText}>
                    {isSyncing ? "Sincronizando..." : 
                     !isOnline ? "Offline" : 
                     !hasPendingDeliveries ? "Nada para sincronizar" : 
                     "Sincronizar Agora"}
                  </Text>
                </TouchableOpacity> */}

                <TouchableOpacity
                  style={styles.checkoutButton}
                  onPress={() => navigation.navigate("DeliveriesStack" as any, {
                    screen: "Checkout"
                  })}
                >
                  <Ionicons name="list" size={16} color={COLORS.primary} />
                  <Text style={styles.checkoutButtonText}>Sincronizar Agora</Text>
                </TouchableOpacity>
              </View>
            </View>
          )}

          {/* Próxima Entrega */}
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionTitle}>Próxima Entrega</Text>
            {deliveries.length > 1 && (
              <TouchableOpacity onPress={() => navigation.navigate("DeliveriesStack" as any)}>
                <Text style={styles.seeAllText}>Ver todas ({deliveries.length})</Text>
              </TouchableOpacity>
            )}
          </View>

          {error && hasNoDeliveries ? (
            <View style={styles.emptyContainer}>
              <LinearGradient
                colors={["#FEF3C7", "#FFFBEB"]}
                style={styles.emptyCard}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
              >
                <Ionicons name="document-text" size={64} color={COLORS.warning} />
                <Text style={styles.emptyTitle}>Nenhuma Entrega</Text>
                <Text style={styles.emptyText}>Não existem entregas disponíveis no momento</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}>Atualizar</Text>
                  </LinearGradient>
                </TouchableOpacity>
              </LinearGradient>
            </View>
          ) : error ? (
            <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>
          ) : !nextDelivery ? (
            <View style={styles.emptyContainer}>
              <LinearGradient
                colors={["#D1FAE5", "#F0FDF4"]}
                style={styles.emptyCard}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
              >
                <Ionicons name="checkmark-circle" size={64} color={COLORS.success} />
                <Text style={styles.emptyTitle}>Parabéns!</Text>
                <Text style={styles.emptyText}>Todas as entregas foram concluídas</Text>
              </LinearGradient>
            </View>
          ) : (
            <TouchableOpacity
              style={styles.nextDeliveryCard}
              onPress={() => handleNavigateToDeliveryDetail(nextDelivery)}
            >
              <View style={styles.deliveryHeader}>
                {/* <View style={styles.deliverySequence}>
                  <Text style={styles.sequenceNumber}>{nextDelivery.deliverySeq}</Text>
                </View> */}

                <View style={styles.deliveryMainInfo}>
                  <Text style={styles.deliveryClient}>{nextDelivery.customerName}</Text>
                  <Text style={styles.deliveryOrderNumber}>
                    Pedido #{nextDelivery.outId.toString().padStart(5, "0")}
                  </Text>
                </View>

                <View
                  style={[styles.statusBadge, { backgroundColor: `${getStatusInfo(nextDelivery.status).color}20` }]}
                >
                  <Ionicons
                    name={getStatusInfo(nextDelivery.status).icon as any}
                    size={14}
                    color={getStatusInfo(nextDelivery.status).color}
                  />
                  <Text style={[styles.statusText, { color: getStatusInfo(nextDelivery.status).color }]}>
                    {getStatusInfo(nextDelivery.status).status}
                  </Text>
                </View>
              </View>

              <View style={styles.deliveryDetails}>
                <View style={styles.deliveryDetailRow}>
                  <Ionicons name="location" size={16} color={COLORS.textLight} />
                  <Text style={styles.deliveryAddress}>{formatAddress(nextDelivery)}</Text>
                </View>

                <View style={styles.deliveryDetailRow}>
                  <Ionicons name="call" size={16} color={COLORS.textLight} />
                  <Text style={styles.deliveryPhone}>{nextDelivery.customerPhone}</Text>
                </View>

                <View style={styles.deliveryDetailRow}>
                  <Ionicons name="time" size={16} color={COLORS.textLight} />
                  <Text style={styles.deliveryTime}>
                    {formatDate(nextDelivery.outDate)} • {formatTime(nextDelivery.outDate)}
                  </Text>
                </View>

                <View style={styles.deliveryDetailRow}>
                  <Ionicons name="navigate" size={16} color={COLORS.textLight} />
                  <Text style={styles.deliveryDistance}>
                    {nextDelivery.distance?.toFixed(1) || "0.0"} km de distância
                  </Text>
                </View>
              </View>

              <View style={styles.deliveryActions}>
                <View style={styles.actionButton}>
                  <Ionicons name="play-circle" size={20} color={COLORS.primary} />
                  <Text style={styles.actionButtonText}>Iniciar Entrega</Text>
                </View>
                <Ionicons name="chevron-forward" size={24} color={COLORS.primary} />
              </View>
            </TouchableOpacity>
          )}

          {/* Informações de Sincronização */}
          <View style={styles.syncInfoContainer}>
            <Ionicons name="information-circle" size={16} color={COLORS.textLight} />
            <Text style={styles.syncInfoText}>
              Última sincronização: {lastSyncTime ? formatDate(lastSyncTime) : "Nunca"}
            </Text>
          </View>
        </ScrollView>

        {/* Botão de Debug 
        <TouchableOpacity
          style={styles.debugButton}
          onPress={() => setShowDebugPanel(true)}
        >
          <Ionicons name="bug" size={20} color="white" />
        </TouchableOpacity>*/}

        {/* Painel de Debug */}
        <DebugPanel
          isVisible={showDebugPanel}
          onToggle={() => setShowDebugPanel(false)}
        />
      </View>
    </>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  headerGradient: {
    paddingBottom: 16,
  },
  safeAreaHeader: {
    backgroundColor: "transparent",
  },
  headerSpacing: {
    // Espaçamento adicional para evitar o notch/status bar
    paddingTop: Platform.OS === "ios" ? 10 : 16,
  },
  header: {
    flexDirection: "row",
    alignItems: "flex-start",
    justifyContent: "space-between",
    paddingHorizontal: 20,
    paddingVertical: 16,
  },
  headerLeft: {
    flex: 1,
    alignItems: "flex-start",
    marginTop: -15,
  },
  logo: {
    width: 180,
    height: 100, 
    resizeMode: "contain",
    marginBottom: 0, // Espaço entre logo e texto
  },
  greetingContainer: {
    marginTop: 8,
  },
  greeting: {
    fontSize: 20,
    fontWeight: "bold",
    color: "white",
    marginBottom: 4,
  },
  statusContainer: {
    flexDirection: "row",
    alignItems: "center",
  },
  statusDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    marginRight: 6,
  },
  statusText: {
    fontSize: 14,
    color: "rgba(255, 255, 255, 0.8)",
  },
  avatarButton: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: "rgba(255, 255, 255, 0.2)",
    alignItems: "center",
    justifyContent: "center",
    borderWidth: 2,
    borderColor: "rgba(255, 255, 255, 0.3)",
    marginTop: Platform.OS === "ios" ? 8 : 4, // Ajuste para alinhar com o conteúdo
  },
  avatarText: {
    fontSize: 18,
    fontWeight: "bold",
    color: "white",
  },
  statsContainer: {
    flexDirection: "row",
    backgroundColor: COLORS.card,
    paddingVertical: 20,
    paddingHorizontal: 20,
    marginHorizontal: 16,
    marginTop: -8,
    borderRadius: 16,
    ...SHADOWS.medium,
  },
  statCard: {
    flex: 1,
    alignItems: "center",
  },
  statNumber: {
    fontSize: 24,
    fontWeight: "bold",
    color: COLORS.primary,
    marginBottom: 4,
  },
  statLabel: {
    fontSize: 12,
    color: COLORS.textLight,
  },
  content: {
    flex: 1,
    marginTop: 16,
    paddingBottom: 80, // Espaço para os botões fixos
  },
  syncCard: {
    backgroundColor: COLORS.card,
    borderRadius: 16,
    padding: 16,
    marginHorizontal: 16,
    marginBottom: 16,
    ...SHADOWS.medium,
    borderLeftWidth: 4,
    borderLeftColor: COLORS.warning,
  },
  syncCardHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 12,
  },
  syncCardTitleContainer: {
    flexDirection: "row",
    alignItems: "center",
  },
  syncCardTitle: {
    fontSize: 16,
    fontWeight: "bold",
    color: COLORS.text,
    marginLeft: 8,
  },
  syncBadge: {
    backgroundColor: COLORS.warning,
    borderRadius: 12,
    paddingHorizontal: 8,
    paddingVertical: 4,
  },
  syncBadgeText: {
    color: "white",
    fontWeight: "bold",
    fontSize: 12,
  },
  syncCardButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: COLORS.primary,
    borderRadius: 12,
    paddingVertical: 12,
    paddingHorizontal: 16,
  },
  syncCardButtonDisabled: {
    backgroundColor: COLORS.textLight,
  },
  syncCardButtonText: {
    color: "white",
    fontWeight: "600",
    fontSize: 14,
    marginLeft: 8,
  },
  syncCardButtons: {
    flexDirection: "row",
    gap: 12,
  },
  checkoutButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "white",
    borderRadius: 12,
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderWidth: 2,
    borderColor: COLORS.primary,
    flex: 1,
  },
  checkoutButtonText: {
    color: COLORS.primary,
    fontWeight: "600",
    fontSize: 14,
    marginLeft: 8,
  },
  sectionHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingHorizontal: 16,
    marginBottom: 16,
  },
  sectionTitle: {
    fontSize: 20,
    fontWeight: "bold",
    color: COLORS.text,
  },
  seeAllText: {
    fontSize: 14,
    color: COLORS.primary,
    fontWeight: "500",
  },
  nextDeliveryCard: {
    backgroundColor: COLORS.card,
    borderRadius: 20,
    padding: 20,
    marginHorizontal: 16,
    marginBottom: 16,
    ...SHADOWS.medium,
    borderWidth: 2,
    borderColor: COLORS.primary + "20",
  },
  deliveryHeader: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 16,
  },
  deliverySequence: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: COLORS.primary,
    alignItems: "center",
    justifyContent: "center",
    marginRight: 16,
  },
  sequenceNumber: {
    fontSize: 14,
    fontWeight: "bold",
    color: "white",
  },
  deliveryMainInfo: {
    flex: 1,
  },
  deliveryClient: {
    fontSize: 16,
    fontWeight: "bold",
    color: COLORS.text,
    marginBottom: 4,
  },
  deliveryOrderNumber: {
    fontSize: 14,
    color: COLORS.primary,
    fontWeight: "500",
  },
  statusBadge: {
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 12,
  },
  deliveryDetails: {
    marginBottom: 20,
  },
  deliveryDetailRow: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 8,
  },
  deliveryAddress: {
    fontSize: 14,
    color: COLORS.text,
    marginLeft: 12,
    flex: 1,
  },
  deliveryPhone: {
    fontSize: 14,
    color: COLORS.textLight,
    marginLeft: 12,
  },
  deliveryTime: {
    fontSize: 14,
    color: COLORS.textLight,
    marginLeft: 12,
  },
  deliveryDistance: {
    fontSize: 14,
    color: COLORS.textLight,
    marginLeft: 12,
  },
  deliveryActions: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    borderTopWidth: 1,
    borderTopColor: COLORS.border,
    paddingTop: 16,
  },
  actionButton: {
    flexDirection: "row",
    alignItems: "center",
  },
  actionButtonText: {
    fontSize: 16,
    color: COLORS.primary,
    fontWeight: "600",
    marginLeft: 8,
  },
  syncInfoContainer: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    padding: 20,
    marginTop: -20,
  },
  syncInfoText: {
    fontSize: 12,
    color: COLORS.textLight,
    marginLeft: 6,
  },
  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: {
    padding: 20,
    alignItems: "center",
    marginHorizontal: 16,
  },
  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",
  },
  emptyContainer: {
    padding: 20,
    alignItems: "center",
    marginHorizontal: 16,
  },
  emptyCard: {
    padding: 40,
    borderRadius: 20,
    alignItems: "center",
    borderWidth: 1,
    borderColor: "#D1FAE5",
  },
  emptyTitle: {
    fontSize: 20,
    fontWeight: "bold",
    color: COLORS.text,
    marginTop: 16,
    marginBottom: 8,
  },
  emptyText: {
    fontSize: 14,
    color: COLORS.textLight,
    textAlign: "center",
  },
  debugButton: {
    position: 'absolute',
    bottom: 100,
    right: 20,
    width: 50,
    height: 50,
    borderRadius: 25,
    backgroundColor: COLORS.secondary,
    alignItems: 'center',
    justifyContent: 'center',
    ...SHADOWS.medium,
    zIndex: 100,
  },
})

export default HomeScreen
