import { memo, useEffect, useState } from "react";
import { OverlayViewF } from "@/components/map";
import UserLocationLineIcon from "remixicon-react/UserLocationLineIcon";
import FlagLineIcon from "remixicon-react/FlagLineIcon";
import { Price } from "@/components/price";
import dynamic from "next/dynamic";
import type { Map as MapLibreMap } from "maplibre-gl";
import maplibregl from "maplibre-gl";

interface ParcelMapProps {
  locationTo: {
    lat: number;
    lng: number;
  };
  locationFrom: {
    lat: number;
    lng: number;
  };
  price?: number;
}

const Map = dynamic(() =>
  import("@/components/map").then((component) => ({ default: component.Map }))
);

export const ParcelMap = memo(({ locationTo, locationFrom, price }: ParcelMapProps) => {
  const [map, setMap] = useState<MapLibreMap>();

  useEffect(() => {
    if (map) {
      const bounds = new maplibregl.LngLatBounds();
      bounds.extend([locationTo.lng, locationTo.lat]);
      bounds.extend([locationFrom.lng, locationFrom.lat]);
      map.fitBounds(bounds, { padding: 40 });
    }
  }, [map, locationFrom, locationTo]);

  return (
    <Map
      onLoad={(currentMap) => setMap(currentMap)}
      containerStyles={{
        width: "100%",
        height: "100%",
        maxHeight: "600px",
        borderRadius: "15px",
      }}
    >
      <OverlayViewF position={locationFrom}>
        <div className="bg-white dark:bg-dark w-11 h-11 rounded-xl flex items-center justify-center">
          <UserLocationLineIcon />
        </div>
      </OverlayViewF>
      <OverlayViewF position={locationTo}>
        <div>
          <div className="bg-white dark:bg-dark w-11 h-11 rounded-xl flex items-center justify-center relative">
            {!!price && (
              <div className="absolute -top-6 left-1/2 -translate-x-1/2 whitespace-nowrap bg-primary text-sm px-2 py-1 rounded-full text-white">
                <Price number={price} />
              </div>
            )}
            <FlagLineIcon />
          </div>
        </div>
      </OverlayViewF>
    </Map>
  );
});
