<script setup>
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import axios from 'axios';
import FetchData from 'components/FetchData.vue';
import VnFilterPanel from 'src/components/ui/VnFilterPanel.vue';
import VnSelect from 'components/common/VnSelect.vue';
import VnFilterPanelChip from 'components/ui/VnFilterPanelChip.vue';
import VnInput from 'src/components/common/VnInput.vue';
import getParamWhere from 'src/filters/getParamWhere';

const { t } = useI18n();

const route = useRoute();
const props = defineProps({
    dataKey: {
        type: String,
        required: true,
    },
    tags: {
        type: Array,
        required: true,
    },
    tagValue: {
        type: Array,
        required: true,
    },
});
const categoryList = ref(null);
const selectedCategoryFk = ref(getParamWhere(route, 'categoryFk'));
const typeList = ref([]);
const selectedTypeFk = ref(null);
const selectedTag = ref(null);
const tagValues = ref([{}]);
const tagOptions = ref([]);
const vnFilterPanelRef = ref();
const orderByList = ref([
    { id: 'relevancy DESC, name', name: t('params.relevancy'), priority: 999 },
    { id: 'showOrder, price', name: t('params.colorAndPrice'), priority: 999 },
    { id: 'name', name: t('params.name'), priority: 999 },
    { id: 'price', name: t('params.price'), priority: 999 },
]);
const orderWayList = ref([
    { id: 'ASC', name: t('params.ASC') },
    { id: 'DESC', name: t('params.DESC') },
]);
const orderBySelected = ref('relevancy DESC, name');
const orderWaySelected = ref('ASC');

const createValue = (val, done) => {
    if (val.length > 2) {
        if (!tagOptions.value.includes(val)) {
            done(tagOptions.value, 'add-unique');
        }
        tagValues.value.push({ value: val });
    }
};
const resetCategory = () => {
    selectedCategoryFk.value = null;
    typeList.value = null;
};

const clearFilter = (key) => {
    if (key === 'categoryFk') {
        resetCategory();
    }
};

const selectCategory = (params, category, search) => {
    if (params.categoryFk === category?.id) {
        resetCategory();
        params.categoryFk = null;
    } else {
        selectedCategoryFk.value = category?.id;
        params.categoryFk = category?.id;
        loadTypes(category?.id);
    }
    search();
};

const loadTypes = async (categoryFk = selectedCategoryFk.value) => {
    const { data } = await axios.get(`Orders/${route.params.id}/getItemTypeAvailable`, {
        params: { itemCategoryId: categoryFk },
    });
    typeList.value = data;
};

const selectedCategory = computed(() =>
    (categoryList.value || []).find(
        (category) => category?.id === selectedCategoryFk.value
    )
);
function filterFn(val, update) {
    update(() => {
        const needle = val.toLowerCase();
        tagOptions.value = props.tagValue.filter(
            (v) => v.toLowerCase().indexOf(needle) > -1
        );
    });
}
const selectedType = computed(() => {
    return (typeList.value || []).find((type) => type?.id === selectedTypeFk.value);
});

function exprBuilder(param, value) {
    switch (param) {
        case 'categoryFk':
        case 'typeFk':
            return { [param]: value };
        case 'search':
            if (/^\d+$/.test(value)) return { 'i.id': value };
            else return { 'i.name': { like: `%${value}%` } };
    }
}

const applyTagFilter = (params, search) => {
    if (!tagValues.value?.length) {
        params.tagGroups = null;
        search();
        return;
    }
    if (!params.tagGroups) {
        params.tagGroups = [];
    }
    params.tagGroups.push(
        JSON.stringify({
            values: tagValues.value.filter((obj) => Object.keys(obj).length > 0),
            tagSelection: {
                ...selectedTag.value,
                orgShowField: selectedTag?.value?.name,
            },
            tagFk: selectedTag?.value?.tagFk,
        })
    );
    search();
    selectedTag.value = null;
    tagValues.value = [{}];
};

const removeTagChip = (selection, params, search) => {
    if (params.tagGroups) {
        params.tagGroups = (params.tagGroups || []).filter(
            (value) => value !== selection
        );
    }
    search();
};

