import React, { createContext, useContext, useState, useEffect } from 'react'
import NetInfo from '@react-native-community/netinfo'
import * as SecureStore from 'expo-secure-store'

interface OfflineCtx {
  isOffline: boolean
  getCache: (key: string) => Promise<unknown>
  setCache: (key: string, data: unknown) => Promise<void>
}

export const OfflineContext = createContext<OfflineCtx>({
  isOffline: false,
  getCache: async () => null,
  setCache: async () => {},
})

export function OfflineProvider({ children }: { children: React.ReactNode }) {
  const [isOffline, setIsOffline] = useState(false)

  useEffect(() => {
    const unsub = NetInfo.addEventListener((state: any) => {
      setIsOffline(!(state.isConnected && state.isInternetReachable !== false))
    })
    return () => unsub()
  }, [])

  const getCache = async (key: string) => {
    try {
      const raw = await SecureStore.getItemAsync(`cache_${key}`)
      return raw ? JSON.parse(raw) : null
    } catch { return null }
  }

  const setCache = async (key: string, data: unknown) => {
    try {
      await SecureStore.setItemAsync(`cache_${key}`, JSON.stringify(data))
    } catch {}
  }

  return (
    <OfflineContext.Provider value={{ isOffline, getCache, setCache }}>
      {children}
    </OfflineContext.Provider>
  )
}

export const useOffline = () => useContext(OfflineContext)
