<script setup lang="ts">
import {LoadingSpinner, Tooltip} from '@/components';
import {formatIsk} from '@/formaters';
import {getQuartiles, type HistoryQuartiles, MarketTrendIcon} from '@/market';
import {computedAsync} from '@vueuse/core';
import {computed, ref} from 'vue';

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

const props = defineProps<Props>();

const open = ref(false);
const loading = ref(false);

const quartiles = computedAsync<HistoryQuartiles | null>(
    () => props.id ? getQuartiles(props.id) : null,
    null,
    loading,
);

const lineColor = computed(() => {
    if (!quartiles.value) {
        return '';
    }
    if (props.buy >= quartiles.value.q3) {
        return 'line-blue';
    }
    if (props.sell >= quartiles.value.q3) {
        return 'line-green';
    }
    return '';
});
</script>

<template>
    <Tooltip v-model:open="open" class="tooltip">
        <template #header>
            <LoadingSpinner v-if="loading || !quartiles" />
            <MarketTrendIcon v-else :trend="quartiles.trend" />
        </template>
        <template #default>
            <div class="bg-slate-500 -left-1/2 relative tooltip-content" v-if="quartiles">
                <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(quartiles.q1) }}</td>
                            <td class="text-right text-nowrap">{{ formatIsk(quartiles.median) }}</td>
                            <td class="text-right text-nowrap">{{ formatIsk(quartiles.q3) }}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </template>
    </Tooltip>
</template>

<style scoped>
@reference "@/style.css";

.tooltip {
    @apply ms-auto;
    &.open {
        &.tooltip-top>:deep(div.header) {
            @apply rounded-t-md bg-slate-600;
        }
        &.tooltip-bottom .tooltip-content {
            bottom: 75px;
        }
        &.tooltip-bottom>:deep(div.header) {
            @apply rounded-b-md bg-slate-600;
        }
    }
}
.tooltip>:deep(div.header) {
  @apply btn-icon px-2;
}

</style>