<script lang='ts' setup>
import type { InfiniteScrollCustomEvent, RefresherCustomEvent } from "@ionic/vue";
import type { EaringsDetailBody, EaringsDetailData } from "@/api/types";
import { client, safeClient } from "@/api";
import { RevenueRecordTypeEnum } from "./enum";

const { t } = useI18n();
const { vibrate } = useHaptics();

const isLoading = ref(true);
const isFinished = ref(false);
const records = ref<Array<EaringsDetailData>>([]);
const [query] = useResetRef<EaringsDetailBody>({
  limit: 20,
  offset: 0,
  type: undefined,
});

const typeOptions = computed(() => [
  { value: undefined, label: t("asset.revenue.types.all") },
  { value: RevenueRecordTypeEnum.dividend, label: t("asset.revenue.types.dividend") },
  { value: RevenueRecordTypeEnum.staking, label: t("asset.revenue.types.staking") },
  { value: RevenueRecordTypeEnum.new_user_reward, label: t("asset.revenue.types.new_user_reward") },
  { value: RevenueRecordTypeEnum.referral_reward, label: t("asset.revenue.types.referral_reward") },
  { value: RevenueRecordTypeEnum.trading_fee_rebate, label: t("asset.revenue.types.trading_fee_rebate") },
  { value: RevenueRecordTypeEnum.deposit_rebate, label: t("asset.revenue.types.deposit_rebate") },
  { value: RevenueRecordTypeEnum.deposit_reward, label: t("asset.revenue.types.deposit_reward") },
  { value: RevenueRecordTypeEnum.other, label: t("asset.revenue.types.other") },
]);

function resetData() {
  query.value.offset = 0;
  records.value = [];
  isFinished.value = false;
}
async function fetchData() {
  isLoading.value = true;
  const { data } = await safeClient(client.api.earnings.details.post(query.value));
  records.value = data.value?.data || [];
  isFinished.value = (data.value?.data.length || 0) < query.value.limit!;
  isLoading.value = false;
}

async function handleRefresh(event: RefresherCustomEvent) {
  vibrate();
  resetData();
  fetchData().finally(() => {
    event.target.complete();
  });
}
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);
}
function changeType(val) {
  resetData();
  if (val === "all") {
    query.value.type = undefined;
  }
  else {
    query.value.type = val as RevenueRecordTypeEnum;
  }
  fetchData();
}

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

<template>
  <ion-page>
    <ion-header class="ion-no-border">
      <ion-toolbar class="ion-toolbar">
        <ui-back-button slot="start" />
        <ion-title>{{ t("asset.revenue.revenueDetails") }}</ion-title>
      </ion-toolbar>
    </ion-header>

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

      <ui-tabs
        size="small"
        class="ion-padding-horizontal py-2"
        :model-value="query.type || 'all'"
        @update:model-value="changeType"
      >
        <ui-tab-pane
          v-for="option in typeOptions"
          :key="option.value"
          :name="option.value || 'all'"
          :title="option.label"
        />
      </ui-tabs>

      <ui-empty v-if="!isLoading && records.length === 0" />

      <ion-list v-else>
        <ion-item
          v-for="item in records"
          :key="item.id"
          lines="full"
        >
          <div class="w-full py-3">
            <div class="flex justify-between items-start">
              <div class="flex-1">
                <div class="flex items-center gap-2 mb-2">
                  <ion-badge class="text-xs px-2 py-0.5">
                    {{ item.type }}
                  </ion-badge>
                  <ion-badge color="success" class="text-xs px-2 py-0.5">
                    已完成
                  </ion-badge>
                </div>
                <div class="text-base font-semibold mb-1">
                  {{ item.relatedAssetName }}
                </div>
                <div class="text-xs text-text-400 mb-2">
                  {{ item.relatedAssetCode }}
                </div>
                <div class="flex items-center gap-1.5 text-xs text-text-400">
                  <i-ic-outline-access-time class="text-sm" />
                  <span>{{ useDateFormat(item.createdAt, 'YYYY/MM/DD HH:mm') }}</span>
                </div>
              </div>
              <div class="text-right ml-4">
                <div class="text-lg font-bold text-success">
                  +{{ formatAmountWithSplit(item.amount) }}
                </div>
              </div>
            </div>
          </div>
        </ion-item>
      </ion-list>

      <ion-infinite-scroll threshold="100px" @ion-infinite="handleInfinite">
        <ion-infinite-scroll-content
          loading-spinner="bubbles"
          loading-text="加载中..."
        />
      </ion-infinite-scroll>
    </ion-content>
  </ion-page>
</template>

<style lang='css' scoped>
:deep(.ui-tabs__nav-wrapper) {
  margin-bottom: 0;
}
</style>
