<script lang='ts' setup>
import type { InfiniteScrollCustomEvent, RefresherCustomEvent } from "@ionic/vue";
import type { HoldingItem } from "@/api/types";
import { alertController, modalController } from "@ionic/vue";
import CryptocurrencyColorNuls from "~icons/cryptocurrency-color/nuls";
import { client, safeClient } from "@/api";
import LockOption from "./lock-option.vue";

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

const holdingsData = ref<HoldingItem[]>([]);
const isLoading = ref(false);

async function fetchHoldings() {
  isLoading.value = true;
  const { data } = await safeClient(() => client.api.rwa.holdings.get());
  if (data.value) {
    holdingsData.value = data.value.data || [];
  }
  isLoading.value = false;
}

function handleRefresh(event: RefresherCustomEvent) {
  vibrate();
  fetchHoldings().finally(() => {
    event.target.complete();
  });
}

function getStatusColor(status: string) {
  switch (status) {
    case "active":
      return "success";
    case "tokenized":
      return "primary";
    case "locked":
      return "warning";
    default:
      return "medium";
  }
}
function getStatusText(status: HoldingItem["status"]) {
  const statusMap = {
    active: t("holdings.status.active"),
    tokenized: t("holdings.status.tokenized"),
    locked: t("holdings.status.locked"),
  };
  return statusMap[status];
}
async function handleTokenized(item: HoldingItem) {
  const alert = await alertController.create({
    header: "资产化确认",
    message: "将持仓转换为可交易资产（失去分红权），是否继续？",
    buttons: [
      {
        text: "取消",
        role: "cancel",
      },
      {
        text: "确认",
        role: "destructive",
        handler: async () => {
          await safeClient(client.api.rwa.tokenization.immediate.post({ productId: item.productId }));
          item.status = "tokenized";
        },
      },
    ],
  });
  await alert.present();
}
async function handleLocked(item: HoldingItem) {
  const modal = await modalController.create({
    component: LockOption,
    componentProps: {
      id: item.productId,
    },
    initialBreakpoint: 0.5,
    breakpoints: [0, 0.5],
    handle: true,
  });
  await modal.present();
}

onMounted(() => {
  fetchHoldings();
});
</script>

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

  <div v-if="isLoading && holdingsData.length === 0" class="flex justify-center items-center h-64">
    <ion-spinner />
  </div>

  <template v-else-if="holdingsData.length === 0">
    <ui-empty />
  </template>

  <div v-else class="space-y-3">
    <div
      v-for="item in holdingsData"
      :key="item.id"
      class="bg-faint rounded-xl p-3"
    >
      <div class="flex justify-between items-center mb-3">
        <div class="flex items-center gap-2">
          <span class="text-sm font-medium">{{ item.product.name }}/{{ item.product.code }}</span>
          <ion-badge :color="getStatusColor(item.status)" class="text-[10px] px-1.5 py-0.5">
            {{ getStatusText(item.status) }}
          </ion-badge>
        </div>
      </div>

      <div class="grid grid-cols-2 gap-2 mb-2">
        <div class="flex justify-between text-xs">
          <span class="text-(--ion-text-color-step-400)">单价</span>
          <span class="text-(--ion-text-color) font-medium">${{ Number(item.subscriptionOrder.unitPrice).toFixed(2) }}</span>
        </div>
        <div class="flex justify-between text-xs">
          <span class="text-(--ion-text-color-step-400)">数量</span>
          <span class="text-(--ion-text-color) font-medium">{{ Number(item.quantity).toFixed(2) }}份</span>
        </div>
        <div class="flex justify-between text-xs">
          <span class="text-(--ion-text-color-step-400)">阶段</span>
          <span class="text-(--ion-text-color) font-medium">{{ item.edition.editionName }}</span>
        </div>
        <div class="flex justify-between text-xs">
          <span class="text-(--ion-text-color-step-400)">总额</span>
          <span class="text-(--ion-text-color) font-medium">${{ item.costValue }}</span>
        </div>
        <div class="flex justify-between text-xs">
          <span class="text-(--ion-text-color-step-400)">总分红</span>
          <span class="text-(--ion-text-color) font-medium">${{ Number(item.totalDividendReceived).toFixed(2) }}</span>
        </div>
      </div>

      <div class="pt-2 flex items-center">
        <span class="text-[11px] text-(--ion-text-color-step-500)">{{ useDateFormat(item.createdAt, 'YYYY/MM/DD HH:mm') }}</span>

        <div v-if="item.status === 'active'" class="flex-1 text-right space-x-2">
          <ion-button size="small" @click="handleTokenized(item)">
            资产化
          </ion-button>
          <ion-button size="small" @click="handleLocked(item)">
            立即锁仓
          </ion-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang='css' scoped>
ion-grid {
  cursor: pointer;
  transition: background-color 0.2s;
}

ion-grid:active {
  background-color: var(--ion-color-light);
}
</style>
