<script setup lang="ts">
import {SliderCheckbox} from '@/components';
import {SortableHeader, useSort, VirtualScrollTable} from '@/components/table';
import {getListedSellTypeIds, MarketType, MarketTypeLabel, TaxInput, useMarketTaxStore} from "@/market";
import {MinusIcon, PlusIcon} from '@heroicons/vue/24/outline';
import {computedAsync, useStorage} from '@vueuse/core';
import {computed, ref} from 'vue';
import {AcquiredType} from './AcquiredType';
import AcquisitionQuartilesTooltip from './AcquisitionQuartilesTooltip.vue';
import {formatEveDate, formatIsk, percentFormater} from "@/formaters.ts";
import {Ledger, LedgerLabel, useLedgersStore} from "@/ledger";

type Result = {
    id: string;
    type: MarketType;
    name: string;
    buy: number;
    sell: number;
    price: number;
    remaining: number;
    quantity: number;
    precentProfit: number;
    iskProfit: number;
    date: Date;
    ledger?: Ledger;
    ledgerName: string;
    acquisitions: AcquiredType[];
}

interface Props {
    items?: AcquiredType[];
    infoOnly?: boolean;
    showAll?: boolean;
    ignoredColumns?: string[] | string;
    defaultSortKey?: string;
}

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,
    ignoredColumns: () => [],
    defaultSortKey: 'precentProfit',
});
defineEmits<Emits>();

const columnsToIgnore = computed(() => {
    const ignoredColumns = typeof props.ignoredColumns === 'string' ? [props.ignoredColumns] : [...props.ignoredColumns];

    if (props.infoOnly && !ignoredColumns.includes('buttons')) {
        ignoredColumns.push('buttons');
    }
    if (!props.showAll && !ignoredColumns.includes('ledger')) {
        ignoredColumns.push('ledger');
    }
    if (ignoredColumns.includes('ledger')) {
      ignoredColumns.push('ledgerName');
    }
    return ignoredColumns;
});

const marketTaxStore = useMarketTaxStore();
const ledgersStore = useLedgersStore();

const listedTypeIds = computedAsync(getListedSellTypeIds, new Set<number>());

const threshold = useStorage('market-acquisition-threshold', 10);
const filter = ref("");
const unlistedOnly = ref(false);
const matchesFilter = (r: AcquiredType) =>
    r.type.name.toLowerCase().includes(filter.value.toLowerCase())
    && (!unlistedOnly.value || !listedTypeIds.value.has(r.type.id));
const { sortedArray, headerProps, showColumn } = useSort<Result>(computed(() => {
    const filteredItems = props.items.filter(matchesFilter);

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

            return {
                id: r.id,
                type: r.type,
                name: r.type.name,
                buy: r.buy,
                sell: r.sell,
                price: r.price,
                remaining: r.remaining,
                quantity: r.quantity,
                precentProfit,
                iskProfit: r.price * precentProfit * r.remaining,
                date: r.date,
                ledger: ledgersStore.findById(r.ledgerId),
                ledgerName: ledgersStore.findById(r.ledgerId)?.name ?? '',
                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.toString(),
            type: first.type,
            name: first.type.name,
            buy: first.buy,
            sell: first.sell,
            price: price,
            remaining: totalRemaining,
            quantity: total,
            precentProfit,
            iskProfit: price * precentProfit * totalRemaining,
            date: first.date,
            ledgerName: '',
            acquisitions: group
        });
    });
    return list;
}), {
    defaultSortKey: props.defaultSortKey,
    defaultSortDirection: 'desc',
    ignoredColumns: columnsToIgnore
})
const getLineColor = (result: Result) => {
    if (result.precentProfit >= (threshold.value / 100)) {
        return 'line-green'; 
    } else if (result.precentProfit < 0) {
        return 'line-red';
    }
    return '';
}
const total = computed(() => {
    if (sortedArray.value.length <= 1) {
        return null;
    }

    const first = sortedArray.value[0];

    if (!first) {
        return null;
    }

    const sameItem = sortedArray.value.every(r => r.type.id === first.type.id);
    const quantity = sameItem ? sortedArray.value.reduce((acc, r) => acc + r.quantity, 0) : 0;
    const totalRemaining = sameItem ? sortedArray.value.reduce((acc, r) => acc + r.remaining, 0) : 0;
    const price = sortedArray.value.reduce((acc, r) => acc + r.price * r.remaining, 0) / totalRemaining;
    const precentProfit = marketTaxStore.calculateProfit(price, first.sell);
    const iskProfit = sortedArray.value.reduce((acc, r) => acc + r.iskProfit, 0);

    return {
        sameItem,
        price,
        remaining: totalRemaining,
        quantity,
        precentProfit,
        iskProfit
    };
});
</script>

