"use client"

import { useState, useRef, useContext, useEffect } from "react"
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Image,
  TextInput,
  Alert,
  ActivityIndicator,
  Dimensions,
  Animated,
  Modal,
  Linking,
  KeyboardAvoidingView,
  Platform,
} from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { Ionicons } from "@expo/vector-icons"
import * as ImagePicker from "expo-image-picker"
import SignatureScreen from "react-native-signature-canvas"
import { LinearGradient } from "expo-linear-gradient"
import { COLORS, SHADOWS } from "../../constants/theme"
import { useSync } from "../../contexts/SyncContext"
import { useOfflineMode } from "../../contexts/OfflineModeContext"
import { api } from "../../services/api"
import { saveDeliveryInvoice } from "../../services/database"
import { navigationRef } from "../../navigation"
import { useMobileSignal } from "../../hooks/useMobileSignal"
import { useOffline } from "../../contexts/OfflineContext"
import { MobileSignalIndicator } from "../../components/MobileSignalIndicator"
import type { NativeStackNavigationProp } from "@react-navigation/native-stack"
import type { RouteProp } from "@react-navigation/native"
import type { Delivery } from "../../types"
import { AuthContext } from "../../contexts/AuthContext"
import { CameraView, useCameraPermissions } from "expo-camera"
import { convertCoordinate } from "../../config/env"

import * as FileSystem from 'expo-file-system/legacy'
import { StatusBar } from "expo-status-bar"

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

type RootStackParamList = {
  CompleteDelivery: { delivery: Delivery }
  DeliveriesList: undefined
}

type CompleteDeliveryScreenRouteProp = RouteProp<RootStackParamList, "CompleteDelivery">
type CompleteDeliveryScreenNavigationProp = NativeStackNavigationProp<RootStackParamList, "CompleteDelivery">

interface CompleteDeliveryScreenProps {
  route: CompleteDeliveryScreenRouteProp
  navigation: CompleteDeliveryScreenNavigationProp
}

// Cores elegantes para os status
const STATUS_COLORS = {
  completed: {
    primary: "#10B981",
    light: "#D1FAE5",
    gradient: ["#10B981", "#059669"] as const,
    background: "#F0FDF4",
  },
  absent: {
    primary: "#F59E0B",
    light: "#FEF3C7",
    gradient: ["#F59E0B", "#D97706"] as const,
    background: "#FFFBEB",
  },
  refused: {
    primary: "#EF4444",
    light: "#FECACA",
    gradient: ["#EF4444", "#DC2626"] as const,
    background: "#FEF2F2",
  },
}

