"use client"

import { useState, useEffect, useRef } from "react"
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Alert,
  Dimensions,
  PanResponder,
  Animated,
  Modal,
  SafeAreaView,
  Linking,
  Platform,
  ActivityIndicator,
  Image,
} from "react-native"
import { useRoute, useNavigation } from "@react-navigation/native"
import { LinearGradient } from "expo-linear-gradient"
import { Ionicons } from "@expo/vector-icons"
import * as Location from "expo-location"
import { COLORS, SHADOWS } from "../../constants/theme"
import { updateDeliveryStatus } from "../../services/database"
import { useMockData } from "../../hooks/useMockData"
import type { Delivery } from "../../types"
import DeliveryMap from "../../components/DeliveryMap"
import { api, getCoordinatesFromAddress } from "../../services/api"
import { StatusBar } from "expo-status-bar"

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

// Cores elegantes para os status
const STATUS_COLORS = {
  pending: {
    primary: "#F59E0B",
    light: "#FEF3C7",
    gradient: ["#F59E0B", "#FBBF24"],
    background: "#FFFBEB",
  },
  in_progress: {
    primary: "#06B6D4",
    light: "#CFFAFE",
    gradient: ["#06B6D4", "#0891B2"],
    background: "#F0FDFF",
  },
  completed: {
    primary: "#10B981",
    light: "#D1FAE5",
    gradient: ["#10B981", "#059669"],
    background: "#F0FDF4",
  },
}