<template>
    <div class="flex" v-if="!infoOnly">
        <div class="flex justify-self-end mb-2 mt-4 ms-auto">
            <TaxInput />
            <div class="end flex items-center" title="Show only acquisitions with no open sell order">
                <SliderCheckbox class="me-1" v-model="unlistedOnly" /> Unlisted only
            </div>
            <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>
    <VirtualScrollTable :list="sortedArray" :itemHeight="33" :footerHeight="!!total ? 33 : 0" 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="ledgerName">Ledger</SortableHeader>
                    <SortableHeader v-bind="headerProps" sortKey="date">Bought at</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>
                    <SortableHeader v-bind="headerProps" sortKey="buttons" unsortable />
                </tr>
            </thead>
            <tbody>
                <tr v-for="r in list" :key="r.index" :class="getLineColor(r.data)">
                    <td v-if="showColumn('name')">
                        <div class="flex">
                            <MarketTypeLabel :id="r.data.type.id" :name="r.data.name" />
                            <AcquisitionQuartilesTooltip :id="r.data.type.id" :buy="r.data.buy" :sell="r.data.sell" />
                        </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('ledger')">
                        <LedgerLabel v-if="r.data.ledger" :ledger="r.data.ledger" link />
                    </td>
                    <td v-if="showColumn('date')" class="text-right">{{ formatEveDate(r.data.date) }}</td>
                    <td v-if="showColumn('price')" class="text-right">{{ formatIsk(r.data.price) }}</td>
                    <td v-if="showColumn('remaining')" class="text-right">{{ r.data.remaining }}/{{ r.data.quantity }}</td>
                    <td v-if="showColumn('precentProfit')" class="text-right">{{ percentFormater.format(r.data.precentProfit) }}</td>
                    <td v-if="showColumn('iskProfit')" class="text-right">{{ formatIsk(r.data.iskProfit) }}</td>
                    <td v-if="showColumn('buttons')" class="text-right">
                        <button class="btn-icon me-1" @click="$emit('buy', r.data.acquisitions, r.data.price, r.data.buy, r.data.sell)"><PlusIcon /></button>
                        <button class="btn-icon me-1" @click="$emit('sell', r.data.acquisitions)"><MinusIcon /></button>
                    </td>
                </tr>
            </tbody>
            <tfoot v-if="!!total">
                <tr>
                    <td v-if="showColumn('name')">Total</td>
                    <td v-if="showColumn('buy')">
                        <template v-if="!showColumn('name')">Total</template>
                    </td>
                    <td v-if="showColumn('sell')">
                        <template v-if="!showColumn('name') && !showColumn('buy')">Total</template>
                    </td>
                    <td v-if="showColumn('ledger')">
                        <template v-if="!showColumn('name') && !showColumn('buy') && !showColumn('sell')">Total</template>
                    </td>
                    <td v-if="showColumn('date')">
                        <template v-if="!showColumn('name') && !showColumn('buy') && !showColumn('sell') && !showColumn('ledger')">Total</template>
                    </td>
                    <td v-if="showColumn('price')"  class="text-right">
                        <template v-if="total.sameItem">
                            {{ formatIsk(total.price) }}
                        </template>
                    </td>
                    <td v-if="showColumn('remaining')"  class="text-right">
                        <template v-if="total.sameItem">
                            {{ total.remaining }}/{{ total.quantity }}
                        </template>
                    </td>
                    <td v-if="showColumn('precentProfit')"  class="text-right">
                        <template v-if="total.sameItem">
                            {{ percentFormater.format(total.precentProfit) }}
                        </template>
                    </td>
                    <td v-if="showColumn('iskProfit')"  class="text-right">{{ formatIsk(total.iskProfit) }}</td>
                    <td v-if="showColumn('buttons')" />
                </tr>
            </tfoot>
        </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>