import { useEffect, useRef } from "react";
import { Marker, Polyline, useMap } from "react-leaflet";
import L from "leaflet";
import polyline from "@mapbox/polyline";
import SourceIcon from "@/assets/images/source-icon.svg";
import DestIcon from "@/assets/images/destination-icon.svg";

const ShowRoute = ({ area }) => {
    const map = useMap();
    const defaultIconSize = [35, 35];

    const createCustomIcon = (size, iconUrl) => {
        return L.icon({
            iconUrl: iconUrl,
            iconSize: size,
            iconAnchor: [size[0] / 2, size[1]],
            popupAnchor: [0, -size[1]],
        });
    };

    useEffect(() => {
        if (coords.length > 0) {
            map.flyToBounds(coords, { padding: [50, 50], duration: 1.5 });
        }
    }, [area]);
    const sourceIcon = createCustomIcon(defaultIconSize, SourceIcon.src);
    const destIcon = createCustomIcon(defaultIconSize, DestIcon.src);

    if (!area) return null;
    const coords = polyline.decode(area, 6);

    if (coords.length === 0) return null;

    const sourcePosition = coords[0];
    const destPosition = coords[coords.length - 1];

    return (
        <>
            <Polyline positions={coords} color="#015688" weight={7} opacity={1} />
            <Marker position={sourcePosition} icon={sourceIcon} />
            <Marker position={destPosition} icon={destIcon} />
        </>
    );
};

export default ShowRoute;
