<script setup lang="ts">
import {ref} from 'vue';
import {Dropdown} from '@/components';
import {compareAppraisal, ComparedItem, CompareResultTable, useAppraisalStore} from '@/market/appraisal';
import {MarketLocation, MarketLocationInput} from '@/market/location';

const store = useAppraisalStore();

const items = ref('');
const from = ref<MarketLocation>();
const to = ref<MarketLocation>();
const showInputs = ref(true);

const result = ref<ComparedItem[]>([]);
const resultLocations = ref<MarketLocation[]>([]);
const loading = ref(false);

const send = async () => {
    const selected = [from.value, to.value].filter((l): l is MarketLocation => l !== undefined);
    loading.value = true;
    try {
        result.value = await compareAppraisal(items.value, selected.map(l => l.id), store.getPrices);
        resultLocations.value = selected;
    } finally {
        loading.value = false;
    }
};
</script>

<template>
    <Dropdown inline :auto-close="false" v-model:open="showInputs" class="mt-4">
        <template #button>Items &amp; locations</template>
        <div class="flex items-stretch mt-2">
            <div class="flex-1 mx-1">
                <span>Items</span>
                <textarea class="mt-1" v-model="items" placeholder="Paste an EVE inventory listing" />
            </div>
        </div>
        <div class="flex flex-wrap gap-6 mx-1 mt-2">
            <div>
                <span>From</span>
                <div class="mt-1">
                    <MarketLocationInput v-model="from" />
                </div>
            </div>
            <div>
                <span>To</span>
                <div class="mt-1">
                    <MarketLocationInput v-model="to" />
                </div>
            </div>
        </div>
        <div class="grid my-2">
            <button class="justify-self-end" @click="send" :disabled="!items.trim() || !from || !to || loading">Send</button>
        </div>
    </Dropdown>
    <template v-if="result.length > 0">
        <hr />
        <div class="grid mt-2">
            <CompareResultTable :result="result" :locations="resultLocations" />
        </div>
    </template>
</template>