const setCategoryList = (data) => {
    categoryList.value = (data || [])
        .filter((category) => category.display)
        .map((category) => ({
            ...category,
            icon: `vn:${(category.icon || '').split('-')[1]}`,
        }));

    selectedCategoryFk.value && loadTypes();
};

const getCategoryClass = (category, params) => {
    if (category.id === params?.categoryFk) {
        return 'active';
    }
};

function addOrder(value, field, params) {
    let { orderBy } = params;
    orderBy = JSON.parse(orderBy);
    orderBy[field] = value;
    params.orderBy = JSON.stringify(orderBy);
    vnFilterPanelRef.value.search();
}
</script>

<template>
    <FetchData url="ItemCategories" limit="30" auto-load @on-fetch="setCategoryList" />
    <VnFilterPanel
        ref="vnFilterPanelRef"
        :data-key="props.dataKey"
        :hidden-tags="['orderFk', 'orderBy']"
        :un-removable-params="['orderFk', 'orderBy']"
        :expr-builder="exprBuilder"
        :custom-tags="['tagGroups']"
        @remove="clearFilter"
        :redirect="false"
    >
        <template #tags="{ tag, formatFn }">
            <strong v-if="tag.label === 'categoryFk'">
                {{ t(selectedCategory?.name || '') }}
            </strong>
            <strong v-else-if="tag.label === 'typeFk'">
                {{ t(selectedType?.name || '') }}
            </strong>
            <div v-else class="q-gutter-x-xs">
                <strong>{{ t(`params.${tag.label}`) }}: </strong>
                <span>{{ formatFn(tag.value) }}</span>
            </div>
        </template>
        <template #customTags="{ tags: customTags, params, searchFn }">
            <template v-for="tag in customTags" :key="tag.label">
                <template v-if="tag.label === 'tagGroups'">
                    <VnFilterPanelChip
                        v-for="chip in tag.value"
                        :key="chip"
                        removable
                        @remove="removeTagChip(chip, params, searchFn)"
                    >
                        <strong> {{ JSON.parse(chip).tagSelection?.name }}: </strong>
                        <span>{{
                            (JSON.parse(chip).values || [])
                                .map((item) => item.value)
                                .join(' | ')
                        }}</span>
                    </VnFilterPanelChip>
                </template>
            </template>
        </template>
        <template #body="{ params, searchFn }">
            <QItem class="category-filter q-mt-md">
                <div
                    v-for="category in categoryList"
                    :key="category.name"
                    :class="['category', getCategoryClass(category, params)]"
                >
                    <QIcon
                        :name="category.icon"
                        class="category-icon"
                        @click="selectCategory(params, category, searchFn)"
                    >
                        <QTooltip>
                            {{ t(category.name) }}
                        </QTooltip>
                    </QIcon>
                </div>
            </QItem>
            <QItem class="q-my-md">
                <QItemSection>
                    <VnSelect
                        :label="t('params.type')"
                        v-model="params.typeFk"
                        :options="typeList"
                        option-value="id"
                        option-label="name"
                        dense
                        outlined
                        rounded
                        emit-value
                        use-input
                        sort-by="name ASC"
                        :disable="!selectedCategoryFk"
                        @update:model-value="
                            (value) => {
                                selectedTypeFk = value;
                                searchFn();
                            }
                        "
                    >
                        <template #option="{ itemProps, opt }">
                            <QItem v-bind="itemProps">
                                <QItemSection>
                                    <QItemLabel>{{ opt.name }}</QItemLabel>
                                    <QItemLabel caption>
                                        {{ opt.categoryName }}
                                    </QItemLabel>
                                </QItemSection>
                            </QItem>
                        </template>
                    </VnSelect>
                </QItemSection>
            </QItem>
            <QSeparator />
            <QItem class="q-mb-md">
                <QItemSection>
                    <VnSelect
                        :label="t('Order by')"
                        v-model="orderBySelected"
                        :options="orderByList"
                        dense
                        outlined
                        rounded
                        @update:model-value="(value) => addOrder(value, 'field', params)"
                    />
                </QItemSection>
            </QItem>
            <QItem class="q-my-md">
                <QItemSection>
                    <VnSelect
                        :label="t('Order')"
                        v-model="orderWaySelected"
                        :options="orderWayList"
                        dense
                        outlined
                        rounded
                        @update:model-value="(value) => addOrder(value, 'way', params)"
                    />
                </QItemSection>
            </QItem>
            <QSeparator />
            <QItem class="q-mt-md">
                <QItemSection>
                    <VnSelect
                        :label="t('params.tag')"
                        v-model="selectedTag"
                        :options="props.tags || []"
                        option-value="id"
                        option-label="name"
                        dense
                        outlined
                        rounded
                        :emit-value="false"
                        use-input
                    />
                </QItemSection>
            </QItem>
            <QItem
                v-for="(value, index) in tagValues"
                :key="value"
                class="q-mt-md filter-value"
            >
                <FetchData
                    v-if="selectedTag"
                    :url="`Tags/${selectedTag}/filterValue`"
                    limit="30"
                    auto-load
                    @on-fetch="(data) => (tagOptions = data)"
                />
                <VnSelect
                    v-if="!selectedTag"
                    :label="t('params.value')"
                    v-model="value.value"
                    :options="tagOptions || []"
                    option-value="value"
                    option-label="value"
                    dense
                    outlined
                    rounded
                    emit-value
                    use-input
                    class="filter-input"
                    @new-value="createValue"
                    @filter="filterFn"
                    @update:model-value="applyTagFilter(params, searchFn)"
                />
                <VnSelect
                    v-else-if="selectedTag === 1"
                    :label="t('params.value')"
                    v-model="value.value"
                    :options="tagOptions || []"
                    option-value="value"
                    option-label="value"
                    dense
                    outlined
                    rounded
                    emit-value
                    use-input
                    class="filter-input"
                    @new-value="createValue"
                    @update:model-value="applyTagFilter(params, searchFn)"
                />
                <VnInput
                    v-else
                    :label="t('params.value')"
                    v-model="value.value"
                    dense
                    outlined
                    rounded
                    class="filter-input"
                    @keyup.enter="applyTagFilter(params, searchFn)"
                />
                <QIcon
                    name="delete"
                    class="filter-icon"
                    @click="(tagValues || []).splice(index, 1)"
                />
            </QItem>
            <QItem class="q-mt-lg">
                <QBtn
                    icon="add_circle"
                    shortcut="+"
                    flat
                    class="filter-icon"
                    @click="tagValues.push({})"
                />
            </QItem>
            <QSeparator />
        </template>
    </VnFilterPanel>
