<template>
  <Stack gap="6">
    <Stack direction="row" align="center" justify="between">
      <Heading :level="1">Выберите продукт</Heading>
      <NuxtLink :to="localePath('/dashboard/cabinet/offers')">
        <Button variant="outline">
          <Icon name="lucide:arrow-left" size="16" class="mr-2" />
          Назад
        </Button>
      </NuxtLink>
    </Stack>

    <Alert v-if="hasError" variant="error">
      <Stack gap="2">
        <Heading :level="4" weight="semibold">Ошибка</Heading>
        <Text tone="muted">{{ error }}</Text>
        <Button @click="loadProducts">Попробовать снова</Button>
      </Stack>
    </Alert>

    <Stack v-else-if="isLoading" align="center" justify="center" gap="3">
      <Spinner />
      <Text tone="muted">Загружаем продукты...</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">Нет доступных продуктов</Heading>
        <Text tone="muted">Обратитесь к администратору для добавления продуктов</Text>
      </Stack>
    </template>
  </Stack>
</template>

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

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

const localePath = useLocalePath()
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 result = await execute(GetProductsDocument, {}, 'public', 'exchange')
    products.value = result.getProducts || []
  } catch (err: any) {
    hasError.value = true
    error.value = err.message || 'Не удалось загрузить продукты'
    products.value = []
  } finally {
    isLoading.value = false
  }
}

const selectProduct = (product: any) => {
  // Переходим на страницу характеристик товара
  navigateTo(localePath(`/dashboard/cabinet/offers/${product.uuid}`))
}

onMounted(async () => {
  await loadProducts()
})
</script>
