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

const MapWithRoute = ({ coordinates, additionalProps }) => {
  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 limeOptions = { color: 'blue', weight: 10 };
  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}>
            <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>
            {/* <Popup>{`Pickup Point ${dayjs(additionalProps.riderStart).utc().format('DD-MM-YYYY')}  (${dayjs(additionalProps.riderStart)
              .utc()
              .format('hh:mm A')})   `}</Popup> */}
          </Marker>
          <Marker position={end}>
            <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>
            {/* <Popup>{`Drop Point ${dayjs(additionalProps.riderEnd).utc().format('DD-MM-YYYY')}  (${dayjs(additionalProps.riderEnd)
              .utc()
              .format('hh:mm A')})   `}</Popup> */}
          </Marker>
          {/* <Marker position={center}>
            <Popup>Center Point</Popup>
          </Marker> */}
          <Polyline pathOptions={limeOptions} positions={coordinates} />
        </MapContainer>
      </div>
    )
  );
};

export default MapWithRoute;
