import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { useEffect, useRef } from 'react';
import { fetchGeoPoints } from '../api';
import { usePolling } from '../hooks/usePolling';
import './Map.css';

export function MapPage() {
  const mapRef = useRef<L.Map | null>(null);
  const layerRef = useRef<L.LayerGroup | null>(null);
  const provinceLayerRef = useRef<L.GeoJSON | null>(null);
  const cityLayerRef = useRef<L.GeoJSON | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const { data: points } = usePolling(fetchGeoPoints, 15000);

  useEffect(() => {
    if (!containerRef.current || mapRef.current) return;

    const map = L.map(containerRef.current, {
      center: [35, 105],
      zoom: 4,
      zoomControl: true,
      attributionControl: false,
      minZoom: 3,
      maxZoom: 12,
    });

    containerRef.current.style.background = '#0d1117';

    const provinceStyle = {
      color: '#00d4ff',
      weight: 1,
      fillColor: '#0d2233',
      fillOpacity: 0.8,
    };

    const cityStyle = {
      color: '#00d4ff',
      weight: 0.5,
      fillColor: '#0d2233',
      fillOpacity: 0.8,
    };

    const addLabels = (geojson: any, layer: L.GeoJSON, labelGroup: L.LayerGroup) => {
      geojson.features.forEach((feature: any) => {
        const name = feature.properties?.name;
        const center = feature.properties?.centroid || feature.properties?.center;
        if (!name || !center) return;
        const marker = L.marker([center[1], center[0]], {
          icon: L.divIcon({
            className: 'geo-label',
            html: `<span>${name}</span>`,
            iconSize: undefined,
          }),
          interactive: false,
        });
        labelGroup.addLayer(marker);
      });
    };

    // 加载省级
    fetch('/china.json')
      .then((r) => r.json())
      .then((geojson) => {
        const labelGroup = L.layerGroup();
        provinceLayerRef.current = L.geoJSON(geojson, { style: provinceStyle }).addTo(map);
        addLabels(geojson, provinceLayerRef.current, labelGroup);
        labelGroup.addTo(map);
        // 缩放时同步显示/隐藏省级标签
        (provinceLayerRef.current as any)._labelGroup = labelGroup;
      });

    // 加载市级（默认隐藏）
    fetch('/china-city.json')
      .then((r) => r.json())
      .then((geojson) => {
        const labelGroup = L.layerGroup();
        cityLayerRef.current = L.geoJSON(geojson, { style: cityStyle });
        addLabels(geojson, cityLayerRef.current, labelGroup);
        (cityLayerRef.current as any)._labelGroup = labelGroup;
      });

    // 缩放切换：zoom >= 6 显示市级，否则显示省级
    map.on('zoomend', () => {
      const z = map.getZoom();
      if (!provinceLayerRef.current || !cityLayerRef.current) return;
      const provLabels = (provinceLayerRef.current as any)._labelGroup as L.LayerGroup | undefined;
      const cityLabels = (cityLayerRef.current as any)._labelGroup as L.LayerGroup | undefined;
      if (z >= 6) {
        if (map.hasLayer(provinceLayerRef.current)) map.removeLayer(provinceLayerRef.current);
        if (provLabels && map.hasLayer(provLabels)) map.removeLayer(provLabels);
        if (!map.hasLayer(cityLayerRef.current)) cityLayerRef.current.addTo(map);
        if (cityLabels && !map.hasLayer(cityLabels)) cityLabels.addTo(map);
      } else {
        if (map.hasLayer(cityLayerRef.current)) map.removeLayer(cityLayerRef.current);
        if (cityLabels && map.hasLayer(cityLabels)) map.removeLayer(cityLabels);
        if (!map.hasLayer(provinceLayerRef.current)) provinceLayerRef.current.addTo(map);
        if (provLabels && !map.hasLayer(provLabels)) provLabels.addTo(map);
      }
    });

    layerRef.current = L.layerGroup().addTo(map);
    mapRef.current = map;

    return () => {
      map.remove();
      mapRef.current = null;
    };
  }, []);

  // 更新打点
  useEffect(() => {
    if (!layerRef.current || !points) return;
    layerRef.current.clearLayers();

    points.forEach((pt) => {
      const circle = L.circleMarker([pt.latitude, pt.longitude], {
        radius: Math.min(4 + Math.log1p(pt.hit_count) * 2, 18),
        color: '#00d4ff',
        fillColor: '#00d4ff',
        fillOpacity: 0.6,
        weight: 1,
      });
      circle.bindTooltip(
        `<b>${pt.country}</b>${pt.city !== 'Unknown' ? `, ${pt.city}` : ''}<br/>Hits: ${pt.hit_count}`,
        { className: 'map-tooltip' }
      );
      circle.addTo(layerRef.current!);
    });
  }, [points]);

  return (
    <div className="map-page">
      <header className="map-header">
        <span className="map-title">CHINA_SCAN_MAP</span>
        {points && (
          <span className="map-count">{points.length} ACTIVE NODES</span>
        )}
      </header>
      <div ref={containerRef} className="map-container" />
    </div>
  );
}
