import { useLocation } from "@/hooks/useLocation"
import { circle } from "@turf/circle"
import { type Map as MaplibreGLMap } from "maplibre-gl"
import { RLayer, RMap, RMarker, RNavigationControl, RSource, useMap } from "maplibre-react-components"
import { useState } from "react"

export default function Map() {
  return (
    <RMap
        initialCenter={[2.9, 46.5]}
        initialZoom={6}
        mapStyle="https://openmaptiles.geo.data.gouv.fr/styles/osm-bright/style.json">
      <RNavigationControl position="bottom-right" showCompass={true} showZoom={true} visualizePitch={true} />

      <RSource id="railwaymap-source" type="raster" tiles={["https://a.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png"]} />
      <RLayer id="railwaymap-layer" type="raster" source="railwaymap-source" paint={{"raster-opacity": 0.7}} />

      <UserLocation />
    </RMap>
  )
}

function UserLocation() {
  const userLocation = useLocation()
  const [firstUserPositionFetched, setFirstUserPositionFetched] = useState(false)
  const map: MaplibreGLMap = useMap()
  if (userLocation != null && !firstUserPositionFetched) {
    setFirstUserPositionFetched(true)
    map.flyTo({center: [userLocation.coords.longitude, userLocation.coords.latitude], zoom: 15})
  }
  const accuracyCircle = circle([userLocation?.coords.longitude ?? 0, userLocation?.coords.latitude ?? 0], userLocation?.coords.accuracy ?? 0, {steps: 64, units: 'meters'})
  const marker = userLocation ? <RMarker longitude={userLocation?.coords.longitude} latitude={userLocation?.coords.latitude} /> : <></>
  return <>
    <RSource id="accuracy-radius" type="geojson" data={accuracyCircle} />
    <RLayer id="accuracy-radius-fill" type="fill" source="accuracy-radius" paint={{"fill-color": "lightblue", "fill-opacity": 0.4}} />
    <RLayer id="accuracy-radius-border" type="line" source="accuracy-radius" paint={{"line-color": "blue", "line-opacity": 0.4}} />
    {marker}
  </>
}
