import 'leaflet/dist/leaflet.css';
import * as L from 'leaflet';
import { LatLngExpression, LatLngBounds } from 'leaflet';
import * as Proj from 'proj4leaflet';
import React, { useEffect, useState } from 'react';
import { FeatureGroup, MapContainer, TileLayer, useMap } from 'react-leaflet';

const STANDARDKART_URL =
	'//nvdbcache.geodataonline.no/arcgis/rest/services/Trafikkportalen/GeocacheTrafikkJPG/MapServer/tile/{z}/{y}/{x}';

// @ts-ignore
const CRS = typeof L?.Proj?.CRS === 'function' ? L.Proj.CRS : Proj.CRS;
const vanligCRS = new CRS(
	'EPSG:25833',
	'+proj=utm +zone=33 +ellps=GRS80 +units=m +no_defs',
	{
		origin: [-2500000, 9045984],
		resolutions: [
			21674.7100160867, 10837.35500804335, 5418.677504021675,
			2709.3387520108377, 1354.6693760054188, 677.3346880027094,
			338.6673440013547, 169.33367200067735, 84.66683600033868,
			42.33341800016934, 21.16670900008467, 10.583354500042335,
			5.291677250021167, 2.6458386250105836, 1.3229193125052918,
			0.6614596562526459, 0.33072982812632296, 0.16536491406316148,
		],
	}
);

const gjennomsiktig =
	'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';

export const markorikon = function () {
	return L.icon({
		className: 'markorikon ikon-kartmarkor',
		iconUrl: gjennomsiktig,
		iconSize: [40, 54],
		iconAnchor: [20, 54],
	});
};

export const varslingsikon = function () {
	return L.icon({
		className: 'varslingsikon ikon-skilt-110-stilk',
		iconUrl: gjennomsiktig,
		iconSize: [45, 80],
		iconAnchor: [22, 79],
	});
};

interface FixBoundsProps {
	featureBounds?: LatLngBounds;
}

const FixBounds: React.FC<FixBoundsProps> = function ({ featureBounds }) {
	const map = useMap();
	useEffect(() => {
		if (featureBounds?.isValid()) {
			map.fitBounds(featureBounds, { padding: [30, 60] });
		}
	}, [featureBounds]);

	return null;
};

const ScrollWheelZoomControl: React.FC<{ enable: boolean }> = ({ enable }) => {
	const map = useMap();

	useEffect(() => {
		if (enable) {
			map.scrollWheelZoom.enable();
		} else {
			map.scrollWheelZoom.disable();
		}
	}, [enable, map]);

	return null;
};

const DEFAULT_ZOOM = 4;
const DEFAULT_CENTER: LatLngExpression = [63.990556, 12.307778];

const Kart: React.FC = ({ children }) => {
	const [enableScrollWheelZoom, setEnableScrollWheelZoom] = useState(false);
	const [featureGroupRef, setFeatureGroupRef] =
		useState<L.FeatureGroup | null>(null);

	return (
		<div
			title="Klikk for å bruke scrollhjul ved zoom"
			onClick={() => setEnableScrollWheelZoom(true)}
		>
			<MapContainer
				crs={vanligCRS}
				minZoom={3}
				maxZoom={16}
				zoom={DEFAULT_ZOOM}
				center={DEFAULT_CENTER}
			>
				<ScrollWheelZoomControl enable={enableScrollWheelZoom} />
				<FeatureGroup
					ref={(featureRef) => setFeatureGroupRef(featureRef)}
				>
					{children}
				</FeatureGroup>
				<TileLayer url={STANDARDKART_URL} />
				<FixBounds featureBounds={featureGroupRef?.getBounds()} />
			</MapContainer>
		</div>
	);
};

export { Kart };
