<script setup>
import { ref } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';

import CrudModel from 'components/CrudModel.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnInput from 'src/components/common/VnInput.vue';
import FetchData from 'components/FetchData.vue';
import VnSelect from 'src/components/common/VnSelect.vue';

import axios from 'axios';

const route = useRoute();
const { t } = useI18n();

const itemTagsRef = ref(null);
const tagOptions = ref([]);
const valueOptionsMap = ref(new Map());

const getSelectedTagValues = async (tag) => {
    try {
        if (!tag.tagFk && tag.tag.isFree) return;
        const filter = {
            fields: ['value'],
            order: 'value ASC',
            limit: 30,
        };

        const params = { filter: JSON.stringify(filter) };
        const { data } = await axios.get(`Tags/${tag.tagFk}/filterValue`, {
            params,
        });
        valueOptionsMap.value.set(tag.tagFk, data);
    } catch (err) {
        console.error('Error getting selected tag values');
    }
};

const onItemTagsFetched = async (itemTags) => {
    (itemTags || []).forEach((tag) => {
        getSelectedTagValues(tag);
    });
};

const handleTagSelected = (rows, index, tagId) => {
    const tag = tagOptions.value.find((t) => t.id === tagId);
    rows[index].tag = tag;
    rows[index].tagFk = tagId;
    rows[index].value = null;
    getSelectedTagValues(rows[index]);
};

const getHighestPriority = (rows) => {
    let max = 0;
    rows.forEach((tag) => {
        if (tag.priority > max) max = tag.priority;
    });
    return max + 1;
};

const insertTag = (rows) => {
    itemTagsRef.value.insert();
    itemTagsRef.value.formData[itemTagsRef.value.formData.length - 1].priority =
        getHighestPriority(rows);
};
</script>

<template>
    <FetchData
        url="Tags"
        :filter="{ fields: ['id', 'name', 'isFree', 'sourceTable'] }"
        @on-fetch="(data) => (tagOptions = data)"
        auto-load
    />
    <div class="full-width flex justify-center">
        <QPage class="card-width q-pa-lg">
            <CrudModel
                ref="itemTagsRef"
                data-key="ItemTags"
                model="ItemTags"
                url="ItemTags"
                update-url="Tags/onSubmit"
                :data-required="{
                    $index: undefined,
                    itemFk: route.params.id,
                    priority: undefined,
                    tag: {
                        isFree: undefined,
                        value: undefined,
                        name: undefined,
                    },
                    tagFk: undefined,
                }"
                :default-remove="false"
                :filter="{
                    fields: ['id', 'itemFk', 'tagFk', 'value', 'priority'],
                    where: { itemFk: route.params.id },
                    include: {
                        relation: 'tag',
                        scope: {
                            fields: ['id', 'name', 'isFree', 'sourceTable'],
                        },
                    },
                }"
                order="priority"
                auto-load
                @on-fetch="onItemTagsFetched"
            >
                <template #body="{ rows, validate }">
                    <QCard class="q-px-lg q-pt-md q-pb-sm">
                        <VnRow v-for="(row, index) in rows" :key="index">
                            <VnSelect
                                :label="t('itemTags.tag')"
                                :options="tagOptions"
                                :model-value="row.tag"
                                option-label="name"
                                hide-selected
                                @update:model-value="
                                    (val) => handleTagSelected(rows, index, val)
                                "
                                :required="true"
                                :rules="validate('itemTag.tagFk')"
                            />
                            <VnSelect
                                v-if="row.tag?.isFree === false"
                                :key="row.tagFk"
                                :label="t('Value')"
                                v-model="row.value"
                                :url="`Tags/${row.tagFk}/filterValue`"
                                option-label="value"
                                option-value="value"
                                emit-value
                                use-input
                                class="col"
                                :is-clearable="false"
                                :required="false"
                                :rules="validate('itemTag.tagFk')"
                                :use-like="false"
                            />
                            <VnInput
                                v-else-if="
                                    row.tag?.isFree || row.tag?.isFree == undefined
                                "
                                v-model="row.value"
                                :label="t('itemTags.value')"
                                :is-clearable="false"
                            />
                            <VnInput
                                :label="t('itemTags.relevancy')"
                                type="number"
                                v-model="row.priority"
                                :required="true"
                                :rules="validate('itemTag.priority')"
                            />
                            <div class="row justify-center items-center" style="flex: 0">
                                <QIcon
                                    @click="itemTagsRef.remove([row])"
                                    class="fill-icon-on-hover"
                                    color="primary"
                                    name="delete"
                                    size="sm"
                                >
                                    <QTooltip>
                                        {{ t('itemTags.removeTag') }}
                                    </QTooltip>
                                </QIcon>
                            </div>
                        </VnRow>
                        <VnRow class="justify-center items-center">
                            <QBtn
                                @click="insertTag(rows)"
                                class="cursor-pointer"
                                color="primary"
                                flat
                                icon="add"
                                shortcut="+"
                                style="flex: 0"
                            >
                                <QTooltip>
                                    {{ t('itemTags.addTag') }}
                                </QTooltip>
                            </QBtn>
                        </VnRow>
                    </QCard>
                </template>
            </CrudModel>
        </QPage>
    </div>
</template>
