<script lang='ts' setup>
import type { InfiniteScrollCustomEvent, RefresherCustomEvent } from "@ionic/vue";
import type { UserDepositOrderBody, UserDepositOrderData } from "@/api/types";
import { alertController } from "@ionic/vue";
import CryptocurrencyColorAppc from "~icons/cryptocurrency-color/appc";
import CryptocurrencyColorNuls from "~icons/cryptocurrency-color/nuls";
import { client, safeClient } from "@/api";
import { DepositTypeEnum } from "@/api/enum";

const { t } = useI18n();
const [query] = useResetRef<UserDepositOrderBody>({
  limit: 20,
  offset: 0,
});

const billData = ref<UserDepositOrderData[]>([]);
const isFinished = ref(false);

async function fetchRwaData() {
  const { data } = await safeClient(() => client.api.deposit.orders.get({
    query: query.value,
  }));
  billData.value.push(...(data.value?.data || []));
  isFinished.value = (data.value?.data.length || 0) < query.value.limit!;
}
function resetRwaData() {
  query.value.offset = 0;
  billData.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);
}
async function handleCancel(id: string) {
  const alert = await alertController.create({
    header: t("wallet.deposit.confirmCancel"),
    buttons: [
      {
        text: t("wallet.deposit.cancel"),
        role: "cancel",
      },
      {
        text: t("wallet.deposit.confirmCancelButton"),
        role: "destructive",
        handler: async () => {
          await safeClient(client.api.deposit.orders({ orderId: id }).cancel.post());
          resetRwaData();
          await fetchRwaData();
        },
      },
    ],
  });

  await alert.present();
}

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

<template>
  <ion-refresher slot="fixed" @ion-refresh="handleRefresh($event)">
    <ion-refresher-content />
  </ion-refresher>

  <ui-empty v-if="billData.length === 0" />

  <div v-else class="space-y-3 antialiased my-3">
    <div v-for="item in billData" :key="item.id">
      <ion-grid class="py-3 space-y-2">
        <ion-row class="ion-align-items-center">
          <ion-col size="12" class="flex items-center">
            <div class="mr-3">
              <CryptocurrencyColorNuls class="text-md" />
            </div>
            <div class="text-xs font-semibold">
              {{ item.assetCode }}
              <ui-tag type="primary" size="small">
                {{ $t(`recharge.status.${item.status}`) }}
              </ui-tag>
            </div>
          </ion-col>
        </ion-row>

        <ion-row class="ion-align-items-center">
          <ion-col size="3" class="flex flex-col">
            <div class="text-xs text-text-500">
              {{ t('wallet.deposit.amount') }}
            </div>
            <div class="text-sm font-bold">
              {{ Number(item.amount).toFixed(2) }}
            </div>
          </ion-col>
          <ion-col size="3" class="flex flex-col">
            <div class="text-xs text-text-500">
              {{ t('wallet.deposit.depositMethod') }}
            </div>
            <div class="text-xs font-bold">
              {{ $t(`wallet.deposit.type.${item.depositType}`) }}
            </div>
          </ion-col>
          <ion-col size="6" class="flex flex-col">
            <div class="text-xs text-text-500 text-right">
              {{ t('wallet.deposit.createdAt') }}
            </div>
            <div class="text-xs font-bold text-right">
              {{ useDateFormat(item.createdAt, 'MM/DD HH:mm') }}
            </div>
          </ion-col>
        </ion-row>

        <ion-row class="ion-align-items-center">
          <ion-col size="6" class="flex flex-col">
            <div class="text-xs text-text-500">
              {{ t('wallet.deposit.orderNo') }}
            </div>
            <div class="text-xs font-bold">
              {{ item.orderNo }}
            </div>
          </ion-col>
          <ion-col size="6" class="text-right">
            <ion-button v-if="item.status === 'pending'" size="small" fill="outline" color="success" @click.stop="handleCancel(item.id)">
              {{ t('wallet.deposit.cancelDeposit') }}
            </ion-button>
          </ion-col>
        </ion-row>
      </ion-grid>
    </div>
  </div>

  <ion-infinite-scroll threshold="100px" @ion-infinite="handleInfinite">
    <ion-infinite-scroll-content
      loading-spinner="bubbles"
    />
  </ion-infinite-scroll>
</template>

<style lang='css' scoped>
ion-grid {
  border-bottom: 1px solid var(--ion-background-color-step-150);
}
</style>
