<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 in productsData"
        :key="product.uuid"
        :product="product"
        selectable
        @select="selectProduct(product)"
      />
    </Grid>
  </Stack>
</template>

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

const searchStore = useSearchStore()

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

const selectProduct = (product: any) => {
  searchStore.setProduct(product.name)
  searchStore.setProductUuid(product.uuid)
  const locationUuid = searchStore.searchForm.locationUuid
  if (locationUuid) {
    navigateTo({
      path: '/request',
      query: {
        productUuid: product.uuid,
        product: product.name,
        locationUuid,
        location: searchStore.searchForm.location,
        quantity: searchStore.searchForm.quantity || undefined
      }
    })
    return
  }
  history.back()
}
</script>
