<template>
  <Stack gap="6">
    <Section variant="plain" paddingY="md">
      <Stack gap="2">
        <Heading :level="1">{{ t('catalogOffersSection.header.title') }}</Heading>
      </Stack>
    </Section>

    <Section v-if="isLoading" variant="plain" paddingY="md">
      <Card padding="lg">
        <Stack align="center" justify="center" gap="3">
          <Spinner />
          <Text tone="muted">{{ t('catalogLanding.states.loading') }}</Text>
        </Stack>
      </Card>
    </Section>

    <Section v-else variant="plain" paddingY="md">
      <Stack gap="4">
        <Grid :cols="1" :md="2" :lg="3" :gap="4">
          <OfferCard
            v-for="offer in offers"
            :key="offer.uuid"
            :offer="offer"
          />
        </Grid>
        <PaginationLoadMore
          :shown="offers.length"
          :total="totalOffers"
          :can-load-more="canLoadMore"
          :loading="isLoadingMore"
          @load-more="loadMore"
        />
        <Stack v-if="totalOffers === 0" align="center" gap="2">
          <Text tone="muted">{{ t('catalogOffersSection.empty.no_offers') }}</Text>
        </Stack>
      </Stack>
    </Section>
  </Stack>
</template>

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

const { t } = useI18n()

const { execute } = useGraphQL()
const PAGE_SIZE = 24
const offers = ref<any[]>([])
const totalOffers = ref(0)
const isLoadingMore = ref(false)

const { data: offersData, pending: offersPending } = await useServerQuery(
  'catalog-offers-all',
  GetOffersDocument,
  { limit: PAGE_SIZE, offset: 0 },
  'public',
  'exchange'
)

watchEffect(() => {
  if (offersData.value?.getOffers) {
    offers.value = offersData.value.getOffers
    totalOffers.value = offersData.value.getOffersCount ?? offersData.value.getOffers.length
  }
})

const isLoading = computed(() => offersPending.value && offers.value.length === 0)
const canLoadMore = computed(() => offers.value.length < totalOffers.value)

const loadMore = async () => {
  if (isLoadingMore.value) return
  isLoadingMore.value = true
  try {
    const data = await execute(
      GetOffersDocument,
      { limit: PAGE_SIZE, offset: offers.value.length },
      'public',
      'exchange'
    )
    const next = data?.getOffers || []
    offers.value = offers.value.concat(next)
    totalOffers.value = data?.getOffersCount ?? totalOffers.value
  } finally {
    isLoadingMore.value = false
  }
}

useHead(() => ({
  title: t('catalogOffersSection.header.title')
}))
</script>
