import React from 'react';
import { useMap, useMapsLibrary } from '@vis.gl/react-google-maps';

interface DrawingManagerProps {
    onBoxDrawn: (bounds: any) => void;
}

const DrawingManager: React.FC<DrawingManagerProps> = ({ onBoxDrawn }) => {
    const mapsLibrary = useMapsLibrary('drawing');
    const map = useMap();

    React.useEffect(() => {
        if (!mapsLibrary || !map) {
            return;
        }

        const drawingManager = new mapsLibrary.drawing.DrawingManager({
            drawingControl: true,
            drawingControlOptions: {
                position: window.google.maps.ControlPosition.TOP_CENTER,
                drawingModes: [window.google.maps.drawing.OverlayType.RECTANGLE],
            },
            rectangleOptions: {
                fillColor: '#FF0000',
                fillOpacity: 0.1,
                strokeWeight: 2,
                strokeColor: '#FF0000',
                clickable: false,
                editable: true,
                zIndex: 1,
            },
        });
        drawingManager.setMap(map);

        const listener = mapsLibrary.event.addListener(drawingManager, 'rectanglecomplete', (rectangle: google.maps.Rectangle) => {
            const bounds = rectangle.getBounds();
            if (bounds) {
                onBoxDrawn({
                    ne: { lat: bounds.getNorthEast().lat(), lng: bounds.getNorthEast().lng() },
                    sw: { lat: bounds.getSouthWest().lat(), lng: bounds.getSouthWest().lng() }
                });
            }
            drawingManager.setDrawingMode(null);
            setTimeout(() => {
                rectangle.setMap(null);
            }, 5000);
        });

        return () => {
            mapsLibrary.event.removeListener(listener);
            drawingManager.setMap(null);
        };
    }, [mapsLibrary, map, onBoxDrawn]);

    return null;
};

export default DrawingManager;