<script setup lang="ts">
import { formatIsk, percentFormater } from '@/formaters';
import { SortableHeader, useSort } from '@/table';
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 useSellOrder = useStorage('reprocess-use-sell-order', false);

const { sortedArray, headerProps } = useSort(computed(() => props.result.map(r => ({
    ...r,
    buy_ratio: r.buy === 0 ? 1 : (r.buy_reprocess / r.buy) - 1,
    sell_ratio: r.sell === 0 ? 1 : (r.sell_reprocess / r.sell) - 1
}))), {
    defaultSortKey: 'name',
    defaultSortDirection: 'asc'
})

const copyToClipboard = (s: string) => navigator.clipboard.writeText(s);
</script>

<template>
    <div class="grid grid-cols-2 mb-2 mt-4 ms-auto">
        <div class="justify-self-end">
            <BuySellSlider v-model="useSellOrder" />
        </div>
        <div class="justify-self-end ms-2">
            <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="useSellOrder ? 'sell' : 'buy'">Market</SortableHeader>
                <SortableHeader v-bind="headerProps" :sortKey="useSellOrder ? 'sell_reprocess' : 'buy_reprocess'">Reprocess</SortableHeader>
                <SortableHeader v-bind="headerProps" :sortKey="useSellOrder ? 'sell_ratio' : 'buy_ratio'">Percent</SortableHeader>
            </tr>
        </thead>
        <tbody>
            <tr v-for="r in sortedArray" :key="r.typeID" class="cursor-pointer" :class="{'bg-emerald-500': (useSellOrder ? r.sell_ratio : r.buy_ratio) >= threshold / 100 }" @click="copyToClipboard(r.name)">
                <td>{{ r.name }}</td>
                <td class="text-right">{{ formatIsk(useSellOrder ? r.sell : r.buy) }}</td>
                <td class="text-right">{{ formatIsk(useSellOrder ? r.sell_reprocess : r.buy_reprocess) }}</td>
                <td class="text-right">{{ percentFormater.format(useSellOrder ? r.sell_ratio : r.buy_ratio) }}</td>
            </tr>
        </tbody>
    </table>
</template>
