import leaflet, { type Map } from 'leaflet';
import { type Ref, useEffect, useRef } from 'preact/hooks';

import 'leaflet/dist/leaflet.css';

export type MapViewParameters = Parameters<Map['setView']>;

export const useMap = (
    mapContainerRef: Readonly<Ref<HTMLElement>>,
    viewParameters: MapViewParameters,
) => {
    const mapRef = useRef<leaflet.Map | undefined>(undefined);

    useEffect(() => {
        if (mapRef.current) {
            return;
        }

        if (!mapContainerRef.current) {
            return;
        }

        const map = leaflet.map(mapContainerRef.current);
        map.setView(...viewParameters);

        leaflet
            .tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
                maxZoom: 19,
                attribution:
                    '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
            })
            .addTo(map);

        mapRef.current = map;

        return () => {
            map.remove();
        };
    }, [mapContainerRef, mapRef, viewParameters]);

    return mapRef;
};
