<template>
  <Stack gap="6">
    <Section variant="plain" paddingY="md">
      <PageHeader :title="t('catalogSuppliersSection.header.title')" />
    </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">
          <SupplierCard
            v-for="supplier in suppliers"
            :key="supplier.uuid || supplier.teamUuid"
            :supplier="supplier"
          />
        </Grid>
        <PaginationLoadMore
          :shown="suppliers.length"
          :total="totalSuppliers"
          :can-load-more="canLoadMore"
          :loading="isLoadingMore"
          @load-more="loadMore"
        />
        <Stack v-if="totalSuppliers === 0" align="center" gap="2">
          <Text tone="muted">{{ t('catalogSuppliersSection.empty.no_suppliers') }}</Text>
        </Stack>
      </Stack>
    </Section>
  </Stack>
</template>

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

const { t } = useI18n()

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

const { data: suppliersData, pending: suppliersPending } = await useServerQuery(
  'catalog-suppliers-list',
  GetSuppliersDocument,
  { limit: PAGE_SIZE, offset: 0 },
  'public',
  'exchange'
)

watchEffect(() => {
  if (suppliersData.value?.getSuppliers) {
    suppliers.value = suppliersData.value.getSuppliers
    totalSuppliers.value = suppliersData.value.getSuppliersCount ?? suppliersData.value.getSuppliers.length
  }
})

const isLoading = computed(() => suppliersPending.value && suppliers.value.length === 0)
const canLoadMore = computed(() => suppliers.value.length < totalSuppliers.value)

const loadMore = async () => {
  if (isLoadingMore.value) return
  isLoadingMore.value = true
  try {
    const data = await execute(
      GetSuppliersDocument,
      { limit: PAGE_SIZE, offset: suppliers.value.length },
      'public',
      'exchange'
    )
    const next = data?.getSuppliers || []
    suppliers.value = suppliers.value.concat(next)
    totalSuppliers.value = data?.getSuppliersCount ?? totalSuppliers.value
  } finally {
    isLoadingMore.value = false
  }
}

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