import React, { useEffect, useRef } from "react";
import {
  MapContainer,
  TileLayer,
  Marker,
  Polyline,
  Tooltip,
} from "react-leaflet";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import dayjs from "dayjs";
var utc = require("dayjs/plugin/utc");
dayjs.extend(utc);

// Define custom icons for start and end markers
const startIcon = new L.Icon({
  iconUrl:
    "https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png",
  shadowUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png",
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  shadowSize: [41, 41],
});

const endIcon = new L.Icon({
  iconUrl:
    "https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png",
  shadowUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png",
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  shadowSize: [41, 41],
});

const MapWithRoute = ({ coordinates, additionalProps }) => {
  console.log("coordinates", coordinates);
  console.log(additionalProps.riderStart);
  console.log(additionalProps.riderEnd);
  const mapRef = useRef(null);

  useEffect(() => {
    if (mapRef.current && coordinates.length > 0) {
      const bounds = calculateBounds(coordinates);
      mapRef.current.fitBounds(bounds);
    }
  }, [coordinates]);

  const calculateBounds = (coords) => {
    const latitudes = coords.map((coord) => coord.lat);
    const longitudes = coords.map((coord) => coord.lng);
    const minLat = Math.min(...latitudes);
    const maxLat = Math.max(...latitudes);
    const minLng = Math.min(...longitudes);
    const maxLng = Math.max(...longitudes);
    return [
      [minLat, minLng],
      [maxLat, maxLng],
    ];
  };

  const dottedOptions = { color: "blue", weight: 8, dashArray: "4 4" };
  const length = coordinates.length;
  const midlenght = Math.round(coordinates.length / 2);
  const start = coordinates[0];
  const end = coordinates[length - 1];
  const center = coordinates[midlenght];

  return (
    coordinates &&
    coordinates.length > 0 && (
      <div id="map" style={{ width: "80vw", height: "80vh", margin: "0 auto" }}>
        <MapContainer
          center={center}
          zoom={15}
          scrollWheelZoom={false}
          style={{ height: "100%" }}
          ref={mapRef}
        >
          <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
          <Marker position={start} icon={startIcon}>
            <Tooltip hover direction="bottom">
              <span>{`Pickup Point: ${dayjs(additionalProps.riderStart)
                .utc()
                .format("DD-MM-YYYY")} (${dayjs(additionalProps.riderStart)
                .utc()
                .format("hh:mm A")})`}</span>
            </Tooltip>
          </Marker>
          <Marker position={end} icon={endIcon}>
            <Tooltip hover direction="bottom">
              <span>{`Drop Point: ${dayjs(additionalProps.riderEnd)
                .utc()
                .format("DD-MM-YYYY")} (${dayjs(additionalProps.riderEnd)
                .utc()
                .format("hh:mm A")})`}</span>
            </Tooltip>
          </Marker>

          <Polyline pathOptions={dottedOptions} positions={coordinates} />
        </MapContainer>
      </div>
    )
  );
};

export default MapWithRoute;
