import { Spin } from "antd";
import { useEffect, useRef, useState } from "react";
import { dynamicLoadJs } from "zy-react-library/utils";

function StaticMapViewer(props) {
  const mapContainerRef = useRef(null);
  const mapInstanceRef = useRef(null);
  const [loading, setLoading] = useState(true);
  const longitude = props.longitude;
  const latitude = props.latitude;

  useEffect(() => {
    const originalRemoveChild = Node.prototype.removeChild;
    Node.prototype.removeChild = function (child) {
      try {
        if (this.contains(child)) {
          return originalRemoveChild.call(this, child);
        }
        return child;
      }
      catch (error) {
        if (error.message && error.message.includes("removeChild")) {
          return child;
        }
        throw error;
      }
    };

    const initMap = async () => {
      if (!window.BMapGL) {
        await dynamicLoadJs(`https://api.map.baidu.com/api?v=1.0&type=webgl&ak=${window.mapBaiDuKey}&callback=initialize`);
      }

      if (!mapContainerRef.current || mapInstanceRef.current) {
        setLoading(false);
        return;
      }

      try {
        const map = new window.BMapGL.Map(mapContainerRef.current, {
          enableScrollWheelZoom: true,
          enableDragging: true,
          enableDoubleClickZoom: true,
          enableKeyboard: true,
          enableInertialDragging: true,
          enableContinuousZoom: true,
        });

        mapInstanceRef.current = map;

        const centerLng = longitude || window.mapLongitude;
        const centerLat = latitude || window.mapLatitude;
        map.centerAndZoom(new window.BMapGL.Point(centerLng, centerLat), 16);

        if (longitude && latitude) {
          const point = new window.BMapGL.Point(longitude, latitude);
          const marker = new window.BMapGL.Marker(point, {
            draggable: false,
            enableMassClear: true,
          });
          map.addOverlay(marker);
        }

        setLoading(false);
      }
      catch {
        setLoading(false);
      }
    };

    const timer = setTimeout(initMap, 500);

    return () => {
      clearTimeout(timer);
      const map = mapInstanceRef.current;
      if (map) {
        try {
          map.destroy();
        }
        catch {
        }
      }
      mapInstanceRef.current = null;
      Node.prototype.removeChild = originalRemoveChild;
    };
  }, [latitude, longitude]);

  return (
    <div
      ref={mapContainerRef}
      style={{
        width: "100%",
        height: 260,
        position: "relative",
        border: "1px solid #f0f0f0",
        borderRadius: 4,
        overflow: "hidden",
      }}
    >
      {loading && (
        <Spin
          size="large"
          tip="地图加载中..."
          spinning
          style={{
            position: "absolute",
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            background: "rgba(255, 255, 255, 0.8)",
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            zIndex: 10,
          }}
        />
      )}
    </div>
  );
}

export default StaticMapViewer;
