<script setup lang="ts">
import { SortableHeader, useSort } from '@/components/table';
import { formatIsk, percentFormater } from '@/formaters';
import { MarketType, MarketTypeLabel, TaxInput, useMarketTaxStore } from "@/market";
import { MinusIcon, PlusIcon } from '@heroicons/vue/24/outline';
import { useStorage } from '@vueuse/core';
import { computed, ref } from 'vue';
import { AcquiredType } from './AcquiredType';
import AcquisitionQuantilsTooltip from './AcquisitionQuantilsTooltip.vue';

type Result = {
    id: number;
    type: MarketType;
    name: string;
    buy: number;
    sell: number;
    price: number;
    remaining: number;
    quantity: number;
    precentProfit: number;
    iskProfit: number;
    acquisitions: AcquiredType[];
}

interface Props {
    items?: AcquiredType[];
    infoOnly?: boolean;
    showAll?: boolean;
}

interface Emits {
    (e: 'buy', type: AcquiredType[], price: number, buy: number, sell: number): void;
    (e: 'sell', type: AcquiredType[]): void;
}

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

const marketTaxStore = useMarketTaxStore();

const threshold = useStorage('market-acquisition-threshold', 10);
const filter = ref("");
const { sortedArray, headerProps } = useSort<Result>(computed(() => {
const filteredItems = props.items.filter(r => r.type.name.toLowerCase().includes(filter.value.toLowerCase()));

    if (props.showAll) {
        return filteredItems.map(r => {
            const precentProfit = marketTaxStore.calculateProfit(r.price, r.sell);

            return {
                id: r.id,
                type: r.type,
                name: r.name,
                buy: r.buy,
                sell: r.sell,
                price: r.price,
                remaining: r.remaining,
                quantity: r.quantity,
                precentProfit,
                iskProfit: r.price * precentProfit * r.remaining,
                acquisitions: [r]
            };
        });
    }

    const list: Result[] = [];
    const groups = Map.groupBy(filteredItems, r => r.type.id);

    groups.forEach((group, typeID) => {
        const first = group[0];

        if (!first) {
            return;
        }

        const total = group.reduce((acc, r) => acc + r.quantity, 0);
        const totalRemaining = group.reduce((acc, r) => acc + r.remaining, 0);
        const price = group.reduce((acc, r) => acc + r.price * r.remaining, 0) / totalRemaining;
        const precentProfit = marketTaxStore.calculateProfit(price, first.sell);

        list.push({
            id: typeID,
            type: first.type,
            name: first.type.name,
            buy: first.buy,
            sell: first.sell,
            price: price,
            remaining: totalRemaining,
            quantity: total,
            precentProfit,
            iskProfit: price * precentProfit * totalRemaining,
            acquisitions: group
        });
    });
    return list;
}), {
    defaultSortKey: 'precentProfit',
    defaultSortDirection: 'desc'
})
const getLineColor = (result: Result) => {
    if (result.precentProfit >= (threshold.value / 100)) {
        return 'line-green';
    } else if (result.precentProfit < 0) {
        return 'line-red';
    }
    return '';
}
</script>

<template>
    <div class="flex" v-if="!infoOnly">
        <div class="flex justify-self-end mb-2 mt-4 ms-auto">
            <TaxInput />
            <div class="end">
                <span>Profit Threshold: </span>
                <input type="number" min="0" max="1000" step="1" v-model="threshold" />
            </div>
            <div class="end">
                <span>Filter: </span>
                <input type="search" class="w-96" v-model="filter" />
            </div>
        </div>
    </div>
    <table>
        <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="price">Bought Price</SortableHeader>
                <SortableHeader v-bind="headerProps" sortKey="remaining">Remaining Amount</SortableHeader>
                <SortableHeader v-bind="headerProps" sortKey="precentProfit">Profit (%)</SortableHeader>
                <SortableHeader v-bind="headerProps" sortKey="iskProfit">Profit (ISK)</SortableHeader>
                <th v-if="!infoOnly" />
            </tr>
        </thead>
        <tbody>
            <tr v-for="r in sortedArray" :key="r.id" :class="getLineColor(r)">
                <td>
                    <div class="flex">
                        <MarketTypeLabel :id="r.type.id" :name="r.name" />
                        <AcquisitionQuantilsTooltip :id="r.type.id" :buy="r.buy" :sell="r.sell" />
                    </div>
                </td>
                <td class="text-right">{{ formatIsk(r.buy) }}</td>
                <td class="text-right">{{ formatIsk(r.sell) }}</td>
                <td class="text-right">{{ formatIsk(r.price) }}</td>
                <td class="text-right">{{ r.remaining }}/{{ r.quantity }}</td>
                <td class="text-right">{{ percentFormater.format(r.precentProfit) }}</td>
                <td class="text-right">{{ formatIsk(r.iskProfit) }}</td>
                <td class="text-right" v-if="!infoOnly">
                    <button class="btn-icon me-1" @click="$emit('buy', r.acquisitions, r.price, r.buy, r.sell)"><PlusIcon /></button>
                    <button class="btn-icon me-1" @click="$emit('sell', r.acquisitions)"><MinusIcon /></button>
                </td>
            </tr>
        </tbody>
    </table>
</template>

<style scoped lang="postcss">
div.end {
    @apply justify-self-end ms-2;
}
</style>