import { useEffect, useRef, useState } from 'react'
import maplibregl, { Map as MapInstance, Marker as MapMarker, StyleSpecification } from 'maplibre-gl'
import 'maplibre-gl/dist/maplibre-gl.css'

const MAHABUBNAGAR_CENTER: [number, number] = [78.0035, 16.7488]
const DEFAULT_ZOOM = 12

const osmStyle: StyleSpecification = {
  version: 8,
  sources: {
    osm: {
      type: 'raster',
      tiles: ['https://tile.openstreetmap.org/{z}/{x}/{y}.png'] as string[],
      tileSize: 256,
      attribution:
        '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }
  },
  layers: [
    {
      id: 'osm-tiles',
      type: 'raster',
      source: 'osm'
    }
  ]
}

export function LocationMarkerRoute() {
  const mapContainerRef = useRef<HTMLDivElement | null>(null)
  const mapRef = useRef<MapInstance | null>(null)
  const markerRef = useRef<MapMarker | null>(null)
  const [coords, setCoords] = useState({
    lat: MAHABUBNAGAR_CENTER[1],
    lng: MAHABUBNAGAR_CENTER[0]
  })

  useEffect(() => {
    if (!mapContainerRef.current || mapRef.current) return

    const map = new maplibregl.Map({
      container: mapContainerRef.current,
      style: osmStyle,
      center: MAHABUBNAGAR_CENTER,
      zoom: DEFAULT_ZOOM,
      attributionControl: { compact: true }
    })

    map.addControl(new maplibregl.NavigationControl({ visualizePitch: true }), 'top-right')

    const marker = new maplibregl.Marker({ draggable: true })
      .setLngLat(MAHABUBNAGAR_CENTER)
      .addTo(map)

    marker.on('dragend', () => {
      const position = marker.getLngLat()
      setCoords({ lat: position.lat, lng: position.lng })
    })

    mapRef.current = map
    markerRef.current = marker

    return () => {
      marker.remove()
      map.remove()
      markerRef.current = null
      mapRef.current = null
    }
  }, [])

  return (
    <div className="min-h-screen rounded-md">
      <div className="mx-auto flex min-h-screen max-w-xl flex-col rounded-md">
          <div
            ref={mapContainerRef}
            className="h-screen w-full rounded-md"
          />
          <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(125,211,252,0.12),transparent_45%)]" />
      </div>
    </div>
  )
}
