import { Button } from '@mui/material';
import { MapContainer, TileLayer, Marker, Tooltip } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';

const containerStyle = {
  width: '100%',
  height: 'calc(100vh - 150px)'
};

// Green marker
const GreenIcon = 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],
  shadowSize: [41, 41]
});

// Red marker
const RedIcon = 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],
  shadowSize: [41, 41]
});

export default function RiderLocationMap({ riderLocations }) {
  console.log('riderLocations', riderLocations);

  const center = [Number(riderLocations?.[0]?.latitude || 11.0056), Number(riderLocations?.[0]?.longitude || 76.9661)];

  return (
    <MapContainer center={center} zoom={12} style={containerStyle}>
      <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" attribution="&copy; OpenStreetMap contributors" />
      {riderLocations &&
        riderLocations.map((r, index) => {
          const lat = Number(r.latitude);
          const lng = Number(r.longitude);
          return (
            <Marker key={index} position={[lat, lng]} icon={r.status == 'active' ? GreenIcon : RedIcon}>
              <Tooltip permanent direction="top" offset={[0, -35]} opacity={1} className="rider-location-tooltip">
                <Button variant="contained" color="primary" size="small">
                  {` ${r.username} `}
                  <br />
                  {`(${r.orderid || ''})   `}
                </Button>
              </Tooltip>
            </Marker>
          );
        })}
    </MapContainer>
  );
}
