import React, { useState, useEffect } from "react";
import { useMap } from "../MapComponent";
import { Layer } from "ol/layer";
import { Checkbox, FormControlLabel } from "@mui/material";
import WebGLVectorTileLayer from "ol/layer/WebGLVectorTile";

const LayerControl: React.FC = () => {
  const map = useMap();
  const [layers, setLayers] = useState<Layer[]>([]);
  const [layerVisibilities, setLayerVisibilities] = useState<
    Map<Layer, boolean>
  >(new Map());

  useEffect(() => {
    if (!map) return;
    const mapLayers = map
      .getLayers()
      .getArray()
      .filter((layer) => layer instanceof WebGLVectorTileLayer) as Layer[];
    setLayers(mapLayers);
    const visible = new Map<Layer, boolean>();
    mapLayers.forEach((layer) => {
      visible.set(layer, layer.getVisible());
    });
    setLayerVisibilities(visible);
  }, [map]);

  const handleVisibilityChange = (layer: Layer, visible: boolean) => {
    layer.setVisible(visible);
    setLayerVisibilities((prev) => new Map(prev).set(layer, visible));
  };

  return (
    <div className="absolute left-4 bottom-4 bg-white rounded-md drop-shadow-lg z-10 opacity-85 hover:opacity-100 transition-opacity max-w-xs">
      <div className="ml-3 grid grid-cols-3">
        {layers.map((layer, index) => (
          <FormControlLabel
            key={index}
            control={
              <Checkbox
                checked={layerVisibilities.get(layer) ?? false}
                onChange={(e) =>
                  handleVisibilityChange(layer, e.target.checked)
                }
                size="small"
              />
            }
            label={layer.get("name") || `Layer ${index + 1}`}
            sx={{
              fontSize: "0.7rem",
              "& .MuiFormControlLabel-label": { fontSize: "0.7rem" },
            }}
          />
        ))}
      </div>
    </div>
  );
};

export default LayerControl;
