import React, { useEffect, useMemo, useRef } from 'react';
import { GoogleMap, Polyline, Marker, useJsApiLoader } from '@react-google-maps/api';

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

export default function RidersRoutes({ details }) {
  const mapRef = useRef(null);

  const { isLoaded } = useJsApiLoader({
    googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_KEY
  });

  // Convert dataset
  const routePath = useMemo(
    () =>
      details?.map((p) => ({
        lat: Number(p.latitude),
        lng: Number(p.longitude)
      })),
    [details]
  );
  const bikeIcon = {
    path: 'M12 2c-2.2 0-4 1.8-4 4v3H5l-1 2h2l3.6 7.59c.34.58.96.94 1.64.94h2.52c.68 0 1.3-.36 1.64-.94L19 11h2l-1-2h-3V6c0-2.2-1.8-4-4-4z',
    fillColor: '#9c27b0', // 🔥 purple
    fillOpacity: 1,
    strokeWeight: 0,
    scale: 1.4,
    anchor: new window.google.maps.Point(12, 24)
  };

  // Auto fit bounds
  useEffect(() => {
    if (!mapRef.current || routePath.length === 0) return;

    const bounds = new window.google.maps.LatLngBounds();
    routePath.forEach((p) => bounds.extend(p));
    mapRef.current.fitBounds(bounds);
  }, [routePath]);

  if (!isLoaded) return <div>Loading map...</div>;

  return (
    <GoogleMap mapContainerStyle={containerStyle} onLoad={(map) => (mapRef.current = map)} center={routePath[0]} zoom={16}>
      {/* Route line */}
      <Polyline
        path={routePath}
        options={{
          strokeColor: '#196fd2',
          strokeOpacity: 0.9,
          strokeWeight: 5
        }}
      />

      {/* Start marker */}
      <Marker
        position={routePath[0]}
        icon={{
          url: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
        }}
      />

      {/* End marker */}
      <Marker position={routePath[routePath.length - 1]} icon={bikeIcon} />
    </GoogleMap>
  );
}
