<script lang='ts' setup>
import type { InfiniteScrollCustomEvent } from "@ionic/vue";
import type { TradableBody, TradableData } from "@/api/types";
import { client, safeClient } from "@/api";
import Category from "./category.vue";
import TokenizedList from "./tokenized-list.vue";

const { t } = useI18n();

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

async function fetchData() {
  const { data: responseData } = await safeClient(() => client.api.rwa.tokenization.tradable_products.get({
    query: query.value,
  }));
  data.value.push(...(responseData.value?.data || []));
  isFinished.value = (responseData.value?.data.length || 0) < query.value.limit!;
}
function resetData() {
  query.value.offset = 0;
  data.value = [];
  isFinished.value = false;
}
async function handleRefresh() {
}

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

watch(() => query.value.categoryId, async () => {
  resetData();
  await fetchData();
});

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

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

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

  <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>
