import "./CreateReportMap.scss";
import "leaflet/dist/leaflet.css";
import {
  MapContainer,
  Marker,
  TileLayer,
  useMapEvents,
} from "react-leaflet";
import { LatLng, LatLngTuple, LeafletMouseEvent } from "leaflet";
import pin from "./assets/pin.svg";
import Image from "next/image";
import { Dispatch, SetStateAction } from "react";

interface ICreateReportMapProps {
  markers: LatLng[];
  setMarkers: Dispatch<SetStateAction<LatLng[]>>;
}

const CreateReportMap: React.FC<ICreateReportMapProps> = ({
  markers,
  setMarkers,
}: ICreateReportMapProps) => {
  const position = [42.8746, 74.606];

  const handleMapClick = (e: LeafletMouseEvent) => {
    if (markers.length <= 2) {
      setMarkers((prev) => [...prev, e.latlng]);
    }
  };

  const LocationMarker = () => {
    useMapEvents({
      click: handleMapClick,
    });

    return (
      <>
        {markers.map((marker) => (
          <Marker
            key={marker.lat}
            position={position as LatLngTuple}
          ></Marker>
        ))}
      </>
    );
  };

  return (
    <div className="create-report-map">
      <MapContainer
        center={position as LatLngTuple}
        zoom={13}
        scrollWheelZoom={false}
        className="create-report-map__container"
      >
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />

        <LocationMarker />
      </MapContainer>

      <div className="create-report-map__info">
        <h4>Как отметить участок дороги?</h4>
        <Image src={pin} alt="Pin Image" />
        <p>
          Поставьте булавку и начните рисовать участок дороги{" "}
          <span>
            (он может состоять из любого количества ломаных линий)
          </span>
        </p>

        <p>Чтобы удалить отрезок нажмите на точки повторно.</p>
      </div>
    </div>
  );
};

export default CreateReportMap;