const EnhancedDeliveryDetailScreen = () => {
  const route = useRoute()
  const navigation = useNavigation()
  const { deliveryId, deliveryData } = (route.params as { deliveryId: string; deliveryData?: Delivery }) || {}
  const [delivery, setDelivery] = useState<Delivery | null>(null)
  const [loading, setLoading] = useState(true)
  const [isMapFullscreen, setIsMapFullscreen] = useState(false)
  const [showNavigationOptions, setShowNavigationOptions] = useState(false)
  const [driverLocation, setDriverLocation] = useState<{ latitude: number; longitude: number } | null>(null)
  const [locationLoading, setLocationLoading] = useState(false)
  const { deliveries } = useMockData()

  // Animações
  const fadeAnim = useRef(new Animated.Value(0)).current
  const slideAnim = useRef(new Animated.Value(50)).current
  const scaleAnim = useRef(new Animated.Value(0.9)).current
  const modalAnim = useRef(new Animated.Value(0)).current

  // Animação para o botão deslizante
  const pan = useRef(new Animated.ValueXY()).current
  const buttonWidth = width - 32
  const iconSize = 48
  const maxSlide = buttonWidth - iconSize - 16

  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderMove: (evt, gestureState) => {
        const newX = Math.max(0, Math.min(gestureState.dx, maxSlide))
        pan.x.setValue(newX)
      },
      onPanResponderRelease: (evt, gestureState) => {
        if (gestureState.dx > maxSlide * 0.7) {
          handleStartDelivery(true)
        } else {
          Animated.spring(pan.x, {
            toValue: 0,
            useNativeDriver: false,
          }).start()
        }
      },
    }),
  ).current

  useEffect(() => {
    const loadDelivery = async () => {
      setLoading(true)
      
      // Se os dados da entrega foram passados diretamente, usar eles
      if (deliveryData) {
        setDelivery(deliveryData)
        startAnimations()
        setLoading(false)
        return
      }
      
      // Caso contrário, buscar na API (fallback)
      try {
        const allDeliveries = await api.getDeliveries()
        
        let found = allDeliveries.find(
          (d) => String(d.outId) === String(deliveryId) || String(d.id) === String(deliveryId),
        )
        
        if (found) {
          // Se não houver coordenadas válidas, geocodifica o endereço
          let coords = found.coordinates;
          if (
            (!coords || isNaN(coords.latitude) || isNaN(coords.longitude)) &&
            found.street && found.streetNumber && found.city
          ) {
            const coordsResult = await getCoordinatesFromAddress({
              address: found.street || '',
              addressNumber: found.streetNumber || '',
              neighborhood: found.neighborhood || '',
              city: found.city || '',
              state: found.state || ''
            });
            if (coordsResult) {
              found = { ...found, coordinates: coordsResult, lat: coordsResult.latitude, lng: coordsResult.longitude };
            }
          }
          setDelivery(found)
          startAnimations()
          return
        }

        const mockDelivery = deliveries.find((d) => d.id === deliveryId)
        if (mockDelivery) {
          const convertedDelivery: Delivery = {
            id: mockDelivery.id,
            outId: Number.parseInt(mockDelivery.id),
            outDate: new Date().toISOString(),
            customerId: Number.parseInt(mockDelivery.id),
            customerName: mockDelivery.client,
            street: mockDelivery.address.split(",")[0] || "",
            streetNumber: mockDelivery.address.split(",")[1] || "",
            neighborhood: mockDelivery.address.split(",")[2] || "",
            complement: "",
            zipCode: mockDelivery.address.split(",")[3] || "",
            city: mockDelivery.address.split(",")[4] || "",
            state: mockDelivery.address.split(",")[5] || "",
            customerPhone: "+55 91 99999-9999",
            lat: mockDelivery.coordinates.latitude,
            lng: mockDelivery.coordinates.longitude,
            latFrom: null,
            lngFrom: null,
            deliverySeq: Number.parseInt(mockDelivery.id),
            status: mockDelivery.status as "in_progress" | "pending" | "delivered" | "failed",
            coordinates: mockDelivery.coordinates,
            notes: mockDelivery.notes || "",
            photos: mockDelivery.photos || [],
            signature: mockDelivery.signature || "",
          }
          setDelivery(convertedDelivery)
          startAnimations()
        } else {
          Alert.alert("Erro", "Entrega não encontrada")
          navigation.goBack()
        }
      } catch (error) {
        Alert.alert("Erro", "Entrega não encontrada")
        navigation.goBack()
      } finally {
        setLoading(false)
      }
    }

    loadDelivery()
  }, [deliveryId, deliveryData, deliveries, navigation])

  // Animação do modal
  useEffect(() => {
    if (showNavigationOptions) {
      Animated.timing(modalAnim, {
        toValue: 1,
        duration: 300,
        useNativeDriver: true,
      }).start()
    } else {
      Animated.timing(modalAnim, {
        toValue: 0,
        duration: 200,
        useNativeDriver: true,
      }).start()
    }
  }, [showNavigationOptions])

  const startAnimations = () => {
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 800,
        useNativeDriver: true,
      }),
      Animated.timing(slideAnim, {
        toValue: 0,
        duration: 600,
        useNativeDriver: true,
      }),
      Animated.spring(scaleAnim, {
        toValue: 1,
        tension: 50,
        friction: 7,
        useNativeDriver: true,
      }),
    ]).start()
  }

  // Função para obter a localização atual do motorista
  const getDriverCurrentLocation = async (): Promise<{ latitude: number; longitude: number } | null> => {
    try {
      setLocationLoading(true)

      // Verificar permissões de localização
      const { status } = await Location.requestForegroundPermissionsAsync()
      if (status !== 'granted') {
        Alert.alert(
          "Permissão Necessária",
          "É necessário permitir o acesso à localização para traçar a rota até a entrega.",
          [
            { text: "Cancelar", style: "cancel" },
            { text: "Configurações", onPress: () => Linking.openSettings() }
          ]
        )
        return null
      }

      // Verificar se o serviço de localização está ativo
      const isLocationEnabled = await Location.hasServicesEnabledAsync()
      if (!isLocationEnabled) {
        Alert.alert(
          "Localização Desativada",
          "Ative o serviço de localização para traçar a rota até a entrega.",
          [
            { text: "Cancelar", style: "cancel" },
            { text: "Configurações", onPress: () => Linking.openSettings() }
          ]
        )
        return null
      }

      // Obter localização atual com alta precisão
      const location = await Location.getCurrentPositionAsync({
        accuracy: Location.Accuracy.High,
      })

      const currentLocation = {
        latitude: location.coords.latitude,
        longitude: location.coords.longitude,
      }

      setDriverLocation(currentLocation)
      return currentLocation

    } catch (error) {
      Alert.alert(
        "Erro de Localização",
        "Não foi possível obter sua localização atual. Verifique se o GPS está ativo.",
        [{ text: "OK" }]
      )
      return null
    } finally {
      setLocationLoading(false)
    }
  }

  const handleStartDelivery = async (openMapFullscreen = false) => {
    try {
      await updateDeliveryStatus(deliveryId, "in_progress")
      setDelivery((prev) => (prev ? { ...prev, status: "in_progress" } : null))

      Animated.timing(pan.x, {
        toValue: 0,
        duration: 300,
        useNativeDriver: false,
      }).start()

      if (openMapFullscreen) {
        setIsMapFullscreen(true)
      }
    } catch (error) {
      Alert.alert("Erro", "Não foi possível iniciar a entrega")
    }
  }

  const handleCompleteDelivery = () => {
    // @ts-ignore
    navigation.navigate('CompleteDelivery', { delivery });
  }

  const openWhatsApp = (phoneNumber: string) => {
    // Limpar e formatar o número de telefone
    let cleanNumber = phoneNumber.replace(/\D/g, ''); // Remove tudo que não é dígito
    
    // Se o número não começar com código do país, adicionar +55 (Brasil)
    if (!cleanNumber.startsWith('55') && cleanNumber.length <= 11) {
      cleanNumber = '55' + cleanNumber;
    }
    
    // Garantir que o número tenha o formato correto (com +)
    if (!cleanNumber.startsWith('+')) {
      cleanNumber = '+' + cleanNumber;
    }
    
    const message = `Olá! Estou a caminho da entrega.`
    
    // URLs mais abrangentes para WhatsApp no Android
    const whatsappUrls = [
      // URLs com protocolo whatsapp:// (mais confiáveis)
      `whatsapp://send?phone=${cleanNumber}&text=${encodeURIComponent(message)}`,
      `whatsapp://send?phone=${cleanNumber.replace('+', '')}&text=${encodeURIComponent(message)}`,
      
      // URLs com https://wa.me/ (fallback web)
      `https://wa.me/${cleanNumber.replace('+', '')}?text=${encodeURIComponent(message)}`,
      `https://wa.me/${cleanNumber}?text=${encodeURIComponent(message)}`,
      
      // URLs alternativas para Android
      `intent://send/${cleanNumber.replace('+', '')}#Intent;scheme=smsto;package=com.whatsapp;S.sms_body=${encodeURIComponent(message)};end`,
      `intent://send/${cleanNumber}#Intent;scheme=smsto;package=com.whatsapp;S.sms_body=${encodeURIComponent(message)};end`,
      
      // URLs com formato mais simples
      `whatsapp://send?phone=${cleanNumber.replace('+', '')}`,
      `whatsapp://send?phone=${cleanNumber}`,
    ];
    

    // Função para tentar abrir WhatsApp com timeout
    const tryOpenWhatsApp = async (urlIndex: number = 0): Promise<void> => {
      if (urlIndex >= whatsappUrls.length) {
        throw new Error('Nenhuma URL do WhatsApp funcionou');
      }
      
      const url = whatsappUrls[urlIndex];
      
      try {
        const supported = await Linking.canOpenURL(url);
        if (supported) {
          await Linking.openURL(url);
          return;
        } else {
          // Tentar próxima URL
          return tryOpenWhatsApp(urlIndex + 1);
        }
      } catch (err: any) {
        // Tentar próxima URL
        return tryOpenWhatsApp(urlIndex + 1);
      }
    };

    // Iniciar tentativas com timeout
    Promise.race([
      tryOpenWhatsApp(),
      new Promise((_, reject) => 
        setTimeout(() => reject(new Error('Timeout')), 5000)
      )
    ]).catch((err) => {
      
      // Tentar abrir na Play Store se WhatsApp não estiver instalado
      const playStoreUrl = `https://play.google.com/store/apps/details?id=com.whatsapp`;
      Linking.openURL(playStoreUrl).catch(() => {
        Alert.alert(
          "WhatsApp não encontrado", 
          "O WhatsApp não está instalado. Deseja instalar o aplicativo?",
          [
            { text: "Cancelar", style: "cancel" },
            { text: "Instalar", onPress: () => Linking.openURL(playStoreUrl) }
          ]
        );
      });
    });
  }

  const makePhoneCall = (phoneNumber: string) => {
    // Limpar e formatar o número de telefone
    let cleanNumber = phoneNumber.replace(/\D/g, ''); // Remove tudo que não é dígito
    
    // Se o número não começar com código do país, adicionar +55 (Brasil)
    if (!cleanNumber.startsWith('55') && cleanNumber.length <= 11) {
      cleanNumber = '55' + cleanNumber;
    }
    
    // Garantir que o número tenha o formato correto (com +)
    if (!cleanNumber.startsWith('+')) {
      cleanNumber = '+' + cleanNumber;
    }
    
    // Múltiplas URLs para tentar
    const phoneUrls = [
      Platform.OS === "ios" ? `telprompt:${cleanNumber}` : `tel:${cleanNumber}`,
      `tel:${cleanNumber}`,
      `tel:${cleanNumber.replace('+', '')}`,
      `telprompt:${cleanNumber}`,
      `telprompt:${cleanNumber.replace('+', '')}`
    ];
    

    // Função para tentar fazer chamada
    const tryMakeCall = (urlIndex: number = 0): Promise<void> => {
      if (urlIndex >= phoneUrls.length) {
        throw new Error('Nenhuma URL de chamada funcionou');
      }
      
      const url = phoneUrls[urlIndex];
      
      return Linking.canOpenURL(url)
        .then((supported) => {
          if (supported) {
            return Linking.openURL(url);
          } else {
            // Tentar próxima URL
            return tryMakeCall(urlIndex + 1);
          }
        })
        .catch((err: any) => {
          // Tentar próxima URL
          return tryMakeCall(urlIndex + 1);
        });
    };

    // Iniciar tentativas
    tryMakeCall()
      .catch((err) => {
        Alert.alert("Erro", "Não foi possível fazer a chamada. Verifique se o dispositivo suporta chamadas.");
      });
  }

  const openNavigationApp = async (appType: string) => {
    setShowNavigationOptions(false)

    if (!delivery) return

    // Obter localização atual do motorista
    const currentLocation = await getDriverCurrentLocation()
    if (!currentLocation) {
    }

    // Construir endereço completo
    const address = `${delivery.street}, ${delivery.streetNumber}, ${delivery.neighborhood}, ${delivery.city}, ${delivery.state}`
    const encodedAddress = encodeURIComponent(address)
    
    // Obter coordenadas de destino
    const destinationLat = delivery.lat || delivery.coordinates?.latitude || -1.4624
    const destinationLng = delivery.lng || delivery.coordinates?.longitude || -48.4787
    
    // Usar localização atual do motorista ou coordenadas padrão
    const originLat = currentLocation?.latitude || -1.4624
    const originLng = currentLocation?.longitude || -48.4787
    
    let urls: string[] = []

    switch (appType) {
      case "google":
        urls = [
          // URLs com origem e destino (rota completa)
          `https://www.google.com/maps/dir/${originLat},${originLng}/${encodedAddress}`,
          `https://www.google.com/maps/dir/${originLat},${originLng}/${destinationLat},${destinationLng}`,
          // URLs com apenas destino (fallback)
          `https://www.google.com/maps/dir/?api=1&destination=${encodedAddress}`,
          `https://www.google.com/maps/dir/?api=1&destination=${destinationLat},${destinationLng}`,
          `https://maps.google.com/maps?daddr=${encodedAddress}`,
          `https://maps.google.com/maps?daddr=${destinationLat},${destinationLng}`,
          `geo:${destinationLat},${destinationLng}?q=${encodedAddress}`,
          `geo:0,0?q=${encodedAddress}`,
        ]
        break
      case "waze":
        urls = [
          // URLs com protocolo waze:// (mais confiáveis)
          `waze://?q=${encodedAddress}&navigate=yes`,
          `waze://?ll=${destinationLat},${destinationLng}&navigate=yes`,
          `waze://?q=${encodedAddress}`,
          `waze://?ll=${destinationLat},${destinationLng}`,
          
          // URLs com https://waze.com/ (fallback web)
          `https://waze.com/ul?q=${encodedAddress}&navigate=yes`,
          `https://waze.com/ul?ll=${destinationLat},${destinationLng}&navigate=yes`,
          `https://waze.com/ul?q=${encodedAddress}`,
          `https://waze.com/ul?ll=${destinationLat},${destinationLng}`,
          
          // URLs com intent:// para Android
          `intent://waze.com/ul?q=${encodedAddress}&navigate=yes#Intent;scheme=https;package=com.waze;end`,
          `intent://waze.com/ul?ll=${destinationLat},${destinationLng}&navigate=yes#Intent;scheme=https;package=com.waze;end`,
          
          // URLs alternativas
          `https://www.waze.com/ul?q=${encodedAddress}&navigate=yes`,
          `https://www.waze.com/ul?ll=${destinationLat},${destinationLng}&navigate=yes`,
        ]
        break
      case "apple":
        urls = [
          `http://maps.apple.com/?daddr=${encodedAddress}`,
          `http://maps.apple.com/?daddr=${destinationLat},${destinationLng}`,
          `maps://?daddr=${encodedAddress}`,
          `maps://?daddr=${destinationLat},${destinationLng}`,
        ]
        break
      default:
        urls = [
          `https://www.google.com/maps/dir/?api=1&destination=${encodedAddress}`,
          `https://www.google.com/maps/dir/?api=1&destination=${destinationLat},${destinationLng}`,
        ]
    }


    // Função para tentar abrir URL com timeout
    const tryOpenURL = async (urlIndex: number = 0): Promise<void> => {
      if (urlIndex >= urls.length) {
        throw new Error('Nenhum aplicativo de navegação encontrado');
      }
      
      const url = urls[urlIndex];
      
      try {
        const supported = await Linking.canOpenURL(url);
        if (supported) {
          await Linking.openURL(url);
          return;
        } else {
          // Tentar próxima URL
          return tryOpenURL(urlIndex + 1);
        }
      } catch (err: any) {
        // Tentar próxima URL
        return tryOpenURL(urlIndex + 1);
      }
    };

    // Iniciar tentativas com timeout
    Promise.race([
      tryOpenURL(),
      new Promise((_, reject) => 
        setTimeout(() => reject(new Error('Timeout')), 5000)
      )
    ]).catch((err) => {
      
      // Tentar abrir na Play Store se o app não estiver instalado
      let playStoreUrl = '';
      if (appType === 'waze') {
        playStoreUrl = 'https://play.google.com/store/apps/details?id=com.waze';
      } else if (appType === 'google') {
        playStoreUrl = 'https://play.google.com/store/apps/details?id=com.google.android.apps.maps';
      }
      
      if (playStoreUrl) {
        Linking.openURL(playStoreUrl).catch(() => {
          Alert.alert(
            "Aplicativo não encontrado", 
            `O ${appType === 'waze' ? 'Waze' : 'Google Maps'} não está instalado. Deseja instalar o aplicativo?`,
            [
              { text: "Cancelar", style: "cancel" },
              { text: "Instalar", onPress: () => Linking.openURL(playStoreUrl) }
            ]
          );
        });
      } else {
        Alert.alert("Erro", "Não foi possível abrir o aplicativo de navegação");
      }
    });
  }

  const getStatusInfo = (status: string) => {
    switch (status) {
      case "delivered":
        return {
          text: "Entregue",
          colors: STATUS_COLORS.completed,
          icon: "checkmark-circle",
        }
      case "in_progress":
        return {
          text: "Em Trânsito",
          colors: STATUS_COLORS.in_progress,
          icon: "car-sport",
        }
      case "pending":
        return {
          text: "Pendente",
          colors: STATUS_COLORS.pending,
          icon: "time",
        }
      default:
        return {
          text: "Pendente",
          colors: STATUS_COLORS.pending,
          icon: "time",
        }
    }
  }

  const formatOrderId = () => {
    if (!delivery || !delivery.id) {
      return "ORD-000000000"
    }
    const idString = String(delivery.id)
    return `ORD-${idString.padStart(9, "0")}`
  }

  if (loading) {
    return (
      <SafeAreaView style={styles.container}>
        <StatusBar style="light" backgroundColor={COLORS.primary} />
        <LinearGradient colors={[COLORS.primary, "#3B82F6"]} style={styles.loadingContainer}>
          <ActivityIndicator size="large" color="white" />
          <Text style={styles.loadingText}>Carregando detalhes...</Text>
        </LinearGradient>
      </SafeAreaView>
    )
  }

  if (!delivery) {
    return (
      <SafeAreaView style={styles.container}>
        <StatusBar style="light" backgroundColor={COLORS.primary} />
        <View style={styles.errorContainer}>
          <Ionicons name="alert-circle" size={64} color={COLORS.danger} />
          <Text style={styles.errorText}>Entrega não encontrada</Text>
        </View>
      </SafeAreaView>
    )
  }

  const statusInfo = getStatusInfo(delivery.status)

  return (
    <>
      {/* StatusBar Global - sempre visível */}
      <StatusBar 
        style="light" 
        backgroundColor={COLORS.primary}
        translucent={false}
      />
      
      <View style={styles.container}>
        {/* Header Compacto */}
        <LinearGradient colors={[COLORS.primary, "#3B82F6"]} style={styles.headerGradient}>
          <SafeAreaView>
            <Animated.View
              style={[
                styles.header,
                {
                  opacity: fadeAnim,
                  transform: [{ translateY: slideAnim }],
                },
              ]}
            >
              <TouchableOpacity style={styles.headerButton} onPress={() => navigation.goBack()}>
                <Ionicons name="arrow-back" size={22} color="white" />
              </TouchableOpacity>

              <View style={styles.headerCenter}>
                <Text style={styles.headerTitle}>Detalhes da Entrega</Text>
                <Text style={styles.headerSubtitle}>{formatOrderId()}</Text>
              </View>

              <TouchableOpacity style={styles.headerButton} onPress={() => setIsMapFullscreen(true)}>
                <Ionicons name="map" size={22} color="white" />
              </TouchableOpacity>
            </Animated.View>
          </SafeAreaView>
        </LinearGradient>

        {/* Status Hero Card Compacto */}
        <Animated.View
          style={[
            styles.heroCard,
            {
              opacity: fadeAnim,
              transform: [{ scale: scaleAnim }],
            },
          ]}
        >
          <LinearGradient
            colors={statusInfo.colors.gradient as any}
            style={styles.heroCardGradient}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}
          >
            <View style={styles.heroCardContent}>
              <View style={styles.heroCardIcon}>
                <Ionicons name={statusInfo.icon as any} size={24} color="white" />
              </View>
              <View style={styles.heroCardInfo}>
                <Text style={styles.heroCardStatus}>{statusInfo.text}</Text>
                <Text style={styles.heroCardCustomer}>{delivery.customerName}</Text>
              </View>
              <View style={styles.heroCardSequence}>
                <Text style={styles.sequenceNumber}>{delivery.deliverySeq}</Text>
              </View>
            </View>
          </LinearGradient>
        </Animated.View>

        <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
          {/* Informações do Cliente Compacto */}
          <Animated.View
            style={[
              styles.infoCard,
              {
                opacity: fadeAnim,
                transform: [{ translateY: slideAnim }],
              },
            ]}
          >
            <View style={styles.cardHeader}>
              <LinearGradient
                colors={["#6366F1", "#4F46E5"]}
                style={styles.cardIconContainer}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <Ionicons name="person" size={16} color="white" />
              </LinearGradient>
              <Text style={styles.cardTitle}>Cliente</Text>
            </View>

            <View style={styles.clientInfo}>
              <Text style={styles.clientName}>{delivery.customerName}</Text>
              <TouchableOpacity style={styles.phoneContainer} onPress={() => makePhoneCall(delivery.customerPhone)}>
                <Ionicons name="call" size={14} color={STATUS_COLORS.in_progress.primary} />
                <Text style={styles.clientPhone}>{delivery.customerPhone}</Text>
              </TouchableOpacity>
            </View>
          </Animated.View>

          {/* Endereço Compacto */}
          <Animated.View
            style={[
              styles.infoCard,
              {
                opacity: fadeAnim,
                transform: [{ translateY: slideAnim }],
              },
            ]}
          >
            <View style={styles.cardHeader}>
              <LinearGradient
                colors={STATUS_COLORS.pending.gradient as any}
                style={styles.cardIconContainer}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <Ionicons name="location" size={16} color="white" />
              </LinearGradient>
              <Text style={styles.cardTitle}>Endereço</Text>
            </View>

            <View style={styles.addressContainer}>
              <Text style={styles.addressMain}>
                {delivery.street}, {delivery.streetNumber}
              </Text>
              <Text style={styles.addressSecondary}>
                {delivery.neighborhood}, {delivery.city}
              </Text>
              <Text style={styles.addressZip}>CEP: {delivery.zipCode}</Text>
            </View>
          </Animated.View>

          {/* Mapa Compacto */}
          <Animated.View
            style={[
              styles.mapCard,
              {
                opacity: fadeAnim,
                transform: [{ translateY: slideAnim }],
              },
            ]}
          >
            <View style={styles.cardHeader}>
              <LinearGradient
                colors={STATUS_COLORS.completed.gradient as any}
                style={styles.cardIconContainer}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <Ionicons name="map" size={16} color="white" />
              </LinearGradient>
              <View style={styles.cardTitleContainer}>
                <Text style={styles.cardTitle}>Localização</Text>
                {driverLocation && (
                  <View style={styles.locationIndicator}>
                    <Ionicons name="location" size={12} color={STATUS_COLORS.completed.primary} />
                    <Text style={styles.locationText}>GPS Ativo</Text>
                  </View>
                )}
              </View>
              <TouchableOpacity style={styles.expandMapButton} onPress={() => setIsMapFullscreen(true)}>
                <Ionicons name="expand" size={14} color={COLORS.primary} />
              </TouchableOpacity>
            </View>

            <View style={styles.mapContainer}>
              <DeliveryMap 
                deliveries={[delivery]} 
                showRoute={true} 
                centerOnUser={false} 
                showDeliveryPin={true}
                driverLocation={driverLocation}
              />
            </View>
          </Animated.View>

          {/* Ações Rápidas Compactas */}
          <Animated.View
            style={[
              styles.actionsCard,
              {
                opacity: fadeAnim,
                transform: [{ translateY: slideAnim }],
              },
            ]}
          >
            <Text style={styles.actionsTitle}>Ações Rápidas</Text>
            <View style={styles.actionButtons}>
              <TouchableOpacity 
                style={styles.actionButton} 
                onPress={async () => {
                  if (!driverLocation) {
                    await getDriverCurrentLocation();
                  }
                  setShowNavigationOptions(true);
                }}
              >
                <LinearGradient
                  colors={["#3B82F6", "#2563EB"]}
                  style={styles.actionButtonGradient}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                >
                  <Ionicons name="navigate" size={20} color="white" />
                  <Text style={styles.actionButtonText}>
                    {locationLoading ? "..." : driverLocation ? "Navegar" : "Localizar"}
                  </Text>
                </LinearGradient>
              </TouchableOpacity>

              <TouchableOpacity style={styles.actionButton} onPress={() => openWhatsApp(delivery.customerPhone)}>
                <LinearGradient
                  colors={["#10B981", "#059669"]}
                  style={styles.actionButtonGradient}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                >
                  <Ionicons name="logo-whatsapp" size={20} color="white" />
                  <Text style={styles.actionButtonText}>WhatsApp</Text>
                </LinearGradient>
              </TouchableOpacity>

              <TouchableOpacity style={styles.actionButton} onPress={() => makePhoneCall(delivery.customerPhone)}>
                <LinearGradient
                  colors={["#F59E0B", "#FBBF24"]}
                  style={styles.actionButtonGradient}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                >
                  <Ionicons name="call" size={20} color="white" />
                  <Text style={styles.actionButtonText}>Ligar</Text>
                </LinearGradient>
              </TouchableOpacity>
            </View>
          </Animated.View>

          {/* Botão Deslizante Compacto */}
          {delivery.status === "pending" && (
            <Animated.View
              style={[
                styles.slideContainer,
                {
                  opacity: fadeAnim,
                  transform: [{ translateY: slideAnim }],
                },
              ]}
            >
              <Text style={styles.slideInstructions}>Deslize para iniciar</Text>
              <View style={styles.slideButton}>
                <LinearGradient
                  colors={[statusInfo.colors.primary, statusInfo.colors.primary + "CC"]}
                  style={styles.slideTrack}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 0 }}
                >
                  <Animated.View
                    style={[
                      styles.slideIcon,
                      {
                        transform: [{ translateX: pan.x }],
                      },
                    ]}
                    {...panResponder.panHandlers}
                  >
                    <LinearGradient
                      colors={["#FF6B35", "#FF8E53"]}
                      style={styles.slideIconGradient}
                      start={{ x: 0, y: 0 }}
                      end={{ x: 1, y: 1 }}
                    >
                      <Ionicons name="play" size={24} color="white" />
                    </LinearGradient>
                  </Animated.View>
                  <Text style={styles.slideText}>Iniciar Entrega</Text>
                </LinearGradient>
              </View>
            </Animated.View>
          )}

          {/* Botão de Conclusão Compacto */}
          {delivery.status === "in_progress" && (
            <Animated.View
              style={[
                styles.completeContainer,
                {
                  opacity: fadeAnim,
                  transform: [{ translateY: slideAnim }],
                },
              ]}
            >
              <TouchableOpacity style={styles.completeButton} onPress={handleCompleteDelivery}>
                <LinearGradient
                  colors={STATUS_COLORS.completed.gradient as any}
                  style={styles.completeButtonGradient}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                >
                  <Ionicons name="checkmark-circle" size={24} color="white" />
                  <Text style={styles.completeButtonText}>Realizar Entrega</Text>
                </LinearGradient>
              </TouchableOpacity>
            </Animated.View>
          )}

          <View style={{ height: 20 }} />
        </ScrollView>

        {/* Modal de Navegação com Header Customizado */}
        <Modal
          animationType="none"
          transparent={true}
          visible={showNavigationOptions}
          onRequestClose={() => setShowNavigationOptions(false)}
        >
          <View style={styles.modalContainer}>
            {/* Header fixo com cor primária */}
            <LinearGradient 
              colors={[COLORS.primary, "#3B82F6"]} 
              style={styles.modalHeader}
            >
              <SafeAreaView>
                <View style={styles.modalHeaderContent}>
                  <TouchableOpacity 
                    style={styles.modalCloseButton} 
                    onPress={() => setShowNavigationOptions(false)}
                  >
                    <Ionicons name="close" size={24} color="white" />
                  </TouchableOpacity>
                  <Text style={styles.modalHeaderTitle}>Escolher Navegação</Text>
                  <View style={{ width: 40 }} />
                </View>
              </SafeAreaView>
            </LinearGradient>

            {/* Conteúdo do modal */}
            <View style={styles.modalOverlay}>
              <TouchableOpacity
                style={styles.modalBackdrop}
                activeOpacity={1}
                onPress={() => setShowNavigationOptions(false)}
              />
              <Animated.View
                style={[
                  styles.modalContent,
                  {
                    opacity: modalAnim,
                    transform: [
                      {
                        translateY: modalAnim.interpolate({
                          inputRange: [0, 1],
                          outputRange: [300, 0],
                        }),
                      },
                    ],
                  },
                ]}
              >
                <TouchableOpacity style={styles.navigationOption} onPress={() => openNavigationApp("google")}>
                  <View style={styles.navigationIconContainer}>
                    <Image 
                      source={require("../../assets/images/icons/google-maps.png")} 
                      style={styles.navigationIcon}
                      resizeMode="contain"
                    />
                  </View>
                  <View style={styles.navigationInfo}>
                    <Text style={styles.navigationTitle}>Google Maps</Text>
                    <Text style={styles.navigationSubtitle}>Navegação com trânsito em tempo real</Text>
                  </View>
                  <Ionicons name="chevron-forward" size={20} color={COLORS.textLight} />
                </TouchableOpacity>

                <TouchableOpacity style={styles.navigationOption} onPress={() => openNavigationApp("waze")}>
                  <View style={styles.navigationIconContainer}>
                    <Image 
                      source={require("../../assets/images/icons/waze.png")} 
                      style={styles.navigationIcon}
                      resizeMode="contain"
                    />
                  </View>
                  <View style={styles.navigationInfo}>
                    <Text style={styles.navigationTitle}>Waze</Text>
                    <Text style={styles.navigationSubtitle}>Rotas otimizadas pela comunidade</Text>
                  </View>
                  <Ionicons name="chevron-forward" size={20} color={COLORS.textLight} />
                </TouchableOpacity>

                {Platform.OS === "ios" && (
                  <TouchableOpacity style={styles.navigationOption} onPress={() => openNavigationApp("apple")}>
                    <View style={styles.navigationIconContainer}>
                      <Ionicons name="location" size={24} color="#007AFF" />
                    </View>
                    <View style={styles.navigationInfo}>
                      <Text style={styles.navigationTitle}>Apple Maps</Text>
                      <Text style={styles.navigationSubtitle}>Navegação integrada do iOS</Text>
                    </View>
                    <Ionicons name="chevron-forward" size={20} color={COLORS.textLight} />
                  </TouchableOpacity>
                )}
              </Animated.View>
            </View>
          </View>
        </Modal>

        {/* Modal de Mapa Fullscreen */}
        <Modal
          animationType="slide"
          presentationStyle="fullScreen"
          visible={isMapFullscreen}
          onRequestClose={() => setIsMapFullscreen(false)}
        >
          <View style={styles.fullscreenContainer}>
            <LinearGradient colors={[COLORS.primary, "#3B82F6"]} style={styles.fullscreenHeader}>
              <SafeAreaView>
                <View style={styles.fullscreenHeaderContent}>
                  <TouchableOpacity style={styles.headerButton} onPress={() => setIsMapFullscreen(false)}>
                    <Ionicons name="close" size={24} color="white" />
                  </TouchableOpacity>
                  <Text style={styles.fullscreenTitle}>Navegação</Text>
                  <View style={{ width: 40 }} />
                </View>
              </SafeAreaView>
            </LinearGradient>

            <DeliveryMap 
              deliveries={[delivery]} 
              showRoute={true} 
              centerOnUser={true} 
              showDeliveryPin={true}
              driverLocation={driverLocation}
            />
          </View>
        </Modal>
      </View>
    </>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  headerGradient: {
    paddingBottom: 16,
  },
  header: {
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 20,
    paddingTop: Platform.OS === "ios" ? 8 : 50,
  },
  headerButton: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: "rgba(255, 255, 255, 0.2)",
    alignItems: "center",
    justifyContent: "center",
  },
  headerCenter: {
    flex: 1,
    alignItems: "center",
  },
  headerTitle: {
    fontSize: 16,
    fontWeight: "bold",
    color: "white",
  },
  headerSubtitle: {
    fontSize: 11,
    color: "rgba(255, 255, 255, 0.8)",
    marginTop: 2,
  },
  heroCard: {
    marginHorizontal: 16,
    marginTop: -8,
    borderRadius: 16,
    overflow: "hidden",
    ...SHADOWS.medium,
  },
  heroCardGradient: {
    padding: 16,
  },
  heroCardContent: {
    flexDirection: "row",
    alignItems: "center",
  },
  heroCardIcon: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: "rgba(255, 255, 255, 0.2)",
    alignItems: "center",
    justifyContent: "center",
    marginRight: 12,
  },
  heroCardInfo: {
    flex: 1,
  },
  heroCardStatus: {
    fontSize: 18,
    fontWeight: "bold",
    color: "white",
    marginBottom: 2,
  },
  heroCardCustomer: {
    fontSize: 13,
    color: "rgba(255, 255, 255, 0.9)",
  },
  heroCardSequence: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: "rgba(255, 255, 255, 0.2)",
    alignItems: "center",
    justifyContent: "center",
  },
  sequenceNumber: {
    fontSize: 14,
    fontWeight: "bold",
    color: "white",
  },
  content: {
    flex: 1,
    marginTop: 16,
  },
  infoCard: {
    backgroundColor: COLORS.card,
    borderRadius: 16,
    padding: 12,
    marginHorizontal: 16,
    marginBottom: 8,
    ...SHADOWS.small,
  },
  cardHeader: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 12,
  },
  cardIconContainer: {
    width: 28,
    height: 28,
    borderRadius: 14,
    alignItems: "center",
    justifyContent: "center",
    marginRight: 10,
  },
  cardTitle: {
    fontSize: 14,
    fontWeight: "bold",
    color: COLORS.text,
    flex: 1,
  },
  cardTitleContainer: {
    flex: 1,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
  },
  locationIndicator: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: STATUS_COLORS.completed.light,
    paddingHorizontal: 8,
    paddingVertical: 2,
    borderRadius: 8,
  },
  locationText: {
    fontSize: 10,
    color: STATUS_COLORS.completed.primary,
    fontWeight: "600",
    marginLeft: 4,
  },
  clientInfo: {
    paddingLeft: 38,
  },
  clientName: {
    fontSize: 16,
    fontWeight: "bold",
    color: COLORS.text,
    marginBottom: 6,
  },
  phoneContainer: {
    flexDirection: "row",
    alignItems: "center",
  },
  clientPhone: {
    fontSize: 14,
    color: STATUS_COLORS.in_progress.primary,
    marginLeft: 6,
    fontWeight: "500",
  },
  addressContainer: {
    paddingLeft: 38,
  },
  addressMain: {
    fontSize: 15,
    fontWeight: "600",
    color: COLORS.text,
    marginBottom: 3,
  },
  addressSecondary: {
    fontSize: 14,
    color: COLORS.textLight,
    marginBottom: 3,
  },
  addressZip: {
    fontSize: 13,
    color: COLORS.textLight,
  },
  mapCard: {
    backgroundColor: COLORS.card,
    borderRadius: 16,
    padding: 12,
    marginHorizontal: 16,
    marginBottom: 8,
    ...SHADOWS.small,
  },
  expandMapButton: {
    width: 28,
    height: 28,
    borderRadius: 14,
    backgroundColor: COLORS.background,
    alignItems: "center",
    justifyContent: "center",
  },
  mapContainer: {
    height: 140,
    borderRadius: 12,
    overflow: "hidden",
  },
  actionsCard: {
    backgroundColor: COLORS.card,
    borderRadius: 16,
    padding: 12,
    marginHorizontal: 16,
    marginBottom: 8,
    ...SHADOWS.small,
  },
  actionsTitle: {
    fontSize: 14,
    fontWeight: "bold",
    color: COLORS.text,
    marginBottom: 12,
    textAlign: "center",
  },
  actionButtons: {
    flexDirection: "row",
    justifyContent: "space-between",
  },
  actionButton: {
    flex: 1,
    marginHorizontal: 3,
    borderRadius: 12,
    overflow: "hidden",
  },
  actionButtonGradient: {
    paddingVertical: 10,
    paddingHorizontal: 8,
    alignItems: "center",
    justifyContent: "center",
  },
  actionButtonText: {
    color: "white",
    fontSize: 10,
    fontWeight: "600",
    marginTop: 3,
  },
  slideContainer: {
    marginHorizontal: 16,
    marginBottom: 12,
  },
  slideInstructions: {
    fontSize: 13,
    color: COLORS.textLight,
    textAlign: "center",
    marginBottom: 10,
  },
  slideButton: {
    height: 52,
    borderRadius: 26,
    overflow: "hidden",
  },
  slideTrack: {
    flex: 1,
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 6,
    position: "relative",
  },
  slideIcon: {
    width: 42,
    height: 42,
    borderRadius: 21,
    position: "absolute",
    left: 5,
    top: 5,
    overflow: "hidden",
  },
  slideIconGradient: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  slideText: {
    flex: 1,
    textAlign: "center",
    fontSize: 15,
    fontWeight: "bold",
    color: "white",
    marginLeft: 42,
  },
  completeContainer: {
    marginHorizontal: 16,
    marginBottom: 12,
  },
  completeButton: {
    borderRadius: 16,
    overflow: "hidden",
  },
  completeButtonGradient: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 14,
  },
  completeButtonText: {
    fontSize: 15,
    fontWeight: "bold",
    color: "white",
    marginLeft: 10,
  },
  // Novos estilos para o modal customizado
  modalContainer: {
    flex: 1,
    backgroundColor: "transparent",
  },
  modalHeader: {
    paddingBottom: 16,
  },
  modalHeaderContent: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 20,
    paddingTop: 8,
  },
  modalCloseButton: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: "rgba(255, 255, 255, 0.2)",
    alignItems: "center",
    justifyContent: "center",
  },
  modalHeaderTitle: {
    fontSize: 16,
    fontWeight: "bold",
    color: "white",
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: "rgba(0, 0, 0, 0.5)",
    justifyContent: "flex-end",
  },
  modalBackdrop: {
    flex: 1,
  },
  modalContent: {
    backgroundColor: COLORS.card,
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    padding: 20,
    paddingBottom: 30,
  },
  navigationOption: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border,
  },
  navigationIconContainer: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: COLORS.background,
    alignItems: "center",
    justifyContent: "center",
    marginRight: 12,
  },
  navigationIcon: {
    width: 24,
    height: 24,
  },
  navigationInfo: {
    flex: 1,
  },
  navigationTitle: {
    fontSize: 14,
    fontWeight: "600",
    color: COLORS.text,
    marginBottom: 2,
  },
  navigationSubtitle: {
    fontSize: 12,
    color: COLORS.textLight,
  },
  fullscreenContainer: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  fullscreenHeader: {
    paddingBottom: 12,
  },
  fullscreenHeaderContent: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 20,
    paddingTop: 8,
  },
  fullscreenTitle: {
    fontSize: 18,
    fontWeight: "bold",
    color: "white",
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  loadingText: {
    fontSize: 15,
    color: "white",
    marginTop: 12,
    fontWeight: "600",
  },
  errorContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  errorText: {
    fontSize: 15,
    color: COLORS.danger,
    marginTop: 12,
    fontWeight: "600",
  },
})

export default EnhancedDeliveryDetailScreen