<template>
  <div v-if="coords" class="delivery">
    <div class="delivery__sidebar">
      <div
        v-for="point in yandexPvz?.points"
        :key="point.id"
        class="pickup-point-item"
        @click="onPickupClick(point)"
      >
        <h3>Yandex</h3>
        {{ `${point?.address?.street} ${point?.address?.house}` }}
        <Icon class="pickup-point-item__action" name="lucide:chevron-right" />
      </div>
    </div>
    <PvzMap ref="mapRef" :pickup-points="yandexPvz?.points" />
  </div>
</template>

<script setup lang="ts">
import { useGeolocation } from '@vueuse/core'
import { onMounted, ref } from 'vue'
import PvzMap from '~/components/PvzMap.vue'

const yandexPvz = ref('')
const { coords } = useGeolocation()
const city = ref('')

const waitForCoords = () =>
  new Promise<void>((resolve) => {
    const stop = watch(coords, (newCoords) => {
      if (newCoords.latitude && newCoords.longitude) {
        stop()
        resolve()
      }
    })
  })

onMounted(async () => {
  await waitForCoords()

  const response = await fetch(
    `https://nominatim.openstreetmap.org/reverse?lat=${coords.value.latitude}&lon=${coords.value.longitude}&format=json&accept-language=ru`,
  )
  const openstreetmap = await response.json()

  const { data: yandexLocation } = await useFetch('/api/yandex_location', {
    method: 'POST',
    body: {
      location: openstreetmap?.address?.city,
    },
  })

  const { data: yandexPvzApi } = await useFetch('/api/yandex_pvz', {
    method: 'POST',
    body: {
      geo_id: yandexLocation?.value?.variants[0]?.geo_id,
    },
  })

  yandexPvz.value = yandexPvzApi.value
})

const mapRef = ref<InstanceType<typeof PvzMap> | null>(null)

const onPickupClick = (point: any) => {
  const lat = point?.position?.latitude
  const lon = point?.position?.longitude
  if (typeof lat === 'number' && typeof lon === 'number') {
    mapRef.value?.centerMap(lat, lon)
  }
}

definePageMeta({
  layout: 'checkout',
})
</script>

<style lang="scss">
.delivery {
  display: flex;
  flex-direction: row;

  &__sidebar {
    width: 410px;
    height: calc(100dvh - 54px);
    flex-shrink: 0;
    overflow-y: auto;
  }
}

.pickup-point-item {
  position: relative;
  width: 400px;
  height: 100px;
  padding: 24px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  cursor: pointer;

  &__action {
    position: absolute;
    right: 20px;
    top: 40px;
  }
}
</style>
