<template>
  <Stack gap="6">
    <Stack direction="row" align="center" justify="between">
      <Heading :level="1">{{ t('offersNew.header.title') }}</Heading>
      <NuxtLink :to="localePath('/clientarea/offers')">
        <Button variant="outline">
          <Icon name="lucide:arrow-left" size="16" class="mr-2" />
          {{ t('offersNew.actions.back') }}
        </Button>
      </NuxtLink>
    </Stack>

    <Alert v-if="hasError" variant="error">
      <Stack gap="2">
        <Heading :level="4" weight="semibold">{{ t('offersNew.errors.title') }}</Heading>
        <Text tone="muted">{{ error }}</Text>
        <Button @click="loadProducts">{{ t('offersNew.errors.retry') }}</Button>
      </Stack>
    </Alert>

    <Stack v-else-if="isLoading" align="center" justify="center" gap="3">
      <Spinner />
      <Text tone="muted">{{ t('offersNew.states.loading') }}</Text>
    </Stack>

    <template v-else>
      <Grid v-if="products.length" :cols="1" :md="2" :lg="3" :gap="4">
        <Card
          v-for="product in products"
          :key="product.uuid"
          padding="lg"
          class="cursor-pointer hover:shadow-md transition-shadow"
          @click="selectProduct(product)"
        >
          <Stack gap="2">
            <Heading :level="3">{{ product.name }}</Heading>
            <Text tone="muted">{{ product.categoryName }}</Text>
          </Stack>
        </Card>
      </Grid>

      <Stack v-else align="center" gap="3">
        <IconCircle tone="warning">
          <Icon name="lucide:package-x" size="24" />
        </IconCircle>
        <Heading :level="3">{{ t('offersNew.empty.title') }}</Heading>
        <Text tone="muted">{{ t('offersNew.empty.description') }}</Text>
      </Stack>
    </template>
  </Stack>
</template>

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

definePageMeta({
  middleware: ['auth-oidc']
})

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

const products = ref<any[]>([])
const isLoading = ref(true)
const hasError = ref(false)
const error = ref('')

const loadProducts = async () => {
  try {
    isLoading.value = true
    hasError.value = false
    const { data, error: productsError } = await useServerQuery('offers-new-products', GetProductsDocument, {}, 'public', 'exchange')
    if (productsError.value) throw productsError.value
    products.value = data.value?.getProducts || []
  } catch (err: any) {
    hasError.value = true
    error.value = err.message || t('offersNew.errors.load_failed')
    products.value = []
  } finally {
    isLoading.value = false
  }
}

const selectProduct = (product: any) => {
  // Navigate to product details page
  navigateTo(localePath(`/clientarea/offers/${product.uuid}`))
}

await loadProducts()
</script>
