import React, { useState, useEffect, useRef } from "react";

import { Box, Card } from "@mantine/core";

import about from "../content/about.json";

import { Feature, Map, View, Overlay } from "ol";
import TileLayer from "ol/layer/Tile";
import OSM from "ol/source/OSM";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Style from "ol/style/Style";
import Point from "ol/geom/Point";
import { fromLonLat } from "ol/proj";

export default function OfficeMap() {
  const [map, setMap] = useState();
  const mapElement = useRef();
  const overlayElement = useRef();

  const lat = 47.378532;
  const lon = 8.5488535;
  const zoomLevel = 17;

  const osmLayer = new TileLayer({
    preload: Infinity,
    source: new OSM(),
  });

  const iconFeature = new Feature({
    geometry: new Point(fromLonLat([lon, lat])),
    name: "TheAlternative Office",
  });

  const vectorSource = new VectorSource({
    features: [iconFeature],
  });

  const vectorLayer = new VectorLayer({
    source: vectorSource,
  });

  const initialMap = new Map({
    layers: [osmLayer, vectorLayer],
    view: new View({
      center: fromLonLat([lon, lat]),
      zoom: zoomLevel,
    }),
  });

  useEffect(() => {
    initialMap.setTarget(mapElement.current);
    const overlay = new Overlay({
      element: overlayElement.current,
      position: fromLonLat([lon, lat]),
      positioning: "bottom-center",
      stopEvent: false,
    });
    initialMap.addOverlay(overlay);
    setMap(initialMap);
  }, []);

  return (
    <Card
      shadow="md"
      style={{
        width: "100%",
        paddingTop: "100%",
        position: "relative",
      }}
      withBorder
    >
      <Box
        style={{
          position: "absolute",
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          display: "flex",
          alignItems: "stretch",
          flexDirection: "column",
        }}
      >
        <div
          style={{ height: "100vh", width: "100%" }}
          ref={mapElement}
          className="map-container"
        />
        <div
          ref={overlayElement}
          id="marker"
          style={{
            border: "1px solid #000",
            borderRadius: ".2rem",
            backgroundColor: "#fff",
            opacity: "0.9",
            padding: "10px",
            marginBottom: "10px",
          }}
        >
          <b style={{ color: "black" }}>TheAlternative</b>
          {about.address.map((line, i) => (
            <p key={i} style={{ color: "black", marginBottom: 0 }}>
              {line}
            </p>
          ))}
        </div>
      </Box>
    </Card>
  );
}