import { useRef } from 'react';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import 'leaflet-routing-machine/dist/leaflet-routing-machine.css';
import 'leaflet-routing-machine';

const projects = [
  { name: "Barcelona", coords: [41.3851, 2.1734], role: "Main Office" },
  { name: "New York", coords: [40.7128, -74.006], role: "AI-Driven Analytics Project" },
  { name: "Singapore", coords: [1.3521, 103.8198], role: "FinTech Automation" },
  { name: "Brussels", coords: [50.8503, 4.3517], role: "EU Digital Transformation" },
  { name: "Berlin", coords: [52.52, 13.405], role: "Industrial IoT Solution" },
  { name: "Buenos Aires", coords: [-34.6037, -58.3816], role: "Supply Chain Optimization" }
];

// Fix for the marker icon issue in react-leaflet
delete (L.Icon.Default.prototype as any)._getIconUrl;
L.Icon.Default.mergeOptions({
  iconRetinaUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon-2x.png",
  iconUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon.png",
  shadowUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png",
});

export default function WorldMap({ className = "" }) {
  const mapRef = useRef<L.Map | null>(null);
  const barcelona = projects[0].coords;

  return (
    <div className={`${className} relative`} style={{ height: "500px" }}>
      <MapContainer
        center={[20, 0]}
        zoom={2}
        whenReady={(map: L.Map) => { mapRef.current = map.target; }}
        style={{ height: "100%", width: "100%" }}
        className="rounded-xl"
      >
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        />
        {projects.map((project, index) => {
          const isMainOffice = index === 0;
          return (
            <Marker 
              key={index} 
              position={[project.coords[0], project.coords[1]]}
            >
              <Popup>
                <div className="text-sm">
                  <strong className="block text-blue-900">{project.name}</strong>
                  <span className="text-gray-600">
                    {isMainOffice ? "ORKEI SOFTWARE Main Office" : project.role}
                  </span>
                </div>
              </Popup>
            </Marker>
          );
        })}
      </MapContainer>
    </div>
  );
}