</template>

<style lang="scss" scoped>
.category-filter {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 12px;

    .category {
        flex: 1;
        flex-shrink: 0;
        display: flex;
        justify-content: center;

        &.active {
            .category-icon {
                background-color: $primary;
            }
        }
    }

    .category-icon {
        border-radius: 50%;
        background-color: var(--vn-accent-color);
        font-size: 2.6rem;
        padding: 8px;
        cursor: pointer;
    }
}

.filter-icon {
    font-size: 24px;
    color: $primary;
    padding: 0 4px;
    cursor: pointer;
}

.filter-input {
    flex-shrink: 1;
    min-width: 0;
}

.filter-value {
    display: flex;
    align-items: center;
}
</style>

<i18n>
en:
    params:
        type: Type
        orderBy: Order By
        tag: Tag
        value: Value
        order: Order
        ASC: Ascendant
        DESC: Descendant
        relevancy: Relevancy
        colorAndPrice: Color and price
        name: Name
        price: Price
es:
    params:
        type: Tipo
        orderBy: Ordenar por
        tag: Etiqueta
        value: Valor
        order: Orden
        ASC: Ascendiente
        DESC: Descendiente
        relevancy: Relevancia
        colorAndPrice: Color y precio
        name: Nombre
        price: Precio
    Order: Orden
    Order by: Ordenar por
    Plant: Planta
    Flower: Flor
    Handmade: Confección
    Green: Verde
    Accessories: Complemento
    Fruit: Fruta
</i18n>
