import { LatLngTuple } from "leaflet";
import { FC, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { MapContainer, TileLayer } from "react-leaflet";

import { MAP_OBJECT_ZOOM } from "../../../constants";
import { isNumber } from "../../../services/math";
import { AssetModel } from "@/contracts/client.schemas";
import { MovableMapObject } from "./MovableMapObject";
import styles from "./OneObjectMap.module.css";
import "leaflet/dist/leaflet.css";

interface Props {
	asset: AssetModel;
}
export const OneObjectMap: FC<Props> = ({ asset }) => {
	const { t } = useTranslation("translation");

	const latitude = isNumber(asset.latitude);
	const longitude = isNumber(asset.longitude);

	const [position, setPosition] = useState<LatLngTuple>(() => {
		if (latitude.is && longitude.is) {
			return [latitude.value, longitude.value];
		}
		return [0, 0];
	});

	useEffect(() => {
		const lat = isNumber(asset.latitude);
		const lng = isNumber(asset.longitude);

		if (lat.is && lng.is) {
			setPosition([lat.value, lng.value]);
		}
	}, [asset]);

	if (!latitude.is || !longitude.is) {
		return null;
	}

	return (
		<MapContainer
			center={position}
			zoom={MAP_OBJECT_ZOOM}
			scrollWheelZoom={true}
			className={styles.map + " h-full w-full"}
			zoomControl={false}
		>
			<TileLayer
				attribution={t("mapAttribution")}
				url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
			/>
			<MovableMapObject asset={asset} />
		</MapContainer>
	);
};
