import { Marker, Popup, useMapEvents } from 'react-leaflet'
import { LatLng } from 'leaflet'

import { SetState } from '../utils/types'
import { iconItem } from '../utils/markerIcons'

type LocationMarkerProps = {
    address: string,
    position: LatLng,
    setPosition: SetState<LatLng>
}

function LocationMarker({ address, position, setPosition }: LocationMarkerProps) {

    const map = useMapEvents({
        dragend: () => {
            setPosition(map.getCenter())
        },
        zoomend: () => {
            setPosition(map.getCenter())
        },
        resize: () => {
            setPosition(map.getCenter())
        }
    })

    return (
        <Marker icon={iconItem} position={position}>
            <Popup>
                {address}
                {position.lat.toFixed(4)}, {position.lng.toFixed(4)}
            </Popup>
        </Marker>
    )
}

export default LocationMarker
