<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { loadModules } from 'esri-loader'
import axios from 'axios'
import type { LocationObject } from '@/interface/index/Main'

const currentPosition = ref<LocationObject>()
const poiPlaceName = ref<string>('')

// Replace ArcGIS api key
const apiKey = ref<string>(
  'AAPK4f700a4324d04e9f8a1a134e0771ac45FXWawdCl-OotFfr52gz9XKxTDJTpDzw_YYcwbmKDDyAJswf14FoPyw0qBkN64DvP'
)
const zoomMap = ref<number>(16)

async function initializeMap() {
  try {
    // Load modules of ArcGIS
    const [esriConfig, Map, MapView, Point, Graphic] = await loadModules([
      'esri/config',
      'esri/Map',
      'esri/views/MapView',
      'esri/geometry/Point',
      'esri/Graphic',
    ])

    // Set apiKey
    esriConfig.apiKey = apiKey.value

    const map = new Map({
      basemap: 'arcgis-topographic',
      // basemap: 'streets-navigation-vector',
    })

    navigator.geolocation.getCurrentPosition(async (position) => {
      const { latitude, longitude } = position.coords

      const mapView = new MapView({
        container: 'mapViewDisplay',
        map: map,
        center: {
          latitude: latitude,
          longitude: longitude,
        }, // Set the initial map center current position
        zoom: zoomMap.value,
        constraints: {
          snapToZoom: false, // Disables snapping to the zoom level
          minZoom: zoomMap.value, // Set minimum zoom level
          maxZoom: zoomMap.value, // Set maximum zoom level (same as minZoom for fixed zoom)
        },
        ui: {
          components: [], // Empty array to remove all default UI components
        },
      })

      // Update the state with the current position
      currentPosition.value = await {
        latitude: latitude,
        longitude: longitude,
      }

      // Create a Point object with the coordinates
      const point = new Point({
        longitude,
        latitude,
      })

      // Pin icon
      const pinSymbol = {
        type: 'picture-marker',
        url: 'http://maps.google.com/mapfiles/ms/icons/red.png',
        width: '32px',
        height: '32px',
      }

      // Create a graphic using the point and symbol
      const pointGraphic = new Graphic({
        geometry: point,
        symbol: pinSymbol,
      })
      mapView.graphics.add(pointGraphic)

      // Get POI place
      axios
        .get(
          'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode/',
          {
            params: {
              f: 'json', // Format JSON response
              distance: 2000,
              category: 'POI',
              location: {
                spatialReference: { wkid: 4326 },
                x: longitude,
                y: latitude,
              },
              token: apiKey.value,
            },
          }
        )
        .then((response) => {
          // console.log('poi', response.data.address)
          poiPlaceName.value = response.data.address
            ? response.data.address.PlaceName
            : 'ไม่พบข้อมูล'
        })
        .catch((error) => {
          console.error('Error fetching points of interest:', error)
        })
    })
  } catch (error) {
    console.error('Error loading the map', error)
  }
}

onMounted(async () => {
  initializeMap()
})
</script>

<template>
  <!-- Loading skeleton -->
  <div v-if="!poiPlaceName" class="q-pa-md">
    <div class="q-gutter-md">
      <q-skeleton height="35vh" width="100%" class="bg-grey-4" />
    </div>
  </div>

  <q-card v-show="poiPlaceName" bordered flat class="col-12 bg-grey-2 shadow-0">
    <div id="mapViewDisplay" style="height: 33vh"></div>

    <div
      :class="
        $q.screen.gt.xs
          ? 'q-pa-xs text-weight-medium text-grey-8'
          : ' text-weight-medium text-grey-8'
      "
    >
      พื้นที่ใกล้เคียง
      <span class="q-px-sm">:</span>
      {{ poiPlaceName }}
    </div>
  </q-card>
</template>
