<template>
  <CatalogPage
    :items="displayItems"
    :map-items="itemsWithCoords"
    :loading="isLoading"
    with-map
    map-id="addresses-map"
    point-color="#10b981"
    :selected-id="selectedAddressId"
    :hovered-id="hoveredAddressId"
    :total-count="items.length"
    @select="onSelectAddress"
    @update:hovered-id="hoveredAddressId = $event"
  >
    <template #searchBar="{ displayedCount, totalCount }">
      <CatalogSearchBar
        v-model:search-query="searchQuery"
        :active-filters="[]"
        :displayed-count="displayedCount"
        :total-count="totalCount"
        @search="onSearch"
      />
    </template>

    <template #header>
      <NuxtLink :to="localePath('/clientarea/addresses/new')">
        <Button variant="outline" class="w-full">
          <Icon name="lucide:plus" size="16" class="mr-2" />
          {{ t('profileAddresses.actions.add') }}
        </Button>
      </NuxtLink>
    </template>

    <template #card="{ item }">
      <NuxtLink :to="localePath(`/clientarea/addresses/${item.uuid}`)" class="block">
        <Card padding="sm" interactive>
          <div class="flex flex-col gap-1">
            <Text size="base" weight="semibold" class="truncate">{{ item.name }}</Text>
            <Text tone="muted" size="sm" class="line-clamp-2">{{ item.address }}</Text>
            <div class="flex items-center mt-1">
              <span class="text-lg">{{ isoToEmoji(item.countryCode) }}</span>
            </div>
          </div>
        </Card>
      </NuxtLink>
    </template>

    <template #empty>
      <EmptyState
        icon="📍"
        :title="t('profileAddresses.empty.title')"
        :description="t('profileAddresses.empty.description')"
        :action-label="t('profileAddresses.empty.cta')"
        :action-to="localePath('/clientarea/addresses/new')"
        action-icon="lucide:plus"
      />
    </template>
  </CatalogPage>
</template>

<script setup lang="ts">
import type { MapBounds } from '~/components/catalog/CatalogMap.vue'

definePageMeta({
  layout: 'topnav',
  middleware: ['auth-oidc']
})

const { t } = useI18n()
const localePath = useLocalePath()

const {
  items,
  isLoading,
  isoToEmoji,
  init
} = useTeamAddresses()

const selectedAddressId = ref<string>()
const hoveredAddressId = ref<string>()

// Search bar
const searchQuery = ref('')

// Search with map checkbox
const searchWithMap = ref(false)
const currentBounds = ref<MapBounds | null>(null)

// Map items
const itemsWithCoords = computed(() => {
  return items.value.filter(addr =>
    addr.latitude != null &&
    addr.longitude != null &&
    !isNaN(Number(addr.latitude)) &&
    !isNaN(Number(addr.longitude))
  ).map(addr => ({
    uuid: addr.uuid,
    name: addr.name,
    latitude: Number(addr.latitude),
    longitude: Number(addr.longitude)
  }))
})

// Filtered items when searchWithMap is enabled
const displayItems = computed(() => {
  if (!searchWithMap.value || !currentBounds.value) return items.value
  return items.value.filter(item => {
    if (item.latitude == null || item.longitude == null) return false
    const { west, east, north, south } = currentBounds.value!
    const lng = Number(item.longitude)
    const lat = Number(item.latitude)
    return lng >= west && lng <= east && lat >= south && lat <= north
  })
})

// Search handler
const onSearch = () => {
  // TODO: Implement search
}

const onSelectAddress = (item: { uuid?: string | null }) => {
  if (item.uuid) {
    selectedAddressId.value = item.uuid
  }
}

await init()
</script>
