<script setup lang="ts">
import { LoadingSpinner, Tooltip } from '@/components';
import { formatIsk } from '@/formaters';
import { getHistory, getHistoryQuartils } from '@/market';
import { ArrowTrendingDownIcon, ArrowTrendingUpIcon } from '@heroicons/vue/24/outline';
import { computedAsync } from '@vueuse/core';
import { ref, watchEffect } from 'vue';

const trendingScale = 3;

interface Props {
    id: number;
    buy: number;
    sell: number;
}

const props = defineProps<Props>();

const open = ref(false);

const q1 = ref(0);
const median = ref(0);
const q3 = ref(0);
const lineColor = ref('');
const history = computedAsync(() => getHistory(props.id), []);

watchEffect(async () => {
    if (!open.value || !props.id) {
        return;
    }
    const quartils = getHistoryQuartils(history.value);

    q1.value = quartils.q1;
    median.value = quartils.median;
    q3.value = quartils.q3;

    if (props.buy >= quartils.q3) {
        lineColor.value = 'line-blue';
    } else if (props.sell >= quartils.q3) {
        lineColor.value = 'line-green';
    } else {
        lineColor.value = '';
    }
})
</script>

<template>
    <Tooltip v-model:open="open" class="tooltip">
        <template #header>
            <LoadingSpinner v-if="history.length < trendingScale" />
            <ArrowTrendingUpIcon v-else-if="history[0].average > history[trendingScale - 1].average" />
            <ArrowTrendingDownIcon v-else />
        </template>
        <template #default>
            <div class="bg-slate-500 -left-1/2 relative tooltip-content" v-if="history.length > 0">
                <table>
                    <thead>
                        <tr>
                            <th>Q1</th>
                            <th>Median</th>
                            <th>Q3</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr :class="lineColor">
                            <td class="text-right text-nowrap">{{ formatIsk(q1) }}</td>
                            <td class="text-right text-nowrap">{{ formatIsk(median) }}</td>
                            <td class="text-right text-nowrap">{{ formatIsk(q3) }}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </template>
    </Tooltip>
</template>

<style scoped lang="postcss">
.tooltip {
    @apply ms-auto;
    >:deep(div.header) {
        @apply btn-icon px-2;
    }
    &.open {
        &.tooltip-top>:deep(div.header) {
            @apply rounded-t-md bg-slate-600;
        }
        &.tooltip-bottom {
            .tooltip-content {
                bottom: 79px;
            }
            >:deep(div.header) {
                @apply rounded-b-md bg-slate-600;
            }
        }
    }
}
</style>