import { ReactNode, useEffect } from 'react'
import { useAuth } from '@/hooks/useAuth'
import { useQueuedLocations, useSetLastPlayerLocations, useUnqueueLocation } from '@/hooks/useLocation'
import { useGeolocationMutation } from '@/hooks/mutations/useGeolocationMutation'
import { useStartGeolocationServiceEffect } from '@/utils/geolocation'
import { Platform } from 'react-native'
import { useQuery } from '@tanstack/react-query'
import { isAuthValid } from '@/utils/features/auth/authSlice'

export default function GeolocationProvider({ children }: { children: ReactNode }) {
  useStartGeolocationServiceEffect()

  const auth = useAuth()
  const geolocationsQueue = useQueuedLocations()
  const unqueueLocation = useUnqueueLocation()
  const setLastPlayerLocations = useSetLastPlayerLocations()
  const geolocationMutation = useGeolocationMutation({
    auth,
    onPostSuccess: (data) => unqueueLocation(data),
    onError: ({ response, error }) => { console.error(response, error) }
  })
  
  if (Platform.OS !== "web") {
    useEffect(() => {
      if (geolocationsQueue.length === 0 || geolocationMutation.isPending || isAuthValid(auth))
        return
      const locToSend = geolocationsQueue[0]
      geolocationMutation.mutate(locToSend)
    }, [auth, geolocationMutation.status, geolocationsQueue])
  }

  const lastLocationsQuery = useQuery({
    queryKey: ['get-last-locations', auth.token],
    queryFn: () => fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/geolocations/last-locations/`, {
      method: "GET",
      headers: {
        "Authorization": `Bearer ${auth.token}`,
        "Content-Type": "application/json",
      },
    }).then(resp => resp.json()),
    initialData: [],
    enabled: isAuthValid(auth),
    refetchInterval: 5000,
  })
  useEffect(() => {
    if (lastLocationsQuery.isSuccess && lastLocationsQuery.data)
      setLastPlayerLocations(lastLocationsQuery.data)
  }, [lastLocationsQuery.status, lastLocationsQuery.dataUpdatedAt])

  return <>
    {children}
  </>
}