<template>
  <Stack gap="6">
    <PageHeader
      :title="$t('goods.title')"
      :description="$t('goods.description')"
    />

    <div v-if="pending" class="flex items-center justify-center p-8">
      <span class="loading loading-spinner loading-lg" />
    </div>

    <Alert v-else-if="error" variant="error">
      <Stack gap="2">
        <Heading :level="4" weight="semibold">{{ $t('goods.error.title') }}</Heading>
        <Button @click="refresh()">{{ $t('goods.error.retry') }}</Button>
      </Stack>
    </Alert>

    <EmptyState
      v-else-if="!productsData?.length"
      :title="$t('goods.empty.title')"
      :description="$t('goods.empty.description')"
    />

    <Grid v-else :cols="1" :md="2" :lg="3" :gap="4">
      <ProductCard
        v-for="(product, index) in productsData"
        :key="product?.uuid ?? index"
        :product="product!"
        selectable
        @select="selectProduct(product!)"
      />
    </Grid>
  </Stack>
</template>

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

type Product = NonNullable<NonNullable<GetProductsQueryResult['getProducts']>[number]>

const searchStore = useSearchStore()

const { data, pending, error, refresh } = await useServerQuery('products', GetProductsDocument, {}, 'public', 'exchange')
const productsData = computed(() => data.value?.getProducts || [])

const selectProduct = (product: Product) => {
  searchStore.setProduct(product.name)
  searchStore.setProductUuid(product.uuid)
  const locationUuid = searchStore.searchForm.locationUuid
  const quantity = searchStore.searchForm.quantity

  const query: Record<string, string> = {}
  if (quantity) query.quantity = String(quantity)

  if (locationUuid) {
    // Both product and hub selected -> show offers
    navigateTo({
      path: `/catalog`,
      query: { product: product.uuid, hub: locationUuid, ...query }
    })
    return
  }
  history.back()
}
</script>
