import React, { useEffect, useRef } from 'react';
import { MapManager } from './BaseMap';

interface VietNamMapProps {
  style?: React.CSSProperties;
  onFeatureClick?: (feature: any) => void;
  onFeatureSelect?: (feature: any) => void;
  onFeaturesClick?: (features: any[]) => void;
  onError?: (error: Error) => void;
  mapManager?: MapManager;
}

const VietNamMap: React.FC<VietNamMapProps> = React.memo(
  ({
    style = {},
    onFeatureClick,
    onFeatureSelect,
    onFeaturesClick,
    onError,
    mapManager,
  }) => {
    const mapRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
      console.log('useEffect in VietNamMap triggered');
      let manager = mapManager;

      if (!manager) {
        manager = new MapManager(mapRef, {
          onFeatureClick,
          onFeatureSelect,
          onFeaturesClick,
        });
      }

      const initialize = (retryCount = 0, maxRetries = 5) => {
        if (mapRef.current) {
          manager!.mapRef = mapRef;
          if (!manager!.map) {
            manager!.initializeMap();
            console.log(
              'Initialized new MapManager instance at',
              new Date().toLocaleTimeString(),
            );
          }
        } else if (retryCount < maxRetries) {
          console.error('mapRef.current is not ready, retrying...');
          setTimeout(() => initialize(retryCount + 1, maxRetries), 100);
        } else {
          console.error('Max retries reached, failed to initialize map');
          onError?.(new Error('Failed to initialize map: mapRef not ready'));
        }
      };

      initialize();

      return () => {
        console.log('Cleanup in VietNamMap triggered');
        // Không gọi destroy ở đây để tránh phá hủy bản đồ không cần thiết
      };
    }, [mapManager, onFeatureClick, onFeatureSelect, onFeaturesClick, onError]);

    return (
      <div style={{ position: 'relative' }}>
        <div ref={mapRef} style={{ ...style }} />
      </div>
    );
  },
);

export default VietNamMap;
export { MapManager };
