"use client";

import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import L from "leaflet";
import { useEffect, useMemo } from "react";

interface Facility {
  name: string;
  location: string;
  tags: string[];
  linkedin: string;
}

interface FacilityMapProps {
  facilities: Facility[];
  isFiltered?: boolean;
}

const facilityCoordinates: Record<
  string,
  { coords: [number, number]; color: string }
> = {
  "A-FLOW": {
    coords: [14.292131, 121.069375],
    color: "#333333",
  },
  "Digital Edge Philippines": {
    coords: [14.272448, 121.065587],
    color: "#333333",
  },
  VITRO: {
    coords: [14.268573, 121.081142],
    color: "#333333",
  },
  "ST Telemedia Global Data Centres Philippines": {
    coords: [14.694576, 121.06819],
    color: "#333333",
  },
  "Digital Halo": {
    coords: [14.589835531242633, 121.137952049625],
    color: "#333333",
  },
  "YCO Cloud": {
    coords: [14.034813843094504, 121.14723051903385],
    color: "#333333",
  },
};

const createCustomIcon = (color: string) => {
  return L.divIcon({
    className: "custom-marker",
    html: `
      <div style="
        background-color: ${color};
        width: 30px;
        height: 30px;
        border-radius: 50% 50% 50% 0;
        transform: rotate(-45deg);
        border: 3px solid white;
        box-shadow: 0 2px 8px rgba(0,0,0,0.3);
      ">
        <div style="
          width: 12px;
          height: 12px;
          background-color: white;
          border-radius: 50%;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        "></div>
      </div>
    `,
    iconSize: [30, 30],
    iconAnchor: [15, 30],
    popupAnchor: [0, -30],
  });
};

export default function FacilityMap({
  facilities,
  isFiltered = false,
}: FacilityMapProps) {
  useEffect(() => {
    delete (L.Icon.Default.prototype as any)._getIconUrl;
    L.Icon.Default.mergeOptions({
      iconRetinaUrl: "/images/marker-icon-2x.png",
      iconUrl: "/images/marker-icon.png",
      shadowUrl: "/images/marker-shadow.png",
    });
  }, []);

  const facilitiesWithCoords = useMemo(
    () =>
      facilities
        .map((facility) => {
          const coords = facilityCoordinates[facility.name];
          if (!coords) return null;
          return {
            ...facility,
            coords: coords.coords,
            color: coords.color,
          };
        })
        .filter((f) => f !== null),
    [facilities],
  );

  return (
    <div className="w-full h-[300px] sm:h-[400px] md:h-[500px] rounded-lg overflow-hidden relative">
      <MapContainer
        center={[14.0, 121.0]}
        zoom={9}
        scrollWheelZoom={true}
        className="w-full h-full"
        style={{ zIndex: 0 }}
      >
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        {facilitiesWithCoords.map(
          (facility, idx) =>
            facility && (
              <Marker
                key={idx}
                position={facility.coords}
                icon={createCustomIcon(facility.color)}
              >
                <Popup>
                  <div className="font-montserrat">
                    <h3 className="font-bold text-[#333333] text-xs sm:text-sm mb-1">
                      {facility.name}
                    </h3>
                    <p className="text-[10px] sm:text-xs text-[#535353]">
                      {facility.location}
                    </p>
                  </div>
                </Popup>
              </Marker>
            ),
        )}
      </MapContainer>

      {isFiltered && facilitiesWithCoords.length > 0 && (
        <div
          className="absolute bottom-2 left-2 sm:bottom-4 sm:left-4 bg-white p-2.5 sm:p-3 md:p-4 rounded-lg shadow-lg max-w-[160px] sm:max-w-xs"
          style={{ zIndex: 1000 }}
        >
          <h3 className="font-bold font-montserrat text-[#333333] text-xs sm:text-sm mb-1.5 sm:mb-2">
            Filtered Results
          </h3>
          <div className="space-y-1 sm:space-y-2 text-[10px] sm:text-xs md:text-sm font-montserrat text-[#535353]">
            {facilitiesWithCoords.map(
              (facility, idx) =>
                facility && (
                  <div key={idx} className="flex items-center gap-1.5 sm:gap-2">
                    <div className="w-1.5 h-1.5 sm:w-2 sm:h-2 rounded-full bg-[#333333] shrink-0"></div>
                    <span className="line-clamp-1">{facility.name}</span>
                  </div>
                ),
            )}
          </div>
        </div>
      )}
    </div>
  );
}