const CompleteDeliveryScreen = ({ route, navigation }: CompleteDeliveryScreenProps) => {
  // HOOKS DEVEM FICAR NO TOPO, ANTES DE QUALQUER RETURN
  const { delivery } = route.params
  const { syncNow } = useSync()
  const { user } = useContext(AuthContext)
  const { signalInfo } = useMobileSignal()
  const { isOfflineMode, saveOfflineData, addToSyncQueue } = useOffline()
  const { completeDeliveryOffline, isOfflineMode: isOfflineModeNew } = useOfflineMode()

  const [photos, setPhotos] = useState<string[]>([])
  const [signature, setSignature] = useState<string | null>(null)
  const [status, setStatus] = useState<"completed" | "absent" | "refused">("completed")
  const [notes, setNotes] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [showCamera, setShowCamera] = useState(false)
  const [showSignature, setShowSignature] = useState(false)
  const [showPhotoOptions, setShowPhotoOptions] = useState(false)
  const [receiverName, setReceiverName] = useState("")
  const [receiverDoc, setReceiverDoc] = useState("")
  const [deliveryDate, setDeliveryDate] = useState(new Date().toISOString())
  const [broken, setBroken] = useState(false)
  const [devolution, setDevolution] = useState(false)
  const [reasonDevolution, setReasonDevolution] = useState("")
  const [customerInvoices, setCustomerInvoices] = useState<any[]>([])
  const [selectedInvoices, setSelectedInvoices] = useState<Set<string>>(new Set())
  const [isLoadingInvoices, setIsLoadingInvoices] = useState(false)
  const [currentStep, setCurrentStep] = useState<'select_invoices' | 'collect_info'>('select_invoices')
  const [currentInvoiceIndex, setCurrentInvoiceIndex] = useState(0)
  const [deliveryDataArray, setDeliveryDataArray] = useState<any[]>([])

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

  const cameraRef = useRef<any>(null)

  const [isCameraActive, setIsCameraActive] = useState(false)
  const [cameraType, setCameraType] = useState<'back' | 'front'>('back')
  const [flashMode, setFlashMode] = useState<'off' | 'on'>('off')
  const [isTakingPhoto, setIsTakingPhoto] = useState(false)
  const [cameraPermission, requestCameraPermission] = useCameraPermissions()

  // Ref para o ScrollView principal
  const scrollViewRef = useRef<ScrollView>(null)

  // Iniciar animações
  useEffect(() => {
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 800,
        useNativeDriver: true,
      }),
      Animated.timing(slideAnim, {
        toValue: 0,
        duration: 600,
        useNativeDriver: true,
      }),
    ]).start()
  }, [])

  // Carregar notas fiscais automaticamente
  useEffect(() => {
    // console.log('=== DEBUG: USEEFFECT - CARREGANDO NOTAS AUTOMATICAMENTE ===')
    // console.log('Delivery:', delivery)
    // console.log('OutId:', delivery?.outId)
    // console.log('CustomerId:', delivery?.customerId)
    
    if (delivery?.outId && delivery?.customerId) {
      loadCustomerInvoices()
    }
  }, [delivery?.outId, delivery?.customerId])

  // Sempre que avançar para a próxima nota, rolar para o topo
  useEffect(() => {
    if (currentStep === 'collect_info' && scrollViewRef.current) {
      scrollViewRef.current.scrollTo({ y: 0, animated: true })
    }
  }, [currentInvoiceIndex, currentStep])

  // Função para carregar notas fiscais do cliente
  const loadCustomerInvoices = async () => {
    try {
      setIsLoadingInvoices(true)
      
      if (!delivery.outId || !delivery.customerId) {
        Alert.alert("Erro", "Dados da entrega incompletos")
        return
      }
      
      const invoices = await api.getCustomerInvoices(delivery.outId, delivery.customerId)
      
      setCustomerInvoices(invoices)
      
    } catch (error: any) {
      Alert.alert("Erro", error?.message || "Erro ao carregar notas fiscais")
    } finally {
      setIsLoadingInvoices(false)
    }
  }

  // Função para alternar seleção de nota fiscal
  const toggleInvoiceSelection = (invoiceId: number, transactionId: number) => {
    const uniqueId = `${invoiceId}-${transactionId}`
    
    setSelectedInvoices((prev: Set<string>) => {
      const newSet = new Set(prev)
      
      if (newSet.has(uniqueId)) {
        newSet.delete(uniqueId)
      } else {
        newSet.add(uniqueId)
      }
      
      return newSet
    })
  }

  // Função para selecionar todas as notas
  const selectAllInvoices = () => {
    
    const allInvoiceIds = new Set(customerInvoices.map((invoice: any) => `${invoice.invoiceDeliveryId}-${invoice.transactionId}`))
    
    setSelectedInvoices(allInvoiceIds)
  }

  // Função para desmarcar todas as notas
  const deselectAllInvoices = () => {
    setSelectedInvoices(new Set<string>())
  }

  // Função para solicitar permissão da câmera
  const requestCameraAccess = async () => {
    try {
      const permission = await requestCameraPermission()
      if (permission.granted) {
        setIsCameraActive(true)
      } else {
        Alert.alert(
          "Permissão Necessária",
          "Para capturar fotos, é necessário permitir o acesso à câmera. Deseja abrir as configurações?",
          [
            { text: "Cancelar", style: "cancel" },
            { 
              text: "Configurações", 
              onPress: () => Linking.openSettings() 
            }
          ]
        )
      }
    } catch (error) {
      Alert.alert("Erro", "Não foi possível solicitar permissão da câmera")
    }
  }

  // Função para abrir a câmera com verificação de permissão
  const openCameraWithPermission = async () => {
    if (cameraPermission === null) {
      // Ainda carregando permissões
      return
    }

    if (cameraPermission.granted) {
      setIsCameraActive(true)
    } else if (cameraPermission.canAskAgain) {
      await requestCameraAccess()
    } else {
      // Permissão foi negada permanentemente
      Alert.alert(
        "Permissão da Câmera",
        "A permissão da câmera foi negada. Para capturar fotos, você precisa habilitar a câmera nas configurações do dispositivo.",
        [
          { text: "Cancelar", style: "cancel" },
          { 
            text: "Abrir Configurações", 
            onPress: () => Linking.openSettings() 
          }
        ]
      )
    }
  }

  if (!delivery) {
    return (
      <>
        <StatusBar style="light" backgroundColor={COLORS.primary} translucent={false} />
        <SafeAreaView style={styles.container}>
          <LinearGradient colors={[COLORS.primary, "#3B82F6"]} style={styles.notFoundContainer}>
            <Ionicons name="alert-circle" size={64} color="white" />
            <Text style={styles.notFoundText}>Entrega não encontrada</Text>
          </LinearGradient>
        </SafeAreaView>
      </>
    )
  }

  const takePhoto = async () => {
    if (!cameraRef.current) return
    setIsTakingPhoto(true)
    try {
      const result = await cameraRef.current.takePictureAsync({ quality: 0.8 })
      if (result?.uri) {
        setPhotos((prev) => [...prev, result.uri])
      }
      setIsCameraActive(false)
    } catch (error) {
      Alert.alert("Erro", "Não foi possível capturar a foto.")
    } finally {
      setIsTakingPhoto(false)
    }
  }

  const pickImage = async () => {
    setShowPhotoOptions(false)
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    })

    if (!result.canceled) {
      setPhotos([...photos, result.assets[0].uri])
    }
  }

  const handleSignature = async (sig: string) => {
    try {
      // Usar a assinatura diretamente como base64
      setSignature(sig);
      setShowSignature(false);
    } catch (error) {
      Alert.alert("Erro", "Falha ao salvar assinatura. Tente novamente.");
    }
  }

  const removePhoto = (index: number) => {
    setPhotos((prev) => prev.filter((_, i) => i !== index))
  }

  const validateForm = () => {
    if (photos.length === 0) {
      Alert.alert("Atenção", "É necessário adicionar pelo menos uma foto da entrega.")
      return false
    }
    /*if (!receiverName || !receiverDoc) {
      Alert.alert("Atenção", "Preencha o nome e o documento do recebedor.")
      return false
    }*/
    if (devolution && !reasonDevolution) {
      Alert.alert("Atenção", "Informe o motivo da devolução.")
      return false
    }
    /*if (status === "completed" && !signature) {
      Alert.alert("Atenção", "A assinatura do cliente é obrigatória para entregas concluídas.")
      return false
    }*/
    if (customerInvoices.length > 0 && selectedInvoices.size === 0) {
      Alert.alert("Atenção", "Selecione pelo menos uma nota fiscal para finalizar a entrega.")
      return false
    }
    return true
  }

  const handleSubmit = async () => {
    // Etapa 1: Seleção de notas fiscais
    if (currentStep === 'select_invoices') {
      if (selectedInvoices.size === 0) {
        Alert.alert("Atenção", "Selecione pelo menos uma nota fiscal para finalizar a entrega.")
        return
      }
      
      // Iniciar etapa de coleta de informações
      setCurrentStep('collect_info')
      setCurrentInvoiceIndex(0)
      setDeliveryDataArray([])
      return
    }
    
    // Etapa 2: Coleta de informações para cada nota
    if (currentStep === 'collect_info') {
    if (!validateForm()) return
      
      // Obter a nota fiscal atual
      const selectedInvoiceIds = Array.from(selectedInvoices)
      const currentInvoiceId = selectedInvoiceIds[currentInvoiceIndex]
      
      const currentInvoice = customerInvoices.find(inv => `${inv.invoiceDeliveryId}-${inv.transactionId}` === currentInvoiceId)
      
      if (!currentInvoice) {
        Alert.alert("Erro", "Nota fiscal não encontrada")
        return
      }
      
      // Definir variáveis no escopo correto
      let uploadedPhotoUrls: string[] = []
      let signatureUrl: string | null = null
      
      // 1. Verificar conectividade antes de fazer upload
      const NetInfo = await import('@react-native-community/netinfo');
      const netInfo = await NetInfo.default.fetch();
      
        
        // Salvar fotos localmente para upload posterior - ABORDAGEM SIMPLIFICADA
        try {
          const { photoUploadService } = await import('../../services/photoUploadService');
          
          // Função auxiliar para converter base64 em arquivo (apenas se necessário)
          const convertBase64ToFile = async (base64Data: string, filename: string): Promise<string> => {
            try {
              const documentDir = FileSystem.documentDirectory;
              if (!documentDir) {
                throw new Error('Diretório de documentos não está disponível');
              }
              
              // Criar diretório se não existir
              const photosDir = `${documentDir}delivery_photos/`;
              const dirInfo = await FileSystem.getInfoAsync(photosDir);
              if (!dirInfo.exists) {
                await FileSystem.makeDirectoryAsync(photosDir, { intermediates: true });
              }
              
              const filePath = `${photosDir}${filename}`;
              const cleanBase64 = base64Data.replace(/^data:image\/\w+;base64,/, '');
              
              await FileSystem.writeAsStringAsync(filePath, cleanBase64, {
                encoding: 'base64' as any
              });
              
              // Verificar se foi salvo
              const savedFile = await FileSystem.getInfoAsync(filePath);
              if (!savedFile.exists) {
                throw new Error('Falha ao salvar arquivo base64');
              }
              
              return filePath;
            } catch (error) {
              throw error;
            }
          };
          
          // Salvar fotos - usar caminhos originais (não copiar)
          for (let i = 0; i < photos.length; i++) {
            const photoPath = photos[i];
            
            try {
              let finalPath = photoPath;
              
              // Se for base64, converter para arquivo
              if (photoPath.startsWith('data:image/')) {
                finalPath = await convertBase64ToFile(
                  photoPath,
                  `photo_${delivery.outId}_${currentInvoice.transactionId}_${i}_${Date.now()}.jpg`
                );
              } else {
                // Verificar se o arquivo existe
                const fileInfo = await FileSystem.getInfoAsync(photoPath);
                if (!fileInfo.exists) {
                  // Continuar mesmo se não existir - pode ser um caminho válido que será verificado no upload
                }
              }
              
              // Salvar no SQLite usando o caminho (original ou convertido)
              await photoUploadService.addPhotoToUpload(
                delivery.outId.toString(),
                currentInvoice.transactionId,
                finalPath
              );
              
            } catch (photoError: any) {
              // Continuar com outras fotos mesmo se uma falhar
            }
          }
          
          // Salvar assinatura se existir
          if (signature) {
            try {
              let signaturePath = signature;
              
              // Se for base64, converter para arquivo
              if (signature.startsWith('data:image/')) {
                signaturePath = await convertBase64ToFile(
                  signature,
                  `signature_${delivery.outId}_${currentInvoice.transactionId}_${Date.now()}.png`
                );
              } else {
                // Verificar se o arquivo existe
                const fileInfo = await FileSystem.getInfoAsync(signature);
                if (!fileInfo.exists) {
                  // Continuar mesmo assim
                }
              }
              
              // Salvar no SQLite
              await photoUploadService.addPhotoToUpload(
                delivery.outId.toString(),
                currentInvoice.transactionId,
                signaturePath
              );
              
            } catch (signatureError: any) {
              // Continuar mesmo se a assinatura falhar
            }
          }
          
          // Para modo offline, usar URLs temporárias locais
          uploadedPhotoUrls = photos.map((_, index) => `local_photo_${index}_${Date.now()}`);
          if (signature) {
            signatureUrl = `local_signature_${Date.now()}`;
          }
          
        } catch (err: any) {
          // SEMPRE tentar salvar a entrega mesmo se houver erro com fotos
          // Isso garante que a entrega não seja perdida
          try {
            // Salvar entrega offline sem fotos (fallback seguro)
            await completeDeliveryOffline({
              deliveryId: delivery.id.toString(),
              status: status === 'completed' ? 'delivered' : 
                      status === 'absent' || status === 'refused' ? 'failed' : 'in_progress',
              photos: [], // Sem fotos por enquanto
              signature: signature ? "assinatura_pendente" : undefined,
              notes: notes,
              completedBy: user?.id?.toString() || "unknown",
            });
            
            // Mensagem de erro mais específica
            let errorMessage = "Falha ao salvar algumas fotos, mas a entrega foi salva. As fotos podem ser adicionadas depois.";
            
            if (err.message?.includes('SQLite not available')) {
              errorMessage = "Banco de dados não está disponível. A entrega foi salva sem fotos. Reinicie o aplicativo.";
            } else if (err.message?.includes('Table photo_uploads does not exist')) {
              errorMessage = "Estrutura do banco de dados corrompida. A entrega foi salva sem fotos. Reinicie o aplicativo.";
            } else if (err.message?.includes('SQLite não está disponível')) {
              errorMessage = "Banco de dados não inicializado. A entrega foi salva sem fotos. Reinicie o aplicativo.";
            } else if (err.message?.includes('Diretório de documentos não está disponível')) {
              errorMessage = "Não foi possível acessar o diretório de documentos. A entrega foi salva sem fotos.";
            } else if (err.message?.includes('EACCES') || err.message?.includes('permission')) {
              errorMessage = "Sem permissão para salvar arquivos. A entrega foi salva sem fotos. Verifique as permissões.";
            } else if (err.message?.includes('ENOSPC') || err.message?.includes('space')) {
              errorMessage = "Espaço em disco insuficiente. A entrega foi salva sem fotos. Libere espaço.";
            }
            
            Alert.alert(
              "Entrega Salva", 
              errorMessage,
              [
                {
                  text: "OK",
                  onPress: () => {
                    // @ts-ignore
                    navigation.navigate('Home', { refreshDeliveries: true });
                  }
                }
              ]
            );
            return;
            
          } catch (fallbackError: any) {
            // Último recurso: mostrar erro genérico
            Alert.alert(
              "Erro", 
              "Não foi possível salvar a entrega. Verifique os logs e tente novamente.",
              [{ text: "OK" }]
            );
            return;
          }
        }

        // 4. Montar o deliveryData com as URLs do servidor
        // Validação robusta dos dados antes de montar o payload
        // Validação obrigatória dos campos críticos
        if (!delivery.outId) {
          Alert.alert("Erro", "ID da entrega não encontrado");
          return;
        }
        
        if (!currentInvoice.transactionId) {
          Alert.alert("Erro", "ID da transação não encontrado");
          return;
        }
        
        if (!user?.id) {
          Alert.alert("Erro", "Usuário não autenticado");
          return;
        }
      
        const deliveryData = {
          outId: delivery.outId, // Usar sempre o outId da entrega principal
          transactionId: currentInvoice.transactionId,
          deliveryDate,
          receiverDoc: receiverDoc || "", // Garantir que não seja null
          receiverName: receiverName || "", // Garantir que não seja null
          lat: delivery.coordinates?.latitude ?? delivery.lat ?? null,
          lng: delivery.coordinates?.longitude ?? delivery.lng ?? null,
          broken,
          devolution,
          reasonDevolution: devolution ? (reasonDevolution || "") : "",
          deliveryImages: [
            ...uploadedPhotoUrls.map((url: string) => ({ type: "EN", url })),
            ...(signatureUrl ? [{ type: "SIG", url: signatureUrl }] : []),
          ],
          userId: user.id,
        }
      
        // Adicionar ao array de dados
        const newDeliveryDataArray = [...deliveryDataArray, deliveryData]
        setDeliveryDataArray(newDeliveryDataArray)
        
        // Se ainda há mais notas para processar
        if (currentInvoiceIndex < selectedInvoices.size - 1) {
          const nextIndex = currentInvoiceIndex + 1
          setCurrentInvoiceIndex(nextIndex)
          
          // Limpar formulário para próxima nota
          setPhotos([])
          setSignature(null)
          setReceiverName("")
          setReceiverDoc("")
          setBroken(false)
          setDevolution(false)
          setReasonDevolution("")
          setNotes("")
          
          Alert.alert(
            "Próxima Nota", 
            `Nota ${currentInvoiceIndex + 1} de ${selectedInvoices.size} processada. Continue com a próxima nota.`
          )
          return
        }
      
      } // Fechamento do bloco if (currentStep === 'collect_info')
      
      // Se todas as notas foram processadas, SEMPRE usar modo offline
      try {
        setIsSubmitting(true)
        
        // SEMPRE MODO OFFLINE - Salvar cada nota fiscal individualmente no SQLite
        try {
          // Salvar cada nota fiscal individualmente
          for (let i = 0; i < deliveryDataArray.length; i++) {
            const deliveryData = deliveryDataArray[i];
            const deliveryInvoiceId = `${delivery.id}-${deliveryData.transactionId}-${i}`;
            
            // Salvar entrega individual por nota fiscal
            await saveDeliveryInvoice({
              id: deliveryInvoiceId,
              deliveryId: delivery.id.toString(),
              outId: deliveryData.outId.toString(),
              transactionId: deliveryData.transactionId,
              deliveryDate: deliveryData.deliveryDate,
              receiverDoc: deliveryData.receiverDoc,
              receiverName: deliveryData.receiverName,
              lat: deliveryData.lat?.toString() || '',
              lng: deliveryData.lng?.toString() || '',
              broken: deliveryData.broken,
              devolution: deliveryData.devolution,
              reasonDevolution: deliveryData.reasonDevolution,
              deliveryImages: JSON.stringify(deliveryData.deliveryImages),
              userId: deliveryData.userId
            });
          }
          
          // Completar entrega principal offline (para atualizar status geral)
          await completeDeliveryOffline({
            deliveryId: delivery.id.toString(),
            status: status === 'completed' ? 'delivered' : 
                    status === 'absent' || status === 'refused' ? 'failed' : 'in_progress',
            photos: photos,
            signature: signature || undefined,
            notes: notes,
            completedBy: user?.id?.toString() || 'unknown'
          })
          
          Alert.alert(
            "Entrega Completada",
            `A entrega foi completada e salva localmente. Será sincronizada automaticamente quando houver conexão com a internet.`,
            [
              {
                text: "OK",
                onPress: () => {
                  // Navegar para sucesso
                  navigation.navigate("DeliverySuccess" as any, {
                    deliveryCount: deliveryDataArray.length,
                    deliveryData: deliveryDataArray,
                    status: status === 'completed' ? 'delivered' : 'failed',
                    isOffline: true
                  })
                }
              }
            ]
          )
          
        } catch (offlineError) {
          Alert.alert(
            "Erro",
            "Não foi possível completar a entrega. Tente novamente."
          )
        }
        
    } catch (error: any) {
      Alert.alert("Erro", error?.message || "Ocorreu um erro ao finalizar a entrega. Tente novamente.")
    } finally {
      setIsSubmitting(false)
    }
  }

  const getStatusInfo = (statusType: string) => {
    switch (statusType) {
      case "completed":
        return {
          title: "Entregue",
          icon: "checkmark-circle",
          colors: STATUS_COLORS.completed,
        }
      case "absent":
        return {
          title: "Ausente",
          icon: "person-remove",
          colors: STATUS_COLORS.absent,
        }
      case "refused":
        return {
          title: "Recusado",
          icon: "close-circle",
          colors: STATUS_COLORS.refused,
        }
      default:
        return {
          title: "Entregue",
          icon: "checkmark-circle",
          colors: STATUS_COLORS.completed,
        }
    }
  }

  const toggleCameraType = () => {
    setCameraType((current: 'back' | 'front') => (current === 'back' ? 'front' : 'back'))
  }

  const toggleFlashMode = () => {
    setFlashMode((current: 'off' | 'on') => (current === 'off' ? 'on' : 'off'))
  }

  // Modal da Câmera
  if (isCameraActive) {
    if (cameraPermission === null) {
      return (
        <>
          <StatusBar style="light" backgroundColor={COLORS.primary} translucent={false} />
          <View style={styles.cameraContainer}>
            <LinearGradient colors={[COLORS.primary, "#3B82F6"]} style={styles.cameraHeader}>
              <SafeAreaView edges={["top"]}>
                <View style={styles.cameraHeaderContent}>
                  <TouchableOpacity style={styles.cameraCloseButton} onPress={() => setIsCameraActive(false)}>
                    <Ionicons name="close" size={24} color="white" />
                  </TouchableOpacity>
                  <Text style={styles.cameraTitle}>Câmera</Text>
                  <View style={{ width: 40 }} />
                </View>
              </SafeAreaView>
            </LinearGradient>
            <View style={styles.cameraPlaceholder}>
              <ActivityIndicator size="large" color={COLORS.primary} />
              <Text style={styles.cameraPlaceholderText}>Verificando permissões...</Text>
            </View>
          </View>
        </>
      )
    }

    if (!cameraPermission.granted) {
      return (
        <>
          <StatusBar style="light" backgroundColor={COLORS.primary} translucent={false} />
          <View style={styles.cameraContainer}>
            <LinearGradient colors={[COLORS.primary, "#3B82F6"]} style={styles.cameraHeader}>
              <SafeAreaView edges={["top"]}>
                <View style={styles.cameraHeaderContent}>
                  <TouchableOpacity style={styles.cameraCloseButton} onPress={() => setIsCameraActive(false)}>
                    <Ionicons name="close" size={24} color="white" />
                  </TouchableOpacity>
                  <Text style={styles.cameraTitle}>Câmera</Text>
                  <View style={{ width: 40 }} />
                </View>
              </SafeAreaView>
            </LinearGradient>
            <View style={styles.cameraPlaceholder}>
              <Ionicons name="camera" size={64} color={COLORS.textLight} />
              <Text style={styles.cameraPlaceholderText}>Permissão da câmera necessária</Text>
              <Text style={styles.cameraPlaceholderSubtext}>
                Para capturar fotos da entrega, precisamos acessar sua câmera
              </Text>
              
              <View style={styles.permissionButtons}>
                <TouchableOpacity style={styles.permissionButton} onPress={requestCameraAccess}>
                  <LinearGradient
                    colors={[COLORS.primary, "#3B82F6"]}
                    style={styles.permissionButtonGradient}
                  >
                    <Ionicons name="camera" size={20} color="white" />
                    <Text style={styles.permissionButtonText}>Permitir Câmera</Text>
                  </LinearGradient>
                </TouchableOpacity>

                <TouchableOpacity 
                  style={styles.permissionButtonSecondary} 
                  onPress={() => setIsCameraActive(false)}
                >
                  <Text style={styles.permissionButtonSecondaryText}>Cancelar</Text>
                </TouchableOpacity>
              </View>
            </View>
          </View>
        </>
      )
    }

    return (
      <>
        <StatusBar style="light" backgroundColor={COLORS.primary} translucent={false} />
        <View style={styles.cameraContainer}>
          <LinearGradient colors={[COLORS.primary, "#3B82F6"]} style={styles.cameraHeader}>
            <SafeAreaView edges={["top"]}>
              <View style={styles.cameraHeaderContent}>
                <TouchableOpacity style={styles.cameraCloseButton} onPress={() => setIsCameraActive(false)}>
                  <Ionicons name="close" size={24} color="white" />
                </TouchableOpacity>
                <Text style={styles.cameraTitle}>Capturar Foto</Text>
                <TouchableOpacity style={styles.cameraCloseButton} onPress={toggleFlashMode}>
                  <Ionicons name={flashMode === 'on' ? "flash" : "flash-off"} size={20} color="white" />
                </TouchableOpacity>
              </View>
            </SafeAreaView>
          </LinearGradient>

          <CameraView
            ref={cameraRef}
            style={{ flex: 1 }}
            facing={cameraType}
            flash={flashMode}
          >
            <View style={styles.cameraOverlay}>
              <View style={styles.cameraBottomControls}>
                <TouchableOpacity style={styles.cameraControlButton} onPress={toggleCameraType}>
                  <LinearGradient
                    colors={["rgba(255,255,255,0.2)", "rgba(255,255,255,0.1)"]}
                    style={styles.cameraControlGradient}
                  >
                    <Ionicons name="camera-reverse" size={24} color="white" />
                  </LinearGradient>
                </TouchableOpacity>

                <TouchableOpacity style={styles.captureButton} onPress={takePhoto} disabled={isTakingPhoto}>
                  <LinearGradient
                    colors={["#FF6B35", "#FF8E53"]}
                    style={styles.captureButtonGradient}
                  >
                    {isTakingPhoto ? (
                      <ActivityIndicator size="large" color="white" />
                    ) : (
                      <View style={styles.captureButtonInner} />
                    )}
                  </LinearGradient>
                </TouchableOpacity>

                <View style={styles.cameraControlButton} />
              </View>
            </View>
          </CameraView>
        </View>
      </>
    )
  }

  // Modal de Assinatura
  if (showSignature) {
    return (
      <>
        <StatusBar style="light" backgroundColor={COLORS.primary} translucent={false} />
        <View style={styles.signatureContainer}>
          <LinearGradient colors={[COLORS.primary, "#3B82F6"]} style={styles.signatureHeader}>
            <SafeAreaView edges={["top"]}>
              <View style={styles.signatureHeaderContent}>
                <TouchableOpacity style={styles.signatureCloseButton} onPress={() => setShowSignature(false)}>
                  <Ionicons name="close" size={24} color="white" />
                </TouchableOpacity>
                <Text style={styles.signatureTitle}>Assinatura do Cliente</Text>
                <View style={{ width: 40 }} />
              </View>
            </SafeAreaView>
          </LinearGradient>

          <SignatureScreen
            onOK={handleSignature}
            onEmpty={() => Alert.alert("Atenção", "Por favor, assine antes de confirmar.")}
            descriptionText="Assine na área abaixo"
            clearText="Limpar"
            confirmText="Confirmar"
            webStyle={`.m-signature-pad--footer { 
              display: flex; 
              justify-content: space-between; 
              background: ${COLORS.primary};
              padding: 10px;
            } 
            .m-signature-pad--footer .button { 
              background-color: white; 
              color: ${COLORS.primary}; 
              border: none;
              border-radius: 8px;
              padding: 10px 20px;
              font-weight: bold;
            }`}
          />
        </View>
      </>
    )
  }

  return (
    <>
      {/* StatusBar Global */}
      <StatusBar style="light" backgroundColor={COLORS.primary} translucent={false} />
      
      <KeyboardAvoidingView
        style={styles.container}
        behavior={Platform.OS === "ios" ? "padding" : undefined}
        keyboardVerticalOffset={Platform.OS === "ios" ? 0 : 0}
      >
        {/* Header Elegante */}
        <LinearGradient colors={[COLORS.primary, "#3B82F6"]} style={styles.headerGradient}>
          <SafeAreaView edges={["top"]}>
            <Animated.View
              style={[
                styles.header
                
              ]}
            >
              <TouchableOpacity style={styles.headerButton} onPress={() => navigation.goBack()}>
                <Ionicons name="arrow-back" size={22} color="white" />
              </TouchableOpacity>
              <View style={styles.headerCenter}>
                <Text style={styles.headerTitle}>
                  {currentStep === 'select_invoices' ? 'Selecionar Notas' : 'Finalizar Entrega'}
                </Text>
                <Text style={styles.headerSubtitle}>
                  {currentStep === 'select_invoices' 
                    ? `#${delivery.id}` 
                    : `Nota ${currentInvoiceIndex + 1} de ${selectedInvoices.size}`
                  }
                </Text>
              </View>
              <View style={styles.headerProgress}>
                <Text style={styles.progressText}>
                  {currentStep === 'select_invoices' ? '1/2' : '2/2'}
                </Text>
              </View>
            </Animated.View>
          </SafeAreaView>
        </LinearGradient>

        {/* Indicador de Sinal Mobile 
        <Animated.View
          style={[
            styles.section,
            {
              opacity: fadeAnim,
              transform: [{ translateY: slideAnim }],
            },
          ]}
        >
          <View style={styles.sectionHeader}>
            <LinearGradient
              colors={["#6366F1", "#4F46E5"]}
              style={styles.sectionIcon}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 1 }}
            >
              <Ionicons name="cellular" size={20} color="white" />
            </LinearGradient>
            <Text style={styles.sectionTitle}>Status da Conexão</Text>
          </View>

          <MobileSignalIndicator showDetails={true} />
          
          {isOfflineMode && (
            <View style={styles.offlineModeBanner}>
              <LinearGradient
                colors={["#F59E0B", "#D97706"]}
                style={styles.offlineModeGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <Ionicons name="cloud-offline" size={16} color="white" />
                <Text style={styles.offlineModeText}>
                  Modo Offline - Dados serão salvos localmente
                </Text>
              </LinearGradient>
            </View>
          )}
        </Animated.View>*/}

        <ScrollView
          ref={scrollViewRef}
          style={styles.content}
          showsVerticalScrollIndicator={false}
        >
          {/* Etapa 1: Seleção de Notas Fiscais */}
          {currentStep === 'select_invoices' && (
            <>
              {/* Informações da Entrega */}
              <Animated.View
                style={[
                  styles.section,
                  {
                    opacity: fadeAnim,
                    transform: [{ translateY: slideAnim }],
                  },
                ]}
              >
                <View style={styles.sectionHeader}>
                  <LinearGradient
                    colors={["#6366F1", "#4F46E5"]}
                    style={styles.sectionIcon}
                    start={{ x: 0, y: 0 }}
                    end={{ x: 1, y: 1 }}
                  >
                    <Ionicons name="information-circle" size={20} color="white" />
                  </LinearGradient>
                  <Text style={styles.sectionTitle}>Informações da Entrega</Text>
                </View>

                <View style={styles.infoCard}>
                  <View style={styles.infoRow}>
                    <Ionicons name="person" size={20} color={COLORS.primary} />
                    <View style={styles.infoContent}>
                      <Text style={styles.infoLabel}>Cliente</Text>
                      <Text style={styles.infoValue}>{delivery.customerName || delivery.id}</Text>
                    </View>
                  </View>

                  <View style={styles.infoRow}>
                    <Ionicons name="location" size={20} color={COLORS.primary} />
                    <View style={styles.infoContent}>
                      <Text style={styles.infoLabel}>Endereço</Text>
                      <Text style={styles.infoValue}>
                        {delivery.street ? `${delivery.street}, ${delivery.streetNumber}` : delivery.id}
                      </Text>
                    </View>
                  </View>
                </View>
              </Animated.View>

              {/* Notas Fiscais */}
              <Animated.View
                style={[
                  styles.section,
                  {
                    opacity: fadeAnim,
                    transform: [{ translateY: slideAnim }],
                  },
                ]}
              >
                <View style={styles.sectionHeader}>
                  <LinearGradient
                    colors={["#8B5CF6", "#7C3AED"]}
                    style={styles.sectionIcon}
                    start={{ x: 0, y: 0 }}
                    end={{ x: 1, y: 1 }}
                  >
                    <Ionicons name="receipt" size={20} color="white" />
                  </LinearGradient>
                  <Text style={styles.sectionTitle}>Selecionar Notas Fiscais</Text>
                  <TouchableOpacity 
                    style={styles.loadInvoicesButton} 
                    onPress={loadCustomerInvoices}
                    disabled={isLoadingInvoices}
                  >
                    {isLoadingInvoices ? (
                      <ActivityIndicator size="small" color={COLORS.primary} />
                    ) : (
                      <Ionicons name="refresh" size={16} color={COLORS.primary} />
                    )}
                  </TouchableOpacity>
                </View>

                {customerInvoices.length > 0 ? (
                  <View style={styles.invoicesContainer}>
                    <View style={styles.invoicesHeader}>
                      <Text style={styles.invoicesCount}>
                        {selectedInvoices.size} de {customerInvoices.length} notas selecionadas
                      </Text>
                      <TouchableOpacity 
                        style={styles.selectAllButton} 
                        onPress={() => {
                          if (selectedInvoices.size === customerInvoices.length) {
                            deselectAllInvoices()
                          } else {
                            selectAllInvoices()
                          }
                        }}
                      >
                        <Text style={styles.selectAllButtonText}>
                          {selectedInvoices.size === customerInvoices.length ? 'Desmarcar Todas' : 'Marcar Todas'}
                        </Text>
                      </TouchableOpacity>
                    </View>
                    
                    {/* Debug: Mostrar IDs selecionados 
                    {__DEV__ && (
                      <View style={styles.debugContainer}>
                        <Text style={styles.debugText}>
                          Notas carregadas: {customerInvoices.length}
                        </Text>
                        <Text style={styles.debugText}>
                          Notas selecionadas: {selectedInvoices.size}
                        </Text>
                        <Text style={styles.debugText}>
                          IDs selecionados: {Array.from(selectedInvoices).join(', ')}
                        </Text>
                        <Text style={styles.debugText}>
                          IDs disponíveis: {customerInvoices.map(inv => `${inv.invoiceDeliveryId}-${inv.transactionId}`).join(', ')}
                        </Text>
                      </View>
                    )}*/}

                    <ScrollView 
                      style={styles.invoicesList} 
                      showsVerticalScrollIndicator={true}
                      nestedScrollEnabled={true}
                      contentContainerStyle={{ paddingBottom: 10 }}
                    >
                      {customerInvoices.map((invoice, index) => {
                        
                        return (
                          <TouchableOpacity
                            key={`${invoice.invoiceDeliveryId}-${invoice.transactionId}`}
                            style={[
                              styles.invoiceItem,
                              selectedInvoices.has(`${invoice.invoiceDeliveryId}-${invoice.transactionId}`) && styles.invoiceItemSelected
                            ]}
                            onPress={() => {
                              toggleInvoiceSelection(invoice.invoiceDeliveryId, invoice.transactionId)
                            }}
                          >
                            <View style={[
                              styles.invoiceCheckbox,
                              selectedInvoices.has(`${invoice.invoiceDeliveryId}-${invoice.transactionId}`) && styles.invoiceCheckboxSelected
                            ]}>
                              {selectedInvoices.has(`${invoice.invoiceDeliveryId}-${invoice.transactionId}`) && (
                                <Ionicons name="checkmark" size={16} color="white" />
                              )}
                            </View>
                            
                            <View style={styles.invoiceInfo}>
                              <Text style={styles.invoiceNumber}>Nota #{invoice.invoiceDeliveryId}</Text>
                              <Text style={styles.invoiceValue}>
                                R$ {invoice.invoiceValue?.toFixed(2) || '0.00'}
                              </Text>
                              <Text style={styles.invoiceItems}>
                                {invoice.itens?.length || 0} item{invoice.itens?.length !== 1 ? 's' : ''}
                              </Text>
                            </View>
                            
                            <View style={styles.invoiceStatus}>
                              <View style={[
                                styles.statusBadge,
                                { backgroundColor: invoice.status === 'PENDING' ? '#F59E0B' : '#10B981' }
                              ]}>
                                <Text style={styles.statusBadgeText}>
                                  {invoice.status === 'PENDING' ? 'PENDENTE' : 'ENTREGUE'}
                                </Text>
                              </View>
                            </View>
                          </TouchableOpacity>
                        )
                      })}
                    </ScrollView>
                  </View>
                ) : isLoadingInvoices ? (
                  <View style={styles.loadingContainer}>
                    <ActivityIndicator size="large" color={COLORS.primary} />
                    <Text style={styles.loadingText}>Carregando notas fiscais...</Text>
                  </View>
                ) : (
                  <TouchableOpacity 
                    style={styles.loadInvoicesPrompt} 
                    onPress={loadCustomerInvoices}
                    disabled={isLoadingInvoices}
                  >
                    <LinearGradient
                      colors={["#F8FAFC", "#F1F5F9"]}
                      style={styles.loadInvoicesPromptGradient}
                      start={{ x: 0, y: 0 }}
                      end={{ x: 0, y: 1 }}
                    >
                      {isLoadingInvoices ? (
                        <ActivityIndicator size="large" color={COLORS.primary} />
                      ) : (
                        <>
                          <Ionicons name="receipt-outline" size={32} color={COLORS.primary} />
                          <Text style={styles.loadInvoicesPromptText}>Carregar Notas Fiscais</Text>
                          <Text style={styles.loadInvoicesPromptSubtext}>
                            Toque para consultar as notas fiscais do cliente
                          </Text>
                        </>
                      )}
                    </LinearGradient>
                  </TouchableOpacity>
                )}
              </Animated.View>
            </>
          )}

          {/* Etapa 2: Coleta de Informações */}
          {currentStep === 'collect_info' && (
            <>
              {/* Indicador de Progresso */}
              <Animated.View
                style={[
                  styles.section,
                  {
                    opacity: fadeAnim,
                    transform: [{ translateY: slideAnim }],
                  },
                ]}
              >
                <View style={styles.sectionHeader}>
                  <LinearGradient
                    colors={["#10B981", "#059669"]}
                    style={styles.sectionIcon}
                    start={{ x: 0, y: 0 }}
                    end={{ x: 1, y: 1 }}
                  >
                    <Ionicons name="checkmark-circle" size={20} color="white" />
                  </LinearGradient>
                  <Text style={styles.sectionTitle}>Progresso da Finalização</Text>
                </View>

                <View style={styles.progressCard}>
                  <Text style={styles.progressCardText}>
                    Processando nota {currentInvoiceIndex + 1} de {selectedInvoices.size}
                  </Text>
                  <View style={styles.progressBar}>
                    <View 
                      style={[
                        styles.progressFill, 
                        { width: `${((currentInvoiceIndex + 1) / selectedInvoices.size) * 100}%` }
                      ]} 
                    />
                  </View>
                  <Text style={styles.progressSubtext}>
                    {currentInvoiceIndex + 1} de {selectedInvoices.size} notas processadas
                  </Text>
                </View>
              </Animated.View>

          {/* Informações da Entrega */}
          <Animated.View
            style={[
              styles.section,
              {
                opacity: fadeAnim,
                transform: [{ translateY: slideAnim }],
              },
            ]}
          >
            <View style={styles.sectionHeader}>
              <LinearGradient
                colors={["#6366F1", "#4F46E5"]}
                style={styles.sectionIcon}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <Ionicons name="information-circle" size={20} color="white" />
              </LinearGradient>
              <Text style={styles.sectionTitle}>Informações da Entrega</Text>
            </View>

            <View style={styles.infoCard}>
              <View style={styles.infoRow}>
                <Ionicons name="person" size={20} color={COLORS.primary} />
                <View style={styles.infoContent}>
                  <Text style={styles.infoLabel}>Cliente</Text>
                  <Text style={styles.infoValue}>{delivery.customerName || delivery.id}</Text>
                </View>
              </View>

              <View style={styles.infoRow}>
                <Ionicons name="location" size={20} color={COLORS.primary} />
                <View style={styles.infoContent}>
                  <Text style={styles.infoLabel}>Endereço</Text>
                  <Text style={styles.infoValue}>
                    {delivery.street ? `${delivery.street}, ${delivery.streetNumber}` : delivery.id}
                  </Text>
                </View>
              </View>
            </View>
          </Animated.View>

          {/* Status da Entrega */}
          <Animated.View
            style={[
              styles.section,
              {
                opacity: fadeAnim,
                transform: [{ translateY: slideAnim }],
              },
            ]}
          >
            <View style={styles.sectionHeader}>
              <LinearGradient
                colors={getStatusInfo(status).colors.gradient}
                style={styles.sectionIcon}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <Ionicons name={getStatusInfo(status).icon as any} size={20} color="white" />
              </LinearGradient>
              <Text style={styles.sectionTitle}>Status da Entrega</Text>
            </View>

            <View style={styles.statusContainer}>
              {(["completed", "absent", "refused"] as const).map((statusType) => {
                const statusInfo = getStatusInfo(statusType)
                const isActive = status === statusType

                return (
                  <TouchableOpacity
                    key={statusType}
                    style={[
                      styles.statusOption,
                      { backgroundColor: isActive ? statusInfo.colors.background : COLORS.card },
                    ]}
                    onPress={() => setStatus(statusType)}
                  >
                    {isActive ? (
                      <LinearGradient
                        colors={statusInfo.colors.gradient}
                        style={styles.statusIconContainer}
                        start={{ x: 0, y: 0 }}
                        end={{ x: 1, y: 1 }}
                      >
                        <Ionicons name={statusInfo.icon as any} size={24} color="white" />
                      </LinearGradient>
                    ) : (
                      <View style={styles.statusIconInactive}>
                        <Ionicons name={statusInfo.icon as any} size={24} color={statusInfo.colors.primary} />
                      </View>
                    )}
                    <Text style={[styles.statusText, { color: isActive ? statusInfo.colors.primary : COLORS.textLight }]}>
                      {statusInfo.title}
                    </Text>
                  </TouchableOpacity>
                )
              })}
            </View>
          </Animated.View>

          {/* Fotos da Entrega */}
          <Animated.View
            style={[
              styles.section,
              {
                opacity: fadeAnim,
                transform: [{ translateY: slideAnim }],
              },
            ]}
          >
            <View style={styles.sectionHeader}>
              <LinearGradient
                colors={["#10B981", "#059669"]}
                style={styles.sectionIcon}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <Ionicons name="camera" size={20} color="white" />
              </LinearGradient>
              <Text style={styles.sectionTitle}>Fotos da Entrega</Text>
              <Text style={styles.photoCount}>{photos.length}/5</Text>
            </View>

            <View style={styles.photosContainer}>
              {photos.map((photo, index) => (
                <View key={index} style={styles.photoWrapper}>
                  <Image source={{ uri: photo }} style={styles.photo} />
                  <TouchableOpacity style={styles.removePhotoButton} onPress={() => removePhoto(index)}>
                    <LinearGradient
                      colors={["#EF4444", "#DC2626"]}
                      style={styles.removePhotoGradient}
                      start={{ x: 0, y: 0 }}
                      end={{ x: 1, y: 1 }}
                    >
                      <Ionicons name="close" size={16} color="white" />
                    </LinearGradient>
                  </TouchableOpacity>
                </View>
              ))}

              <TouchableOpacity style={styles.addPhotoButton} onPress={openCameraWithPermission}>
                <LinearGradient
                  colors={["#F8FAFC", "#F1F5F9"]}
                  style={styles.addPhotoGradient}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 0, y: 1 }}
                >
                  <Ionicons name="camera" size={24} color={COLORS.primary} />
                  <Text style={styles.addPhotoText}>Câmera</Text>
                </LinearGradient>
              </TouchableOpacity>
            </View>
          </Animated.View>

          {/* Assinatura do Cliente */}
          {status === "completed" && (
            <Animated.View
              style={[
                styles.section,
                {
                  opacity: fadeAnim,
                  transform: [{ translateY: slideAnim }],
                },
              ]}
            >
              <View style={styles.sectionHeader}>
                <LinearGradient
                  colors={["#8B5CF6", "#7C3AED"]}
                  style={styles.sectionIcon}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                >
                  <Ionicons name="create" size={20} color="white" />
                </LinearGradient>
                <Text style={styles.sectionTitle}>Assinatura do Cliente</Text>
              </View>

              <TouchableOpacity style={styles.signatureBox} onPress={() => setShowSignature(true)}>
                {signature ? (
                  <Image source={{ uri: signature }} style={styles.signatureImage} resizeMode="contain" />
                ) : (
                  <LinearGradient
                    colors={["#F8FAFC", "#F1F5F9"]}
                    style={styles.signaturePlaceholder}
                    start={{ x: 0, y: 0 }}
                    end={{ x: 0, y: 1 }}
                  >
                    <Ionicons name="create-outline" size={32} color={COLORS.textLight} />
                    <Text style={styles.signaturePlaceholderText}>Toque para adicionar assinatura</Text>
                  </LinearGradient>
                )}
              </TouchableOpacity>
            </Animated.View>
          )}

          {/* Dados do Recebedor */}
          <Animated.View
            style={[
              styles.section,
              {
                opacity: fadeAnim,
                transform: [{ translateY: slideAnim }],
              },
            ]}
          >
            <View style={styles.sectionHeader}>
              <LinearGradient
                colors={["#F59E0B", "#D97706"]}
                style={styles.sectionIcon}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <Ionicons name="person-add" size={20} color="white" />
              </LinearGradient>
              <Text style={styles.sectionTitle}>Dados do Recebedor</Text>
            </View>

            <View style={styles.inputContainer}>
              <View style={styles.inputWrapper}>
                <Ionicons name="person" size={20} color={COLORS.textLight} />
                <TextInput
                  style={styles.input}
                  placeholder="Nome completo do recebedor"
                  value={receiverName}
                  onChangeText={setReceiverName}
                  placeholderTextColor={COLORS.textLight}
                />
              </View>

              <View style={styles.inputWrapper}>
                <Ionicons name="card" size={20} color={COLORS.textLight} />
                <TextInput
                  style={styles.input}
                  placeholder="CPF ou CNPJ do recebedor"
                  value={receiverDoc}
                  onChangeText={setReceiverDoc}
                  placeholderTextColor={COLORS.textLight}
                />
              </View>
            </View>
          </Animated.View>

          {/* Situação da Entrega */}
          <Animated.View
            style={[
              styles.section,
              {
                opacity: fadeAnim,
                transform: [{ translateY: slideAnim }],
              },
            ]}
          >
            <View style={styles.sectionHeader}>
              <LinearGradient
                colors={["#EF4444", "#DC2626"]}
                style={styles.sectionIcon}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <Ionicons name="alert-circle" size={20} color="white" />
              </LinearGradient>
              <Text style={styles.sectionTitle}>Situação da Entrega</Text>
            </View>

            <View style={styles.checkboxContainer}>
              <TouchableOpacity style={styles.checkboxRow} onPress={() => setBroken(!broken)}>
                <View style={[styles.checkbox, broken && styles.checkboxActive]}>
                  {broken && <Ionicons name="checkmark" size={16} color="white" />}
                </View>
                <Text style={styles.checkboxLabel}>Produto danificado/quebrado</Text>
              </TouchableOpacity>

              <TouchableOpacity style={styles.checkboxRow} onPress={() => setDevolution(!devolution)}>
                <View style={[styles.checkbox, devolution && styles.checkboxActive]}>
                  {devolution && <Ionicons name="checkmark" size={16} color="white" />}
                </View>
                <Text style={styles.checkboxLabel}>Devolução necessária</Text>
              </TouchableOpacity>
            </View>

            {devolution && (
              <View style={styles.inputWrapper}>
                <Ionicons name="document-text" size={20} color={COLORS.textLight} />
                <TextInput
                  style={styles.input}
                  placeholder="Motivo da devolução"
                  value={reasonDevolution}
                  onChangeText={setReasonDevolution}
                  placeholderTextColor={COLORS.textLight}
                  multiline
                />
              </View>
            )}
          </Animated.View>

          {/* Observações */}
          <Animated.View
            style={[
              styles.section,
              {
                opacity: fadeAnim,
                transform: [{ translateY: slideAnim }],
              },
            ]}
          >
            <View style={styles.sectionHeader}>
              <LinearGradient
                colors={["#6B7280", "#4B5563"]}
                style={styles.sectionIcon}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <Ionicons name="document-text" size={20} color="white" />
              </LinearGradient>
              <Text style={styles.sectionTitle}>Observações</Text>
            </View>

            <View style={styles.inputWrapper}>
              <Ionicons name="chatbubble-ellipses" size={20} color={COLORS.textLight} />
              <TextInput
                style={[styles.input, styles.textArea]}
                placeholder="Adicione observações sobre a entrega..."
                value={notes}
                onChangeText={setNotes}
                multiline
                numberOfLines={4}
                textAlignVertical="top"
                placeholderTextColor={COLORS.textLight}
              />
            </View>
          </Animated.View>
            </>
          )}

          {/* Botão de Finalizar */}
          <Animated.View
            style={[
              styles.submitContainer,
              {
                opacity: fadeAnim,
                transform: [{ translateY: slideAnim }],
              },
            ]}
          >
            <TouchableOpacity style={styles.submitButton} onPress={handleSubmit} disabled={isSubmitting}>
              <LinearGradient
                colors={isSubmitting ? ["#9CA3AF", "#6B7280"] : getStatusInfo(status).colors.gradient}
                style={styles.submitButtonGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                {isSubmitting ? (
                  <ActivityIndicator color="white" size="small" />
                ) : (
                  <Ionicons name="checkmark-circle" size={24} color="white" />
                )}
                <Text style={styles.submitButtonText}>
                  {isSubmitting 
                    ? "Finalizando..." 
                    : currentStep === 'select_invoices'
                      ? selectedInvoices.size > 0 
                        ? `Continuar (${selectedInvoices.size} nota${selectedInvoices.size > 1 ? 's' : ''} selecionada${selectedInvoices.size > 1 ? 's' : ''})`
                        : "Continuar"
                      : `Finalizar Nota ${currentInvoiceIndex + 1} de ${selectedInvoices.size}`
                  }
                </Text>
              </LinearGradient>
            </TouchableOpacity>
          </Animated.View>

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

        {/* Modal de Opções de Foto com Header Customizado */}
        <Modal
          animationType="none"
          transparent={true}
          visible={showPhotoOptions}
          onRequestClose={() => setShowPhotoOptions(false)}
        >
          <View style={styles.modalContainer}>
            <LinearGradient colors={[COLORS.primary, "#3B82F6"]} style={styles.modalHeader}>
              <SafeAreaView edges={["top"]}>
                <View style={styles.modalHeaderContent}>
                  <TouchableOpacity 
                    style={styles.modalCloseButton} 
                    onPress={() => setShowPhotoOptions(false)}
                  >
                    <Ionicons name="close" size={24} color="white" />
                  </TouchableOpacity>
                  <Text style={styles.modalHeaderTitle}>Adicionar Foto</Text>
                  <View style={{ width: 40 }} />
                </View>
              </SafeAreaView>
            </LinearGradient>

            <View style={styles.modalOverlay}>
              <TouchableOpacity style={styles.modalBackdrop} onPress={() => setShowPhotoOptions(false)} />
              <Animated.View
                style={[
                  styles.photoOptionsModal,
                  {
                    opacity: modalAnim,
                    transform: [
                      {
                        translateY: modalAnim.interpolate({
                          inputRange: [0, 1],
                          outputRange: [300, 0],
                        }),
                      },
                    ],
                  },
                ]}
              >
                <TouchableOpacity style={styles.photoOption} onPress={openCameraWithPermission}>
                  <LinearGradient
                    colors={["#3B82F6", "#2563EB"]}
                    style={styles.photoOptionIcon}
                    start={{ x: 0, y: 0 }}
                    end={{ x: 1, y: 1 }}
                  >
                    <Ionicons name="camera" size={24} color="white" />
                  </LinearGradient>
                  <View style={styles.photoOptionInfo}>
                    <Text style={styles.photoOptionTitle}>Câmera</Text>
                    <Text style={styles.photoOptionSubtitle}>Tirar uma nova foto</Text>
                  </View>
                  <Ionicons name="chevron-forward" size={20} color={COLORS.textLight} />
                </TouchableOpacity>

                <TouchableOpacity style={styles.photoOption} onPress={pickImage}>
                  <LinearGradient
                    colors={["#10B981", "#059669"]}
                    style={styles.photoOptionIcon}
                    start={{ x: 0, y: 0 }}
                    end={{ x: 1, y: 1 }}
                  >
                    <Ionicons name="images" size={24} color="white" />
                  </LinearGradient>
                  <View style={styles.photoOptionInfo}>
                    <Text style={styles.photoOptionTitle}>Galeria</Text>
                    <Text style={styles.photoOptionSubtitle}>Escolher da galeria</Text>
                  </View>
                  <Ionicons name="chevron-forward" size={20} color={COLORS.textLight} />
                </TouchableOpacity>
              </Animated.View>
            </View>
          </View>
        </Modal>
      </KeyboardAvoidingView>
    </>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  headerGradient: {
    paddingBottom: 12,
  },
  header: {
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 16,
    paddingTop: 8,
  },
  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: 18,
    fontWeight: "bold",
    color: "white",
  },
  headerSubtitle: {
    fontSize: 12,
    color: "rgba(255, 255, 255, 0.8)",
    marginTop: 2,
  },
  headerProgress: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: "rgba(255, 255, 255, 0.2)",
    alignItems: "center",
    justifyContent: "center",
  },
  progressText: {
    fontSize: 11,
    fontWeight: "bold",
    color: "white",
  },
  content: {
    flex: 1,
    marginTop: -8,
  },
  section: {
    marginHorizontal: 16,
    marginBottom: 16,
  },
  sectionHeader: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 10,
    marginTop: 20,
  },
  sectionIcon: {
    width: 28,
    height: 28,
    borderRadius: 14,
    alignItems: "center",
    justifyContent: "center",
    marginRight: 10,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: "bold",
    color: COLORS.text,
    flex: 1,
  },
  photoCount: {
    fontSize: 12,
    color: COLORS.textLight,
    fontWeight: "500",
  },
  infoCard: {
    backgroundColor: COLORS.card,
    borderRadius: 12,
    padding: 12,
    ...SHADOWS.medium,
  },
  infoRow: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 10,
  },
  infoContent: {
    marginLeft: 10,
    flex: 1,
  },
  infoLabel: {
    fontSize: 11,
    color: COLORS.textLight,
    marginBottom: 2,
  },
  infoValue: {
    fontSize: 14,
    color: COLORS.text,
    fontWeight: "500",
  },
  statusContainer: {
    flexDirection: "row",
    justifyContent: "space-between",
    gap: 8,
  },
  statusOption: {
    flex: 1,
    alignItems: "center",
    padding: 12,
    borderRadius: 12,
    ...SHADOWS.small,
  },
  statusIconContainer: {
    width: 40,
    height: 40,
    borderRadius: 20,
    alignItems: "center",
    justifyContent: "center",
    marginBottom: 6,
  },
  statusIconInactive: {
    width: 40,
    height: 40,
    borderRadius: 20,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: COLORS.background,
    marginBottom: 6,
  },
  statusText: {
    fontSize: 12,
    fontWeight: "600",
    textAlign: "center",
  },
  photosContainer: {
    flexDirection: "row",
    flexWrap: "wrap",
    gap: 8,
  },
  photoWrapper: {
    width: (width - 48) / 2,
    aspectRatio: 1,
    borderRadius: 10,
    overflow: "hidden",
    position: "relative",
    ...SHADOWS.small,
  },
  photo: {
    width: "100%",
    height: "100%",
  },
  removePhotoButton: {
    position: "absolute",
    top: 6,
    right: 6,
    width: 20,
    height: 20,
    borderRadius: 10,
    overflow: "hidden",
  },
  removePhotoGradient: {
    width: "100%",
    height: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  addPhotoButton: {
    width: (width - 48) / 2,
    aspectRatio: 1,
    borderRadius: 10,
    overflow: "hidden",
    borderWidth: 1.5,
    borderColor: COLORS.border,
    borderStyle: "dashed",
  },
  addPhotoGradient: {
    width: "100%",
    height: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  addPhotoText: {
    fontSize: 11,
    color: COLORS.primary,
    fontWeight: "500",
    marginTop: 4,
  },
  signatureBox: {
    height: 120,
    borderRadius: 10,
    overflow: "hidden",
    borderWidth: 1,
    borderColor: COLORS.border,
    ...SHADOWS.small,
  },
  signaturePlaceholder: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  signaturePlaceholderText: {
    fontSize: 12,
    color: COLORS.textLight,
    marginTop: 6,
    fontWeight: "500",
  },
  signatureImage: {
    width: "100%",
    height: "100%",
  },
  inputContainer: {
    gap: 8,
  },
  inputWrapper: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: COLORS.card,
    borderRadius: 10,
    paddingHorizontal: 12,
    paddingVertical: 10,
    borderWidth: 1,
    borderColor: COLORS.border,
    ...SHADOWS.small,
  },
  input: {
    flex: 1,
    fontSize: 14,
    color: COLORS.text,
    marginLeft: 10,
  },
  textArea: {
    minHeight: 60,
    textAlignVertical: "top",
  },
  checkboxContainer: {
    gap: 10,
  },
  checkboxRow: {
    flexDirection: "row",
    alignItems: "center",
  },
  checkbox: {
    width: 20,
    height: 20,
    borderRadius: 5,
    borderWidth: 2,
    borderColor: COLORS.border,
    alignItems: "center",
    justifyContent: "center",
    marginRight: 10,
  },
  checkboxActive: {
    backgroundColor: COLORS.primary,
    borderColor: COLORS.primary,
  },
  checkboxLabel: {
    fontSize: 14,
    color: COLORS.text,
    flex: 1,
  },
  submitContainer: {
    marginHorizontal: 16,
    marginTop: 16,
  },
  submitButton: {
    borderRadius: 12,
    overflow: "hidden",
    ...SHADOWS.medium,
  },
  submitButtonGradient: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 14,
    gap: 10,
  },
  submitButtonText: {
    fontSize: 16,
    fontWeight: "bold",
    color: "white",
  },
  // Novos estilos para modais customizados
  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,
  },
  photoOptionsModal: {
    backgroundColor: COLORS.card,
    borderTopLeftRadius: 16,
    borderTopRightRadius: 16,
    padding: 16,
    paddingBottom: 24,
    maxHeight: height * 0.4,
  },
  photoOption: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 10,
    paddingHorizontal: 4,
    borderRadius: 8,
    marginVertical: 2,
  },
  photoOptionIcon: {
    width: 36,
    height: 36,
    borderRadius: 18,
    alignItems: "center",
    justifyContent: "center",
    marginRight: 12,
  },
  photoOptionInfo: {
    flex: 1,
  },
  photoOptionTitle: {
    fontSize: 14,
    fontWeight: "600",
    color: COLORS.text,
    marginBottom: 1,
  },
  photoOptionSubtitle: {
    fontSize: 12,
    color: COLORS.textLight,
  },
  // Estilos da câmera
  cameraContainer: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  cameraHeader: {
    paddingBottom: 12,
  },
  cameraHeaderContent: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 20,
    paddingTop: 8,
  },
  cameraCloseButton: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: "rgba(255, 255, 255, 0.2)",
    alignItems: "center",
    justifyContent: "center",
  },
  cameraTitle: {
    fontSize: 16,
    fontWeight: "bold",
    color: "white",
  },
  cameraPlaceholder: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: COLORS.background,
    paddingHorizontal: 32,
  },
  cameraPlaceholderText: {
    fontSize: 16,
    color: COLORS.text,
    marginTop: 12,
    fontWeight: "600",
    textAlign: "center",
  },
  cameraPlaceholderSubtext: {
    fontSize: 14,
    color: COLORS.textLight,
    marginTop: 8,
    textAlign: "center",
    lineHeight: 20,
  },
  permissionButtons: {
    marginTop: 32,
    width: "100%",
    gap: 12,
  },
  permissionButton: {
    borderRadius: 12,
    overflow: "hidden",
    ...SHADOWS.medium,
  },
  permissionButtonGradient: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 14,
    paddingHorizontal: 24,
    gap: 8,
  },
  permissionButtonText: {
    fontSize: 16,
    fontWeight: "bold",
    color: "white",
  },
  permissionButtonSecondary: {
    paddingVertical: 14,
    paddingHorizontal: 24,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: COLORS.border,
    backgroundColor: COLORS.card,
    alignItems: "center",
    justifyContent: "center",
  },
  permissionButtonSecondaryText: {
    fontSize: 16,
    fontWeight: "600",
    color: COLORS.textLight,
  },
  cameraOverlay: {
    flex: 1,
    justifyContent: "flex-end",
  },
  cameraBottomControls: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 32,
    paddingVertical: 32,
    backgroundColor: "rgba(0, 0, 0, 0.3)",
  },
  cameraControlButton: {
    width: 48,
    height: 48,
    borderRadius: 24,
    overflow: "hidden",
  },
  cameraControlGradient: {
    width: "100%",
    height: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  captureButton: {
    width: 72,
    height: 72,
    borderRadius: 36,
    overflow: "hidden",
    ...SHADOWS.medium,
  },
  captureButtonGradient: {
    width: "100%",
    height: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  captureButtonInner: {
    width: 60,
    height: 60,
    borderRadius: 30,
    backgroundColor: "white",
  },
  // Estilos da assinatura
  signatureContainer: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  signatureHeader: {
    paddingBottom: 12,
  },
  signatureHeaderContent: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 20,
    paddingTop: 8,
  },
  signatureCloseButton: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: "rgba(255, 255, 255, 0.2)",
    alignItems: "center",
    justifyContent: "center",
  },
  signatureTitle: {
    fontSize: 16,
    fontWeight: "bold",
    color: "white",
  },
  notFoundContainer: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  notFoundText: {
    fontSize: 16,
    color: "white",
    marginTop: 12,
    fontWeight: "600",
  },
  // Estilos para notas fiscais
  loadInvoicesButton: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: COLORS.background,
    alignItems: "center",
    justifyContent: "center",
    ...SHADOWS.small,
  },
  invoicesContainer: {
    backgroundColor: COLORS.card,
    borderRadius: 12,
    padding: 12,
    ...SHADOWS.small,
  },
  invoicesHeader: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    marginBottom: 12,
  },
  invoicesCount: {
    fontSize: 12,
    color: COLORS.textLight,
    fontWeight: "500",
  },
  selectAllButton: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 8,
    backgroundColor: COLORS.primary,
  },
  selectAllButtonText: {
    fontSize: 11,
    color: "white",
    fontWeight: "600",
  },
  invoicesList: {
    maxHeight: 300,
  },
  invoiceItem: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 8,
    paddingHorizontal: 12,
    borderRadius: 8,
    backgroundColor: COLORS.background,
    marginBottom: 6,
    borderWidth: 1,
    borderColor: COLORS.border,
  },
  invoiceItemSelected: {
    backgroundColor: COLORS.primary + "10",
    borderColor: COLORS.primary,
  },
  invoiceCheckbox: {
    width: 20,
    height: 20,
    borderRadius: 10,
    borderWidth: 2,
    borderColor: COLORS.border,
    alignItems: "center",
    justifyContent: "center",
    marginRight: 12,
  },
  invoiceCheckboxSelected: {
    backgroundColor: COLORS.primary,
    borderColor: COLORS.primary,
  },
  invoiceInfo: {
    flex: 1,
  },
  invoiceNumber: {
    fontSize: 14,
    fontWeight: "600",
    color: COLORS.text,
    marginBottom: 2,
  },
  invoiceValue: {
    fontSize: 12,
    color: COLORS.primary,
    fontWeight: "600",
    marginBottom: 2,
  },
  invoiceItems: {
    fontSize: 11,
    color: COLORS.textLight,
  },
  invoiceStatus: {
    marginLeft: 8,
  },
  statusBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 6,
  },
  statusBadgeText: {
    fontSize: 10,
    color: "white",
    fontWeight: "600",
  },
  loadInvoicesPrompt: {
    height: 120,
    borderRadius: 10,
    overflow: "hidden",
    borderWidth: 1,
    borderColor: COLORS.border,
    ...SHADOWS.small,
  },
  loadInvoicesPromptGradient: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  loadInvoicesPromptText: {
    fontSize: 14,
    color: COLORS.primary,
    fontWeight: "600",
    marginTop: 8,
  },
  loadInvoicesPromptSubtext: {
    fontSize: 12,
    color: COLORS.textLight,
    marginTop: 4,
    textAlign: "center",
  },
  // Estilos para o indicador de progresso
  progressCard: {
    backgroundColor: COLORS.card,
    borderRadius: 12,
    padding: 16,
    ...SHADOWS.small,
    alignItems: "center",
  },
  progressCardText: {
    fontSize: 14,
    fontWeight: "600",
    color: COLORS.text,
    marginBottom: 8,
  },
  progressBar: {
    width: "100%",
    height: 8,
    backgroundColor: COLORS.border,
    borderRadius: 4,
    marginBottom: 8,
  },
  progressFill: {
    height: "100%",
    borderRadius: 4,
    backgroundColor: COLORS.primary,
  },
  progressSubtext: {
    fontSize: 12,
    color: COLORS.textLight,
  },
  // Estilos para debug
  debugContainer: {
    backgroundColor: COLORS.card,
    borderRadius: 8,
    padding: 10,
    marginTop: 10,
    alignSelf: 'center',
    ...SHADOWS.small,
  },
  debugText: {
    fontSize: 12,
    color: COLORS.textLight,
    fontWeight: '500',
  },
  loadingContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    padding: 20,
  },
  loadingText: {
    marginTop: 10,
    fontSize: 14,
    color: COLORS.textLight,
    textAlign: 'center',
  },

  offlineModeBanner: {
    marginTop: 8,
    borderRadius: 8,
    overflow: 'hidden',
  },
  offlineModeGradient: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 8,
    paddingHorizontal: 12,
    gap: 8,
  },
  offlineModeText: {
    fontSize: 12,
    color: 'white',
    fontWeight: '600',
    textAlign: 'center',
  },
})

export default CompleteDeliveryScreen