<script setup lang="ts">
import { SortableHeader, useSort } from '@/components/table';
import { formatIsk, percentFormater } from '@/formaters';
import { MarketTypeLabel } from '@/market/type';
import { useStorage } from '@vueuse/core';
import { computed } from 'vue';
import BuySellSlider from './BuySellSlider.vue';
import { ReprocessItemValues } from './reprocess';

interface Props {
    result?: ReprocessItemValues[];
}

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

const threshold = useStorage('reprocess-threshold', 0);
const useSellOrderForMarket = useStorage('reprocess-market-use-sell-order', false);
const useSellOrderForMaterials = useStorage('reprocess-materials-use-sell-order', false);

const { sortedArray, headerProps } = useSort(computed(() => props.result.map(r => {
    const market = useSellOrderForMarket.value ? r.sell : r.buy;
    const materials = useSellOrderForMaterials.value ? r.sell_reprocess : r.buy_reprocess;
    const ratio = market === 0 ? 1 : ((materials / market) - 1);

    return { ...r, market, materials, ratio };
})), {
    defaultSortKey: 'name',
    defaultSortDirection: 'asc'
})
</script>

<template>
    <div class="flex justify-self-end mb-2 mt-4 ms-auto">
        <div class="justify-self-end me-4 flex flex-col">
            <div class="flex mb-1">
                <BuySellSlider v-model="useSellOrderForMarket" class="me-2" /> Market
            </div>
            <div class="flex">
                <BuySellSlider v-model="useSellOrderForMaterials" class="me-2" /> Materials
            </div>
        </div>
        <div class="justify-self-end mt-auto mb-auto">
            <span>Threshold: </span>
            <input type="number" min="-100" max="100" step="1" v-model="threshold" />
        </div>
    </div>
    <table>
        <thead>
            <tr>
                <SortableHeader v-bind="headerProps" sortKey="name">Item</SortableHeader>
                <SortableHeader v-bind="headerProps" sortKey="market">Market</SortableHeader>
                <SortableHeader v-bind="headerProps" sortKey="materials">Materials</SortableHeader>
                <SortableHeader v-bind="headerProps" sortKey="ratio">Percent</SortableHeader>
            </tr>
        </thead>
        <tbody>
            <tr v-for="r in sortedArray" :key="r.typeID" :class="{'line-green': r.ratio >= threshold / 100 }">
                <td>
                    <MarketTypeLabel :id="r.typeID" :name="r.name" />
                </td>
                <td class="text-right">{{ formatIsk(r.market) }}</td>
                <td class="text-right">{{ formatIsk(r.materials) }}</td>
                <td class="text-right">{{ percentFormater.format(r.ratio) }}</td>
            </tr>
        </tbody>
    </table>
</template>
