<script setup lang="ts">

import {EditLedgerModal, Ledger, LedgerLabel, useLedgersStore} from "@/ledger";
import {storeToRefs} from "pinia";
import {nextTick, ref} from "vue";
import {PencilSquareIcon} from "@heroicons/vue/24/outline";
import {IskLabel} from "@/market";
import {SortableHeader, useSort, VirtualScrollTable} from "@/components/table";

const {ledgers} = storeToRefs(useLedgersStore());

const { sortedArray, headerProps } = useSort<Ledger>(ledgers);

const editModal = ref<typeof EditLedgerModal>();
const editingLedgerId = ref("");

const openEdit = async (ledgerId: string) => {
  editingLedgerId.value = ledgerId;
  await nextTick();
  editModal.value?.open();
};

</script>

<template>
  <div class="mt-4">
    <VirtualScrollTable :list="sortedArray" :itemHeight="33" bottom="1rem">
      <template #default="{ list }">
        <thead>
        <tr>
          <SortableHeader v-bind="headerProps" sortKey="name">Ledger</SortableHeader>
          <SortableHeader v-bind="headerProps" sortKey="balance">Isk Balance</SortableHeader>
          <SortableHeader v-bind="headerProps" sortKey="buttons" unsortable />
        </tr>
        </thead>
        <tbody>
        <tr v-for="l in list" :key="l.data.ledgerId">
          <td>
            <LedgerLabel :ledger="l.data" :link="true" />
          </td>
          <td class="text-right">
            <IskLabel class="ms-2" :amount="l.data.balance" />
          </td>
          <td class="text-right">
            <button class="btn-icon ms-2" @click="openEdit(l.data.ledgerId)"><PencilSquareIcon /></button>
          </td>
        </tr>
        </tbody>
      </template>
      <template #empty>
        <div class="text-center mt-4">
          <span>No ledgers found</span>
        </div>
      </template>
    </VirtualScrollTable>
  </div>
  <EditLedgerModal ref="editModal" :ledger-id="editingLedgerId" />
</template>
