<script lang='ts' setup>
import type { InfiniteScrollCustomEvent, RefresherCustomEvent } from "@ionic/vue";
import type { MySubscribeRwaBody, MySubscribeRwaData } from "@/api/types";
import { client, safeClient } from "@/api";
import Category from "./components/category.vue";
import MySubscribeList from "./components/my-subscribe-list.vue";

const { t } = useI18n();

const [query] = useResetRef<MySubscribeRwaBody>({
  categoryId: "",
  limit: 20,
  offset: 0,
});

const subscribeData = ref<MySubscribeRwaData[]>([]);
const isFinished = ref(false);

async function fetchRwaData() {
  const { data } = await safeClient(() => client.api.rwa.subscription.my_subscriptions.get({
    query: query.value,
  }));
  subscribeData.value.push(...(data.value?.data || []));
  isFinished.value = (data.value?.data?.length || 0) < query.value.limit!;
}
function resetData() {
  query.value.offset = 0;
  subscribeData.value = [];
  isFinished.value = false;
}
async function handleRefresh(event: RefresherCustomEvent) {
  resetData();
  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 () => {
  resetData();
  await fetchRwaData();
});

onBeforeMount(() => {
  fetchRwaData();
});
</script>

<template>
  <ion-page>
    <ion-header>
      <ion-toolbar class="ion-toolbar">
        <ui-back-button slot="start" />
        <ion-title>{{ t('tradeSettings.mySubscribe.title') }}</ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true" class="ion-padding">
      <ion-refresher slot="fixed" @ion-refresh="handleRefresh($event)">
        <ion-refresher-content />
      </ion-refresher>

      <Category v-model="query!.categoryId" />
      <MySubscribeList :data="subscribeData" />

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

<style scoped></style>
