<script setup lang="ts">
import {SortableHeader, useSort, VirtualScrollTable} from '@/components/table';
import {MarketTypeLabel} from '@/market/type';
import {computed} from 'vue';
import IskLabel from '../IskLabel.vue';
import {AppraisalItemValue} from './appraise';

interface Props {
    result?: AppraisalItemValue[];
}

const props = withDefaults(defineProps<Props>(), {
    result: () => []
});

const { sortedArray, headerProps } = useSort(computed(() => props.result), {
    defaultSortKey: 'sell',
    defaultSortDirection: 'desc'
});

const totalBuy = computed(() => props.result.reduce((sum, r) => sum + r.buy, 0));
const totalSell = computed(() => props.result.reduce((sum, r) => sum + r.sell, 0));
</script>

<template>
    <VirtualScrollTable :list="sortedArray" :itemHeight="33" :footerHeight="33" bottom="1rem">
        <template #default="{ list }">
            <thead>
                <tr>
                    <SortableHeader v-bind="headerProps" sortKey="name">Item</SortableHeader>
                    <SortableHeader v-bind="headerProps" sortKey="quantity">Qty</SortableHeader>
                    <SortableHeader v-bind="headerProps" sortKey="buyUnit">Buy/unit</SortableHeader>
                    <SortableHeader v-bind="headerProps" sortKey="sellUnit">Sell/unit</SortableHeader>
                    <SortableHeader v-bind="headerProps" sortKey="buy">Buy total</SortableHeader>
                    <SortableHeader v-bind="headerProps" sortKey="sell">Sell total</SortableHeader>
                </tr>
            </thead>
            <tbody>
                <tr v-for="r in list" :key="r.data.typeID">
                    <td>
                        <MarketTypeLabel :id="r.data.typeID" :name="r.data.name" />
                    </td>
                    <td class="text-right">{{ r.data.quantity.toLocaleString() }}</td>
                    <td class="text-right"><IskLabel :amount="r.data.buyUnit" :colored="false" /></td>
                    <td class="text-right"><IskLabel :amount="r.data.sellUnit" :colored="false" /></td>
                    <td class="text-right"><IskLabel :amount="r.data.buy" :colored="false" /></td>
                    <td class="text-right"><IskLabel :amount="r.data.sell" :colored="false" /></td>
                </tr>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="4" class="font-semibold">Total</td>
                    <td class="text-right"><IskLabel :amount="totalBuy" :colored="false" /></td>
                    <td class="text-right"><IskLabel :amount="totalSell" :colored="false" /></td>
                </tr>
            </tfoot>
        </template>
        <template #empty>
            <div class="text-center mt-4">
                <span>No items found</span>
            </div>
        </template>
    </VirtualScrollTable>
</template>
