<script lang='ts' setup>
import type { InfiniteScrollCustomEvent, RefresherCustomEvent } from "@ionic/vue";
import type { AvailableSubscriptionBody, RwaData } from "@/api/types";
import { client, safeClient } from "@/api";
import Category from "./category.vue";
import RwaList from "./rwa-list.vue";

const { t } = useI18n();

const [query] = useResetRef<AvailableSubscriptionBody>({
  limit: 20,
  offset: 0,
  categoryId: "",
});
const rwaData = ref<RwaData[]>([]);
const isFinished = ref(false);

async function fetchRwaData() {
  const { data } = await safeClient(() => client.api.rwa.subscription.available_editions.get({
    query: query.value,
  }));
  rwaData.value.push(...(data.value?.data || []));
  isFinished.value = (data.value?.data.length || 0) < query.value.limit!;
}
function resetRwaData() {
  query.value.offset = 0;
  rwaData.value = [];
  isFinished.value = false;
}
async function handleRefresh() {
  resetRwaData();
  await fetchRwaData();
}

async function handleInfinite(event: InfiniteScrollCustomEvent) {
  if (isFinished.value) {
    event.target.complete();
    event.target.disabled = true;
    return;
  }
  query.value.offset! += query.value.limit!;
  await fetchRwaData();
  setTimeout(() => {
    event.target.complete();
  }, 500);
}

watch(() => query.value.categoryId, async () => {
  resetRwaData();
  await fetchRwaData();
});

onBeforeMount(() => {
  fetchRwaData();
});

defineExpose({
  handleRefresh,
});
</script>

<template>
  <Category v-model="query!.categoryId" />
  <RwaList :data="rwaData" />

  <ion-infinite-scroll threshold="100px" @ion-infinite="handleInfinite">
    <ion-infinite-scroll-content
      loading-spinner="bubbles"
      :loading-text="t('market.loading.loadingMore')"
    />
  </ion-infinite-scroll>
</template>

<style lang='css' scoped></style>
