<template>
  <CatalogPage
    :items="currentItems"
    :loading="isLoading"
    :total-count="currentItems.length"
    :grid-columns="3"
    :with-map="showMap"
    :use-server-clustering="useServerClustering"
    :cluster-node-type="clusterNodeType"
    map-id="unified-catalog-map"
    :point-color="mapPointColor"
    :hovered-id="hoveredId"
    @select="onMapSelect"
    @update:hovered-id="hoveredId = $event"
  >
    <template #header>
      <Text v-if="!isLoading" tone="muted">{{ headerText }}</Text>
    </template>

    <template #card="{ item }">
      <!-- Product card -->
      <ProductCard
        v-if="cardType === 'product'"
        :product="item"
        selectable
        :is-selected="item.uuid === hoveredId"
        @select="onSelectProduct({ uuid: item.uuid, name: item.name })"
        @hover="(h: boolean) => hoveredId = h ? item.uuid : undefined"
      />

      <!-- Supplier card -->
      <SupplierCard
        v-else-if="cardType === 'supplier'"
        :supplier="item"
        selectable
        :is-selected="item.uuid === hoveredId"
        @select="onSelectSupplier({ uuid: item.uuid || item.teamUuid, name: item.name })"
      />

      <!-- Hub card -->
      <HubCard
        v-else-if="cardType === 'hub'"
        :hub="item"
        selectable
        :is-selected="item.uuid === hoveredId"
        @select="onSelectHub({ uuid: item.uuid, name: item.name })"
        @hover="(h: boolean) => hoveredId = h ? item.uuid : undefined"
      />

      <!-- Offer card -->
      <OfferCard
        v-else-if="cardType === 'offer'"
        :offer="item"
        linkable
      />
    </template>

    <template #empty>
      <!-- Hero for empty state -->
      <CatalogHero v-if="displayMode === 'hero'" @start-select="startSelect" />
      <Text v-else tone="muted">{{ t('catalog.empty.noResults') }}</Text>
    </template>
  </CatalogPage>
</template>

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

definePageMeta({
  layout: 'topnav'
})

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

const {
  selectMode,
  displayMode,
  productId,
  supplierId,
  hubId,
  searchQuery,
  activeTokens,
  availableChips,
  startSelect,
  cancelSelect,
  selectItem,
  removeFilter,
  editFilter,
  setLabel
} = useCatalogSearch()

// Composables for data
const { items: products, isLoading: productsLoading, init: initProducts } = useCatalogProducts()
const { items: suppliers, isLoading: suppliersLoading, init: initSuppliers } = useCatalogSuppliers()
const { items: hubs, isLoading: hubsLoading, init: initHubs } = useCatalogHubs()

// Local state for specific queries
const hubsForProduct = ref<any[]>([])
const productsFromSupplier = ref<any[]>([])
const productsInHub = ref<any[]>([])
const offers = ref<any[]>([])
const specificLoading = ref(false)

const hoveredId = ref<string>()

// Determine what to show
const cardType = computed(() => {
  switch (displayMode.value) {
    case 'grid-products':
    case 'grid-products-from-supplier':
    case 'grid-products-in-hub':
      return 'product'
    case 'grid-suppliers':
      return 'supplier'
    case 'grid-hubs':
    case 'grid-hubs-for-product':
      return 'hub'
    case 'grid-offers':
      return 'offer'
    default:
      return 'product'
  }
})

const showMap = computed(() => displayMode.value !== 'hero')

// Use server clustering for grids that need it
const useServerClustering = computed(() => {
  // Products grid - show offers clusters
  // Hubs grid - show hubs clusters
  // Offers grid - show offer clusters
  return ['grid-products', 'grid-hubs', 'grid-offers', 'grid-products-from-supplier', 'grid-products-in-hub'].includes(displayMode.value)
})

const clusterNodeType = computed(() => {
  // For products/offers show offer locations
  if (['grid-products', 'grid-offers', 'grid-products-from-supplier', 'grid-products-in-hub'].includes(displayMode.value)) {
    return 'offer'
  }
  // For hubs show logistics nodes
  return 'logistics'
})

const mapPointColor = computed(() => {
  if (cardType.value === 'supplier') return '#3b82f6'
  if (cardType.value === 'hub') return '#10b981'
  if (cardType.value === 'offer') return '#22c55e'
  return '#f59e0b'
})

const headerText = computed(() => {
  switch (displayMode.value) {
    case 'grid-products': return t('catalog.headers.selectProduct')
    case 'grid-suppliers': return t('catalog.headers.selectSupplier')
    case 'grid-hubs': return t('catalog.headers.selectHub')
    case 'grid-hubs-for-product': return t('catalog.headers.hubsForProduct')
    case 'grid-products-from-supplier': return t('catalog.headers.productsFromSupplier')
    case 'grid-products-in-hub': return t('catalog.headers.productsInHub')
    case 'grid-offers': return t('catalog.headers.offers')
    default: return ''
  }
})

const isLoading = computed(() => {
  if (specificLoading.value) return true
  switch (displayMode.value) {
    case 'grid-products': return productsLoading.value
    case 'grid-suppliers': return suppliersLoading.value
    case 'grid-hubs': return hubsLoading.value
    default: return false
  }
})

// Filter items by search query
const filterBySearch = (items: any[]) => {
  if (!searchQuery.value.trim()) return items
  const q = searchQuery.value.toLowerCase()
  return items.filter(item =>
    item.name?.toLowerCase().includes(q) ||
    item.productName?.toLowerCase().includes(q) ||
    item.teamName?.toLowerCase().includes(q) ||
    item.locationName?.toLowerCase().includes(q) ||
    item.country?.toLowerCase().includes(q)
  )
}

