<script setup lang="ts">
import {SliderCheckbox} from '@/components';
import {SortableHeader, useSort, VirtualScrollTable} from '@/components/table';
import {formatIsk, percentFormater} from "@/formaters";
import {MarketTrend, MarketTrendIcon, MarketTrends, MarketType, MarketTypeLabel, TrendFilter} from "@/market";
import {useStorage} from '@vueuse/core';
import {computed, ref} from 'vue';
import {useAcquiredTypesStore} from '../acquisition';
import {ScanResult} from './scan';

type Result = {
    type: MarketType;
    typeID: number;
    name: string;
    buy: number;
    sell: number;
    q1: number;
    median: number;
    q3: number;
    totalVolume: number;
    acquisitions: number;
    profit: number;
    score: number;
    trend: MarketTrend;
}

interface Props {
    items?: ScanResult[];
    infoOnly?: boolean;
    ignoredColumns?: string[] | string;
}

const scoreFormater = new Intl.NumberFormat("en-US", {
    maximumFractionDigits: 0
});
const volumeFormater = new Intl.NumberFormat("en-US", {
    maximumFractionDigits: 0
});

const props = withDefaults(defineProps<Props>(), {
    items: () => [],
    infoOnly: false,
    ignoredColumns: () => []
});

const acquiredTypesStore = useAcquiredTypesStore();

const threshold = useStorage('market-scan-threshold', 10);
const filter = ref("");
const onlyCheap = ref(false);
const trackedTrends = useStorage<MarketTrend[]>('market-scan-trends', [
    MarketTrends.Up,
    MarketTrends.Flat,
    MarketTrends.Down,
]);
const columnsToIgnore = computed(() =>
    typeof props.ignoredColumns === 'string' ? [props.ignoredColumns] : props.ignoredColumns
);
const { sortedArray, headerProps, showColumn } = useSort<Result>(computed(() => props.items
    .filter(r => r.type.name.toLowerCase().includes(filter.value.toLowerCase()))
    .filter(r => trackedTrends.value.includes(r.trend))
    .map(r => {
        const acquisitions = columnsToIgnore.value.includes('acquisitions') ? 0 : acquiredTypesStore.acquiredTypes
            .filter(t => t.type === r.type.id)
            .reduce((a, b) => a + b.remaining, 0);

        return {
            type: r.type,
            typeID: r.type.id,
            name: r.type.name,
            buy: r.buy,
            sell: r.sell,
            q1: r.q1,
            median: r.median,
            q3: r.q3,
            totalVolume: r.totalVolume,
            acquisitions,
            profit: r.profit,
            score: r.score,
            trend: r.trend,
        };
    }).filter(r => !onlyCheap.value || (r.buy <= r.q1 && r.profit >= (threshold.value / 100)))), {
        defaultSortKey: 'score',
        defaultSortDirection: 'desc',
        ignoredColumns: columnsToIgnore
    })
const getLineColor = (result: Result) => {
    if (props.infoOnly) {
        return '';
    } else if (result.profit < (threshold.value / 100)) {
        return 'line-red';
    } else if (result.sell > 0 && result.sell <= result.q1) {
        return 'line-blue';
    } else if (result.buy <= result.q1) {
        return 'line-green';
    }
    return '';
}
</script>

<template>
    <div v-if="!infoOnly" class="flex mb-2 mt-4">
        <div class="flex justify-self-end ms-auto">
            <div class="end">
                <span>Profit Threshold: </span>
                <input type="number" min="0" max="1000" step="1" v-model="threshold" />
            </div>
            <div class="end flex">
                <SliderCheckbox class="me-1" v-model="onlyCheap" /> Show only cheap items
            </div>
            <div class="end flex items-center">
                <TrendFilter v-model="trackedTrends" />
            </div>
            <div class="end">
                <span>Filter: </span>
                <input type="search" class="w-96" v-model="filter" />
            </div>
        </div>
    </div>
    <VirtualScrollTable :list="sortedArray" :itemHeight="33" bottom="1rem">
        <template #default="{ list }">
            <thead>
                <tr>
                    <SortableHeader v-bind="headerProps" sortKey="name">Item</SortableHeader>
                    <SortableHeader v-bind="headerProps" sortKey="buy">Buy</SortableHeader>
                    <SortableHeader v-bind="headerProps" sortKey="sell">Sell</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="totalVolume">Volume</SortableHeader>
                    <SortableHeader v-bind="headerProps" sortKey="profit">Profit</SortableHeader>
                    <SortableHeader v-bind="headerProps" sortKey="score">Score</SortableHeader>
                    <SortableHeader v-bind="headerProps" sortKey="acquisitions">Acquisitions</SortableHeader>
                </tr>
            </thead>
            <tbody>
                <tr v-for="r in list" :key="r.data.typeID" :class="getLineColor(r.data)">
                    <td v-if="showColumn('name')">
                      <div class="flex">
                        <MarketTypeLabel :id="r.data.typeID" :name="r.data.name" />
                        <MarketTrendIcon class="ms-auto" :trend="r.data.trend" />
                      </div>
                    </td>
                    <td v-if="showColumn('buy')" class="text-right">{{ formatIsk(r.data.buy) }}</td>
                    <td v-if="showColumn('sell')" class="text-right">{{ formatIsk(r.data.sell) }}</td>
                    <td v-if="showColumn('q1')" class="text-right">{{ formatIsk(r.data.q1) }}</td>
                    <td v-if="showColumn('median')" class="text-right">{{ formatIsk(r.data.median) }}</td>
                    <td v-if="showColumn('q3')" class="text-right">{{ formatIsk(r.data.q3) }}</td>
                    <td v-if="showColumn('totalVolume')" class="text-right">{{ volumeFormater.format(r.data.totalVolume) }}</td>
                    <td v-if="showColumn('profit')" class="text-right">{{ percentFormater.format(r.data.profit) }}</td>
                    <td v-if="showColumn('score')" class="text-right">{{ scoreFormater.format(r.data.score) }}</td>
                    <td v-if="showColumn('acquisitions')" class="text-right">{{ r.data.acquisitions }}</td>
                </tr>
            </tbody>
        </template>
        <template #empty>
            <div class="text-center mt-4">
                <span>No items found</span>
            </div>
        </template>
    </VirtualScrollTable>
</template>

<style scoped>
@reference "@/style.css";
div.end {
    @apply justify-self-end ms-2;
}
</style>
