<template>
  <div>
    <Text size="lg" weight="semibold" class="mb-4">
      {{ t('catalog.headers.hubsForProduct') }}
      <span v-if="!isLoading" class="text-base-content/50 font-normal">
        ({{ filteredItems.length }})
      </span>
    </Text>

    <div v-if="isLoading" class="flex justify-center py-12">
      <span class="loading loading-spinner loading-lg"></span>
    </div>

    <div v-else-if="filteredItems.length === 0" class="text-center py-12">
      <Text tone="muted">{{ t('catalog.empty.noHubs') }}</Text>
    </div>

    <div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
      <HubCard
        v-for="hub in filteredItems"
        :key="hub.uuid"
        :hub="hub"
        selectable
        @select="$emit('select', { uuid: hub.uuid, name: hub.name })"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { GetOffersDocument } from '~/composables/graphql/public/exchange-generated'

const props = defineProps<{
  productId: string
  searchQuery: string
}>()

const emit = defineEmits<{
  (e: 'select', hub: { uuid: string; name: string }): void
  (e: 'product-loaded', name: string): void
}>()

const { t } = useI18n()
const { execute } = useGraphQL()

const items = ref<any[]>([])
const isLoading = ref(true)

// Fetch hubs for product by getting offers and extracting unique hubs
const fetchData = async () => {
  isLoading.value = true
  try {
    const data = await execute(
      GetOffersDocument,
      { productUuid: props.productId },
      'public',
      'exchange'
    )
    const offers = data?.getOffers || []

    // Get product name from first offer
    if (offers.length > 0 && offers[0].productName) {
      emit('product-loaded', offers[0].productName)
    }

    // Extract unique hubs from offers
    const hubsMap = new Map<string, any>()
    offers.forEach((offer: any) => {
      if (offer.locationUuid && !hubsMap.has(offer.locationUuid)) {
        hubsMap.set(offer.locationUuid, {
          uuid: offer.locationUuid,
          name: offer.locationName,
          country: offer.locationCountry,
          countryCode: offer.locationCountryCode,
          latitude: offer.locationLatitude,
          longitude: offer.locationLongitude
        })
      }
    })

    items.value = Array.from(hubsMap.values())
  } finally {
    isLoading.value = false
  }
}

await fetchData()

watch(() => props.productId, fetchData)

const filteredItems = computed(() => {
  if (!props.searchQuery.trim()) return items.value
  const q = props.searchQuery.toLowerCase()
  return items.value.filter((item: any) =>
    item.name?.toLowerCase().includes(q) ||
    item.country?.toLowerCase().includes(q)
  )
})
</script>
