---
import Layout from 'layouts/PageLayout.astro'
import 'leaflet/dist/leaflet.css'
import FormContainer from 'components/ui/Form.astro'
import Input from 'components/Input.astro'
import Button from 'components/ui/Button.astro'

const metadata = {
  title: 'Maps',
  ignoreTitleTemplate: true,
}
---

<Layout metadata={metadata}>

  <div class="flex flex-row justify-between align-center max-w-xl mx-auto rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-slate-900 shadow p-4 sm:p-6 lg:p-8 w-full">
    <Input type='text' name='search' placeholder='Paris' divClass='grow mr-4'/>
    <Button variant="primary" id='search-btn' class='grow-4'>rechercher</Button>
  </div>

  <div class="w-full h-96" id="map" />


</Layout>

<script>
  import L, { geoJSON, Icon, type LatLngTuple } from 'leaflet'
  import markerShadow from "leaflet/dist/images/marker-shadow.png"
  import markerIcon from "leaflet/dist/images/marker-icon.png"

  const btn = document.querySelector('#search-btn')
  const input = document.querySelector<HTMLInputElement>('#search')
  const icon = {icon: new L.Icon({iconUrl: markerIcon.src, shadowUrl: markerShadow.src, iconAnchor: [13,41]})}

  // const BACK_URL = "https://drink-tweb.cb85.fr/"
  const BACK_URL = "http://localhost:3001/"

  let mapsCenter : L.LatLngTuple

  const map = L.map('map', {
    center: [51.5, -0.09],
    zoom: 13,
    preferCanvas: true
  })
  L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
    attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
  }).addTo(map)

  let marker = L.marker([51.5, -0.09],icon).addTo(map)
  marker.bindPopup("test")


  function search() {
    const params: URLSearchParams = new URLSearchParams();
    params.append("name", input!.value)

    fetch(`${BACK_URL}otm/city?${params.toString()}`,{method: 'GET',headers: {'Content-Type': 'application/json'}}).then(function (response) {
      // The API call was successful!
      return response.json();
    }).then(function (data) {
      console.log(data);
      mapsCenter = [data.lat, data.lon]
      marker.setLatLng(mapsCenter)
      map.setView(mapsCenter)
      data.features.forEach(element => {
        console.log(element)
        const poiMarker = L.marker([element.geometry.coordinates[1],element.geometry.coordinates[0]],icon).bindPopup(element.properties)
        poiMarker.addTo(map)
      });
    }).catch(function (err) {
      console.warn('Something went wrong.', err);
    });
  }

  btn?.addEventListener('click',search)
  input?.addEventListener('keypress',(e) =>{
    if(e.key == 'Enter'){
      search()
    }
  })

    // marker.setLatLng(mapsCenter)
    // map.setView(mapsCenter)
    // const mark2 = map.getBounds().getNorthWest()
    // const mark3 = map.getBounds().getSouthEast()
    // let marker2 = L.marker(mark2,icon).addTo(map)
    // let marker3 = L.marker(mark3,icon).addTo(map)

</script>
