<template>
  <Stack gap="6">
    <Stack gap="1">
      <Heading :level="1">{{ $t('goods.title') }}</Heading>
      <Text tone="muted" size="base">Материалы и товары доступные на платформе</Text>
    </Stack>

    <Card v-if="pending">
      <Stack align="center" justify="center" gap="3">
        <Spinner />
        <Text tone="muted">Загружаем товары...</Text>
      </Stack>
    </Card>

    <Alert v-else-if="error" variant="error">
      <Stack gap="2">
        <Heading :level="4" weight="semibold">Ошибка загрузки</Heading>
        <Button @click="refresh()">Попробовать снова</Button>
      </Stack>
    </Alert>

    <Grid v-else :cols="1" :md="2" :lg="3" :gap="4">
      <Card
        v-for="product in productsData"
        :key="product.uuid"
        padding="sm"
        tone="muted"
        interactive
        @click="selectProduct(product)"
      >
        <Stack gap="2">
          <Stack gap="1">
            <Text size="base" weight="semibold">{{ product.name }}</Text>
            <Text tone="muted">{{ product.categoryName || 'Без категории' }}</Text>
          </Stack>
          <Text v-if="product.description" tone="muted" size="base">{{ product.description }}</Text>
        </Stack>
      </Card>
    </Grid>
  </Stack>
</template>

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

const searchStore = useSearchStore()
const { execute } = useGraphQL()

const { data: productsData, pending, error, refresh } = await useLazyAsyncData('products', async () => {
  const result = await execute(GetProductsDocument, {}, 'public', 'exchange')
  return result.getProducts
})

const selectProduct = (product) => {
  searchStore.setProduct(product.name)
  searchStore.setProductUuid(product.uuid)
  history.back()
}
</script>
