import { CircularProgress } from "@mui/material";
import { Field } from "models";
import { useEffect, useState } from "react";
import Map from "react-map-gl/mapbox";
import 'mapbox-gl/dist/mapbox-gl.css';
import GeoMapLayer from "maps/mapLayers/geoMapLayer";
import { Feature, FeatureCollection } from "geojson";
import { GeometryMapping } from "models/GeometryMapping";

interface Props {
  field: Field
  squared?: boolean
  borderSpacing?: number
}

export default function FieldMinimap(props: Props) {
  const { field, squared, borderSpacing } = props
  const MAPBOX_TOKEN = import.meta.env.VITE_MAPBOX_ACCESS_TOKEN;
  const [geoCollection, setGeoCollection] = useState<FeatureCollection>();

  useEffect(()=>{
    let fieldData = field.settings.fieldGeoData
    if(fieldData){
      let fieldFeature = GeometryMapping.geoJSON(fieldData.geoShape, fieldData.shapes, fieldData.holes) as Feature;
      fieldFeature.id = fieldData.objectKey;
      fieldFeature.properties = {
        title: fieldData.title,
        objectKey: fieldData.objectKey,
        fill: fieldData.colour,
        lineWidth: fieldData.geoShape === "LineString" ? 5 : 2,
        origin: fieldData.origin
      };
      let collection: FeatureCollection = {
        type: "FeatureCollection",
        features: [fieldFeature]
      };
      setGeoCollection(collection);
    }
  },[field])
  

    return geoCollection ?
      (
      <Map
        zoom={1}
        maxBounds={
          field.fieldBounds(borderSpacing, squared)
        }
        reuseMaps
        style={{width: "100%", height: "100%"}}
        mapboxAccessToken={MAPBOX_TOKEN}
        mapStyle="mapbox://styles/mapbox/satellite-streets-v11"
      >
      <GeoMapLayer 
        objectCollection={geoCollection}
      />
      </Map>
      )
    :
    (<CircularProgress />)
}