<script setup lang="ts">
import { formatIsk, percentFormater } from '@/formaters';
import { SortableHeader, useSort } from '@/table';
import { copyToClipboard } from '@/utils';
import { ArrowPathIcon } from '@heroicons/vue/24/outline';
import { computed } from 'vue';
import { MarketResult } from ".";
import { MarketTypeLabel } from "./type";

interface Props {
    result?: MarketResult[];
}

interface Emits {
    (e: 'relaod', typeID: number): void;
}

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

const { sortedArray, headerProps } = useSort(computed(() => props.result.map(r => ({
    typeID: r.type.id,
    name: r.type.name,
    q1: r.q1,
    mmedian: r.median,
    q3: r.q3,
    percent: r.q3 / r.q1
}))), {
    defaultSortKey: 'name',
    defaultSortDirection: 'asc'
})
</script>

<template>
    <div class="grid mt-2">
        <table>
            <thead>
                <tr>
                    <SortableHeader v-bind="headerProps" sortKey="name">Item</SortableHeader>
                    <SortableHeader v-bind="headerProps" sortKey="q1">Q1</SortableHeader>
                    <SortableHeader v-bind="headerProps" sortKey="median">Median</SortableHeader>
                    <SortableHeader v-bind="headerProps" sortKey="q3">Q3</SortableHeader>
                    <SortableHeader v-bind="headerProps" sortKey="percent">Percent</SortableHeader>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="r in sortedArray" :key="r.typeID" class="cursor-pointer" @click="copyToClipboard(r.name)">
                    <td>
                        <MarketTypeLabel :id="r.typeID" :name="r.name" />
                    </td>
                    <td class="text-right">{{ formatIsk(r.q1) }}</td>
                    <td class="text-right">{{ formatIsk(r.mmedian) }}</td>
                    <td class="text-right">{{ formatIsk(r.q3) }}</td>
                    <td class="text-right">{{  percentFormater.format(r.percent) }}</td>
                    <td class="text-right">
                        <button class="btn-icon" @click="$emit('relaod', r.typeID)"><ArrowPathIcon class="hover:stroke-slate-400"/></button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</template>