"use client"

import type React from "react"
import { createContext, useContext, useState, useEffect } from "react"
import NetInfo from "@react-native-community/netinfo"
import { getSetting, saveSetting } from "../services/database"
import { offlineSyncService } from "../services/offlineSyncService"

// Interface para o contexto
interface SyncContextData {
  isOnline: boolean
  isSyncing: boolean
  lastSyncTime: number | null
  pendingSyncCount: number
  syncNow: () => Promise<boolean>
}

// Criar o contexto
const SyncContext = createContext<SyncContextData>({} as SyncContextData)

// Hook para usar o contexto
export const useSync = () => useContext(SyncContext)

// Provedor do contexto
export const SyncProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [isOnline, setIsOnline] = useState(true)
  const [isSyncing, setIsSyncing] = useState(false)
  const [lastSyncTime, setLastSyncTime] = useState<number | null>(null)
  // Simular 3 entregas pendentes de sincronização
  const [pendingSyncCount, setPendingSyncCount] = useState(3)

  // Carregar o último tempo de sincronização
  useEffect(() => {
    const loadLastSyncTime = async () => {
      try {
        const lastSync = await getSetting("last_sync")
        if (lastSync) {
          setLastSyncTime(Number.parseInt(lastSync, 10))
        }
      } catch (error) {
        // Ignorar erro
      }
    }

    loadLastSyncTime()
  }, [])

  // Monitorar o estado da conexão
  useEffect(() => {
    const unsubscribe = NetInfo.addEventListener((state) => {
      // Verificar se state existe e tem a propriedade isConnected
      if (state && typeof state.isConnected !== 'undefined') {
        setIsOnline(state.isConnected)
      } else {
        setIsOnline(false);
      }
    })

    return () => unsubscribe()
  }, [])

  // Função para sincronizar dados
  const syncNow = async (): Promise<boolean> => {
    if (!isOnline || isSyncing) {
      return false
    }

    setIsSyncing(true)

    try {
      // Usar o serviço de sincronização offline
      const result = await offlineSyncService.syncAllPendingDeliveries()

      // Atualizar último tempo de sincronização
      const now = Date.now()
      await saveSetting("last_sync", now.toString())
      setLastSyncTime(now)
      
      // Atualizar contador de pendentes
      const stats = await offlineSyncService.getSyncStats()
      setPendingSyncCount(stats.pendingDeliveries || 0)

      return result.success
    } catch (error) {
      console.error("❌ Erro ao sincronizar dados:", error.message)
      return false
    } finally {
      setIsSyncing(false)
    }
  }

  return (
    <SyncContext.Provider
      value={{
        isOnline,
        isSyncing,
        lastSyncTime,
        pendingSyncCount,
        syncNow,
      }}
    >
      {children}
    </SyncContext.Provider>
  )
}

