<script setup lang="ts">
import {Modal} from '@/components';
import {formatIsk} from '@/formaters';
import {MarketType, MarketTypeLabel} from '@/market';
import {ref} from 'vue';
import {useAcquiredTypesStore} from './acquisition';

const acquiredTypesStore = useAcquiredTypesStore();

const modalOpen = ref<boolean>(false);
const type = ref<MarketType>();
const suggestions = ref<Record<string, number>>({});
const price = ref(1000000);
const count = ref(1);

const open = (t: MarketType, s?: Record<string, number> | number) => {
    type.value = t;
    count.value = 1;
    
    if (typeof s === 'number') {
        suggestions.value = {};
        price.value = s;
    } else if (s) {
        suggestions.value = s;
        price.value = Object.values(s)[0];
    } else {
        suggestions.value = {};
        price.value = 1000000;
    }
    modalOpen.value = true;
}
const add = () => {
    const id = type.value?.id;

    if (!id) {
        modalOpen.value = false;
        return;
    }

    acquiredTypesStore.addAcquiredType(id, count.value, price.value);
    modalOpen.value = false;
}

defineExpose({ open });
</script>

<template>
    <Modal v-model:open="modalOpen">
        <div class="bg-slate-800 rounded">
            <MarketTypeLabel v-if="type" class="m-1" :id="type.id" :name="type.name" hideCopy />
            <hr />
            <div class="flex p-4">
                <div class="flex me-2">
                    <span>Price: </span>
                    <div class="ms-2">
                        <input  type="number" min="0" step="1" v-model="price" @keyup.enter="add" />
                        <div class="px-2 mt-2 bg-slate-600 hover:bg-slate-700 border rounded cursor-pointer" v-for="(p, n) of suggestions" :key="n" @click="price = p">{{ n }}: {{ formatIsk(p) }}</div>
                    </div>
                </div>
                <div class="flex me-2 mb-auto">
                    <span>Count: </span>
                    <input class="ms-2" type="number" min="0" step="1" v-model="count" @keyup.enter="add" />
                </div>
                <button class="mb-auto" @click="add">Add</button>
            </div>
        </div>
    </Modal>
</template>