<script setup lang="ts">
import {RouterLink, RouterView} from 'vue-router';
import {appraiseItemBalances, getLedgerBalance, isMain, LedgerLabel, useLedgerParam} from "@/ledger";
import {routeNames} from "@/routes.ts";
import {getMarketTypes, getPrices, IskLabel} from "@/market";
import {useMarketLocationStore} from '@/market/location';
import {computedAsync} from "@vueuse/core";

const {ledgerId, ledger} = useLedgerParam();
const marketLocationStore = useMarketLocationStore();

const itemAppraisal = computedAsync(async () => {
  if (!ledgerId.value) {
    return undefined;
  }

  const {itemBalances} = await getLedgerBalance(ledgerId.value);

  if (itemBalances.length === 0) {
    return undefined;
  }

  const types = await getMarketTypes([...new Set(itemBalances.map(i => i.typeId))]);
  const prices = await getPrices(types, marketLocationStore.location.id);
  const appraisal = appraiseItemBalances(itemBalances, prices);

  return appraisal.buy === 0 && appraisal.sell === 0 ? undefined : appraisal;
}, undefined);

</script>

<template>
  <div v-if="ledger" class="mt-4">
    <div class="flex">
      <div class="flex w-full">
        <LedgerLabel :ledger="ledger" :link="false" />
      </div>
      <div class="flex justify-end items-baseline gap-3 w-full mb-2">
        <span v-if="itemAppraisal" class="text-sm text-gray-400">
          ~<IskLabel :amount="itemAppraisal.buy" :colored="false" /> buy /
          ~<IskLabel :amount="itemAppraisal.sell" :colored="false" /> sell
        </span>
        <IskLabel :amount="ledger.balance" />
      </div>
    </div>
    <div class="flex border-b-2 border-emerald-500 mt-4">
      <RouterLink :to="{name: routeNames.viewLedgerBalance}" class="tab">
        <span>Balance</span>
      </RouterLink>
      <RouterLink :to="{name: routeNames.listLedgerTransactions}" class="tab">
        <span>Transactions</span>
      </RouterLink>
      <RouterLink :to="{name: routeNames.listLedgerAcquisitions}" class="tab">
        <span>Acquisitions</span>
      </RouterLink>
      <RouterLink v-if="isMain(ledger)" :to="{name: routeNames.viewLedgerStatistics}" class="tab">
        <span>Statistics</span>
      </RouterLink>
    </div>
    <RouterView />
  </div>
</template>
