import * as Location from 'expo-location'
import {useEffect, useState} from 'react'

export type Coords = {latitude: number; longitude: number}

export const useCurrentLocation = () => {
  const [coords, setCoords] = useState<Coords | null>(null)

  useEffect(() => {
    let sub: Location.LocationSubscription | null = null
    let cancelled = false
    const start = async () => {
      const {status} =
        await Location.requestForegroundPermissionsAsync()
      if (status !== 'granted' || cancelled) return
      sub = await Location.watchPositionAsync(
        {accuracy: Location.Accuracy.Balanced, distanceInterval: 25},
        ({coords}) =>
          setCoords({
            latitude: coords.latitude,
            longitude: coords.longitude,
          }),
      )
    }
    void start()
    return () => {
      cancelled = true
      sub?.remove()
    }
  }, [])

  return coords
}
