<script setup lang="ts">
import {getLedgerBalance, useLedgerParam} from "@/ledger";
import {computedAsync} from "@vueuse/core";
import {BalanceResponse} from "@/generated/mammon";
import {getMarketType, IskLabel, MarketTypeLabel} from "@/market";
import {SortableHeader, useSort, VirtualScrollTable} from "@/components/table";

const {ledgerId} = useLedgerParam();

const balance = computedAsync<BalanceResponse>(async () => {
  if (ledgerId.value) {
    return await getLedgerBalance(ledgerId.value);
  }
  return undefined;
});

const { sortedArray, headerProps } = useSort(computedAsync(async () => {
  const itemBalances = balance.value?.itemBalances;

  if (!itemBalances) {
    return [];
  }

  return await Promise.all(itemBalances.map(async i => {
    const item = await getMarketType(i.typeId);

    return {
      ...i,
      name: item.name
    };
  }));
}, []));

</script>

<template>
  <div v-if="balance" class="mt-4">
    <div class="flex justify-end w-full">
      <IskLabel class="mb-2" :amount="balance.iskBalance" />
    </div>
    <VirtualScrollTable :list="sortedArray" :itemHeight="33" bottom="1rem">
      <template #default="{ list }">
        <thead>
        <tr>
          <SortableHeader v-bind="headerProps" sortKey="name">Item</SortableHeader>
          <SortableHeader v-bind="headerProps" sortKey="quantity">Balance</SortableHeader>
        </tr>
        </thead>
        <tbody>
        <tr v-for="i in list" :key="i.data.typeId">
          <td>
            <MarketTypeLabel :id="i.data.typeId" :name="i.data.name" />
          </td>
          <td class="text-right">{{i.data.quantity}}</td>
        </tr>
        </tbody>
      </template>
    </VirtualScrollTable>
  </div>
</template>
