import React, { useEffect, useRef } from 'react';
import { LoadScriptNext, GoogleMap } from '@react-google-maps/api';

const containerStyle = {
  width: '100%',
  height: '90vh'
};

const MapWithRouteGoogle = ({ coordinates, additionalProps, setMapOpen }) => {
  const mapRef = useRef(null);

  /** Convert coordinates to numbers */
  const numericCoordinates = coordinates
    .map((c) => {
      const lat = Number(c.lat);
      const lng = Number(c.lng);
      return isNaN(lat) || isNaN(lng) ? null : { lat, lng };
    })
    .filter(Boolean);

  if (numericCoordinates.length < 2) {
    return <div>No route data available</div>;
  }

  const start = numericCoordinates[0];
  const end = numericCoordinates[numericCoordinates.length - 1];

  /** Map loaded callback */
  const onMapLoad = (map) => {
    // draw markers
    new window.google.maps.Marker({
      position: start,
      map,
      label: 'S',
      title: `Start: ${additionalProps?.riderStart}`
    });

    new window.google.maps.Marker({
      position: end,
      map,
      label: 'E',
      title: `End: ${additionalProps?.riderEnd}`
    });

    // draw rider route (point-to-point)
    const route = new window.google.maps.Polyline({
      path: numericCoordinates,
      geodesic: false,
      strokeColor: '#1A73E8',
      strokeOpacity: 1.0,
      strokeWeight: 4
    });

    route.setMap(map);

    // auto fit
    const bounds = new window.google.maps.LatLngBounds();
    numericCoordinates.forEach((p) => bounds.extend(p));
    map.fitBounds(bounds);
  };

  return (
    <>
      <button
        onClick={() => setMapOpen(false)}
        style={{
          position: 'absolute',
          top: 10,
          right: 10,
          zIndex: 999,
          padding: '6px 12px',
          background: '#1A73E8',
          color: 'white',
          borderRadius: 6,
          cursor: 'pointer',
          border: 'none'
        }}
      >
        Close
      </button>

      <LoadScriptNext googleMapsApiKey={process.env.REACT_APP_GOOGLE_MAPS_API_KEY}>
        <GoogleMap mapContainerStyle={containerStyle} center={start} zoom={14} onLoad={onMapLoad}>
          {/* Polyline and markers added via onLoad */}
        </GoogleMap>
      </LoadScriptNext>
    </>
  );
};

export default MapWithRouteGoogle;
