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

// distance function
function distance(lat1, lng1, lat2, lng2) {
  const R = 6371;
  const dLat = (lat2 - lat1) * (Math.PI / 180);
  const dLng = (lng2 - lng1) * (Math.PI / 180);

  const a = Math.sin(dLat / 2) ** 2 + Math.cos(lat1 * (Math.PI / 180)) * Math.cos(lat2 * (Math.PI / 180)) * Math.sin(dLng / 2) ** 2;

  return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}

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

export default function RidersPinPoint({ pickCust, dropCust }) {
  // Ensure valid lat/lng
  const center = pickCust?.latitude && pickCust?.longitude ? { lat: Number(pickCust.latitude), lng: Number(pickCust.longitude) } : null;

  // If center missing, don't render map
  if (!center) return null;

  const sortedRiders = dropCust
    ?.map((r) => ({
      ...r,
      distance: distance(center.lat, center.lng, Number(r.latitude), Number(r.longitude))
    }))
    .sort((a, b) => a.distance - b.distance);

  return (
    <LoadScriptNext googleMapsApiKey={process.env.REACT_APP_GOOGLE_MAPS_API_KEY}>
      <GoogleMap mapContainerStyle={containerStyle} zoom={11} center={center}>
        <Marker position={center} icon={{ url: 'http://maps.google.com/mapfiles/ms/icons/purple-dot.png' }} />

        {sortedRiders?.map((r, index) => (
          <Marker
            key={index}
            position={{ lat: Number(r.latitude), lng: Number(r.longitude) }}
            label={{
              text: (index + 1).toString(),
              color: 'white',
              fontSize: '14px',
              fontWeight: 'bold'
            }}
          />
        ))}
      </GoogleMap>
    </LoadScriptNext>
  );
}
