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

const { t } = useI18n();

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

async function fetchRwaData() {
  const { data } = await safeClient(() => client.api.rwa.issuance.products.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(event: RefresherCustomEvent) {
  resetRwaData();
  await fetchRwaData();
  setTimeout(() => {
    event.target.complete();
  }, 500);
}

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();
});
</script>

<template>
  <IonPage>
    <IonHeader class="ion-no-border">
      <ion-toolbar class="ion-toolbar">
        <ion-title>{{ t('myIssues.title') }}</ion-title>
      </ion-toolbar>
      <ion-toolbar class="ion-toolbar px-3">
        <ion-searchbar :placeholder="t('myIssues.search')" />
      </ion-toolbar>
    </IonHeader>
    <IonContent :fullscreen="true" class="ion-padding">
      <ion-refresher slot="fixed" @ion-refresh="handleRefresh($event)">
        <ion-refresher-content />
      </ion-refresher>

      <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('myIssues.loadMore')"
        />
      </ion-infinite-scroll>
    </IonContent>
  </IonPage>
</template>

<style scoped>
ion-searchbar {
  padding: 0;
}
</style>
