import React, { useEffect, useRef, useState } from 'react';
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import icon from "leaflet/dist/images/marker-icon.png";
import iconShadow from "leaflet/dist/images/marker-shadow.png";

let DefaultIcon = L.icon({
iconUrl: icon,
shadowUrl: iconShadow,
});

export default function Map() {

    const mapContainer = useRef();
    const [map, setMap] = useState({});

    useEffect(()=>{

	/*Instantiates a map object given an instance of a <div> HTML element and optionally an object literal with Map options.*/
        const map = L.map(
	    mapContainer.current,
	    {attributionControl: false}
	).setView([51.505, -0.09], 13);

	map.zoomControl.setPosition("bottomright");

	L.tileLayer(
	    "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}",
	    {
		attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
		maxZoom: 18,
		id: 'mapbox/streets-v11',
		tileSize: 512,
		zoomOffset: -1,
		accessToken:  "pk.eyJ1IjoidGFyLWhlbCIsImEiOiJjbDJnYWRieGMwMTlrM2luenIzMzZwbGJ2In0.RQRMAJqClc4qoNwROT8Umg",
		scrollWheelZoom: false,
	    }).addTo(map);

	//TODO: Why is 'scrollWheelZoom: false,' above not working?
	//TODO: Why the following line instead?
	map.scrollWheelZoom.disable()

	L.Marker.prototype.options.icon = DefaultIcon;
	var marker = L.marker(
	    [51.5, -0.09],
	    {alt: 'popup marker name: ' + "Hello world! I am a popup."}
	).addTo(map);
	marker.bindPopup("<b>Hello world!</b><br>I am a popup.").openPopup();

	// unmount map function
	//You should unmount the function in react.js to remove the existing map.
	return () => map.remove();
    }, []);

    return (
	<>
	    <p>MapNxt</p>
            <div
		style={{padding: 0, margin: 0, width: "50%", height: "23vh",}}
		ref={el => mapContainer.current = el}>
            </div>
	</>
    );
};
//https://stackoverflow.com/a/66920207/15078958
