<template>
  <NuxtLayout name="map">
    <template #sidebar>
      <CatalogMapSidebar
        :title="t('catalogMap.hubsTab')"
        :back-link="localePath('/select-location')"
        :back-label="t('catalogMap.actions.list_view')"
        :items-count="items.length"
        :filters="filters"
        :selected-filter="selectedFilter"
        :loading="isLoading"
        :empty-text="t('catalogMap.noHubs')"
        @update:selected-filter="selectedFilter = $event"
      >
        <template #cards>
          <HubCard
            v-for="(hub, index) in items"
            :key="hub.uuid ?? index"
            :hub="hub"
            selectable
            :is-selected="selectedItemId === hub.uuid"
            @select="selectItem(hub)"
          />
        </template>
      </CatalogMapSidebar>
    </template>

    <CatalogMap
      ref="mapRef"
      map-id="select-location-fullscreen-map"
      :items="itemsWithCoords"
      point-color="#10b981"
      @select-item="onMapSelectItem"
    />
  </NuxtLayout>
</template>

<script setup lang="ts">
import { useLocationStore } from '~/stores/location'
import type { CatalogHubItem, CatalogNearestHubItem } from '~/composables/useCatalogHubs'

definePageMeta({
  layout: false
})

const router = useRouter()
const route = useRoute()
const { t } = useI18n()
const localePath = useLocalePath()
const locationStore = useLocationStore()
const searchStore = useSearchStore()
const isSearchMode = computed(() => route.query.mode === 'search')

const {
  items,
  selectedFilter,
  filters,
  isLoading,
  itemsWithCoords,
  init
} = useCatalogHubs()

await init()

const mapRef = ref<{ flyTo: (lat: number, lng: number, zoom?: number) => void } | null>(null)
const selectedItemId = ref<string | null>(null)

const selectItem = async (item: CatalogHubItem | CatalogNearestHubItem) => {
  if (!item.uuid) return
  selectedItemId.value = item.uuid

  if (item.latitude && item.longitude) {
    mapRef.value?.flyTo(item.latitude, item.longitude, 8)
  }

  // Selection logic
  if (isSearchMode.value) {
    searchStore.setLocation(item.name ?? '')
    searchStore.setLocationUuid(item.uuid)
    if (route.query.after === 'request' && searchStore.searchForm.productUuid && searchStore.searchForm.locationUuid) {
      const query: Record<string, string> = {
        product: searchStore.searchForm.productUuid,
        hub: searchStore.searchForm.locationUuid
      }
      if (searchStore.searchForm.quantity) query.quantity = String(searchStore.searchForm.quantity)

      router.push({
        path: `/catalog`,
        query
      })
      return
    }
    router.push(localePath('/select-location'))
    return
  }

  const success = await locationStore.select('hub', item.uuid, item.name ?? '', item.latitude ?? 0, item.longitude ?? 0)
  if (success) router.push(localePath('/select-location'))
}

const onMapSelectItem = (uuid: string) => {
  const item = items.value.find(h => h.uuid === uuid)
  if (item) selectItem(item)
}
</script>