const currentItems = computed(() => {
  let items: any[] = []

  switch (displayMode.value) {
    case 'grid-products':
      items = products.value
      break
    case 'grid-suppliers':
      items = suppliers.value
      break
    case 'grid-hubs':
      items = hubs.value
      break
    case 'grid-hubs-for-product':
      items = hubsForProduct.value
      break
    case 'grid-products-from-supplier':
      items = productsFromSupplier.value
      break
    case 'grid-products-in-hub':
      items = productsInHub.value
      break
    case 'grid-offers':
      items = offers.value
      break
    case 'hero':
    default:
      items = []
  }

  return filterBySearch(items)
})

// Fetch data based on displayMode
const fetchSpecificData = async () => {
  specificLoading.value = true
  try {
    if (displayMode.value === 'grid-hubs-for-product' && productId.value) {
      // Get hubs for product via offers
      const data = await execute(
        GetOffersDocument,
        { productUuid: productId.value },
        'public',
        'exchange'
      )
      const offersData = data?.getOffers || []

      // Set product name from first offer
      if (offersData.length > 0 && offersData[0].productName) {
        setLabel('product', productId.value, offersData[0].productName)
      }

      // Extract unique hubs
      const hubsMap = new Map<string, any>()
      offersData.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
          })
        }
      })
      hubsForProduct.value = Array.from(hubsMap.values())
    }

    if (displayMode.value === 'grid-products-from-supplier' && supplierId.value) {
      const data = await execute(
        GetOffersDocument,
        { teamUuid: supplierId.value },
        'public',
        'exchange'
      )
      const offersData = data?.getOffers || []

      // Set supplier name
      if (offersData.length > 0 && offersData[0].teamName) {
        setLabel('supplier', supplierId.value, offersData[0].teamName)
      }

      // Extract unique products
      const productsMap = new Map<string, any>()
      offersData.forEach((offer: any) => {
        if (offer.productUuid && !productsMap.has(offer.productUuid)) {
          productsMap.set(offer.productUuid, {
            uuid: offer.productUuid,
            name: offer.productName,
            categoryName: offer.categoryName
          })
        }
      })
      productsFromSupplier.value = Array.from(productsMap.values())
    }

    if (displayMode.value === 'grid-products-in-hub' && hubId.value) {
      const data = await execute(
        GetOffersDocument,
        { locationUuid: hubId.value },
        'public',
        'exchange'
      )
      const offersData = data?.getOffers || []

      // Set hub name
      if (offersData.length > 0 && offersData[0].locationName) {
        setLabel('hub', hubId.value, offersData[0].locationName)
      }

      // Extract unique products
      const productsMap = new Map<string, any>()
      offersData.forEach((offer: any) => {
        if (offer.productUuid && !productsMap.has(offer.productUuid)) {
          productsMap.set(offer.productUuid, {
            uuid: offer.productUuid,
            name: offer.productName,
            categoryName: offer.categoryName
          })
        }
      })
      productsInHub.value = Array.from(productsMap.values())
    }

    if (displayMode.value === 'grid-offers') {
      const vars: any = {}
      if (productId.value) vars.productUuid = productId.value
      if (supplierId.value) vars.teamUuid = supplierId.value
      if (hubId.value) vars.locationUuid = hubId.value

      const data = await execute(GetOffersDocument, vars, 'public', 'exchange')
      offers.value = data?.getOffers || []
    }
  } finally {
    specificLoading.value = false
  }
}

// Initialize base data
const initBaseData = async () => {
  if (displayMode.value === 'grid-products') await initProducts()
  if (displayMode.value === 'grid-suppliers') await initSuppliers()
  if (displayMode.value === 'grid-hubs') await initHubs()
}

// Watch displayMode and fetch appropriate data
watch(displayMode, async (mode) => {
  if (['grid-products', 'grid-suppliers', 'grid-hubs'].includes(mode)) {
    await initBaseData()
  } else if (['grid-hubs-for-product', 'grid-products-from-supplier', 'grid-products-in-hub', 'grid-offers'].includes(mode)) {
    await fetchSpecificData()
  }
}, { immediate: true })

// Selection handlers
const onSelectProduct = (product: { uuid: string; name: string }) => {
  selectItem('product', product.uuid, product.name)
}

const onSelectSupplier = (supplier: { uuid: string; name: string }) => {
  selectItem('supplier', supplier.uuid, supplier.name)
}

const onSelectHub = (hub: { uuid: string; name: string }) => {
  selectItem('hub', hub.uuid, hub.name)
}

const onMapSelect = (item: any) => {
  if (cardType.value === 'product') {
    onSelectProduct({ uuid: item.uuid, name: item.name })
  } else if (cardType.value === 'supplier') {
    onSelectSupplier({ uuid: item.uuid || item.teamUuid, name: item.name })
  } else if (cardType.value === 'hub') {
    onSelectHub({ uuid: item.uuid, name: item.name })
  }
}

// SEO
useHead(() => {
  let title = t('catalog.hero.title')

  if (displayMode.value === 'grid-products') {
    title = t('catalog.headers.selectProduct')
  } else if (displayMode.value === 'grid-suppliers') {
    title = t('catalog.headers.selectSupplier')
  } else if (displayMode.value === 'grid-hubs') {
    title = t('catalog.headers.selectHub')
  } else if (displayMode.value === 'grid-offers') {
    title = t('catalog.headers.offers')
  }

  return { title }
})
</script>
