<script setup>
import { ref, reactive, computed } from 'vue';
import { useI18n } from 'vue-i18n';

import VnRow from 'components/ui/VnRow.vue';
import FetchData from 'components/FetchData.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnSelect from 'components/common/VnSelect.vue';
import ItemDescriptorProxy from 'src/pages/Item/Card/ItemDescriptorProxy.vue';

import axios from 'axios';
import { dashIfEmpty } from 'src/filters';

const props = defineProps({
    url: {
        type: String,
        required: true,
    },
});

const emit = defineEmits(['itemSelected']);

const { t } = useI18n();

const itemFilter = {
    include: [
        {
            relation: 'producer',
            scope: {
                fields: ['name'],
            },
        },
        {
            relation: 'ink',
            scope: {
                fields: ['name'],
            },
        },
    ],
};

const itemFilterParams = reactive({});
const closeButton = ref(null);
const isLoading = ref(false);
const producersOptions = ref([]);
const ItemTypesOptions = ref([]);
const InksOptions = ref([]);
const tableRows = ref([]);
const loading = ref(false);

const tableColumns = computed(() => [
    {
        label: t('entry.buys.id'),
        name: 'id',
        field: 'id',
        align: 'left',
    },
    {
        label: t('entry.buys.name'),
        name: 'name',
        field: 'name',
        align: 'left',
    },
    {
        label: t('entry.buys.size'),
        name: 'size',
        field: 'size',
        align: 'left',
    },
    {
        label: t('entry.buys.producer'),
        name: 'producerName',
        field: 'producer',
        align: 'left',
        format: (val) => dashIfEmpty(val),
    },

    {
        label: t('entry.buys.color'),
        name: 'ink',
        field: (row) => row?.ink?.name,
        align: 'left',
    },
]);

const onSubmit = async () => {
    try {
        let filter = itemFilter;
        const params = itemFilterParams;
        const where = {};
        for (let key in params) {
            const value = params[key];
            if (!value) continue;

            switch (key) {
                case 'name':
                    where[key] = { like: `%${value}%` };
                    break;
                case 'producerFk':
                case 'typeFk':
                case 'size':
                case 'inkFk':
                    where[key] = value;
            }
        }
        filter.where = where;

        const { data } = await axios.get(props.url, {
            params: { filter: JSON.stringify(filter) },
        });
        tableRows.value = data;
    } catch (err) {
        console.error('Error fetching entries items');
    }
};

const closeForm = () => {
    if (closeButton.value) closeButton.value.click();
};

const selectItem = ({ id }) => {
    emit('itemSelected', id);
    closeForm();
};
</script>

<template>
    <FetchData
        url="Producers"
        @on-fetch="(data) => (producersOptions = data)"
        :filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }"
        auto-load
    />
    <FetchData
        url="ItemTypes"
        :filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }"
        order="name"
        @on-fetch="(data) => (ItemTypesOptions = data)"
        auto-load
    />
    <FetchData
        url="Inks"
        :filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }"
        order="name"
        @on-fetch="(data) => (InksOptions = data)"
        auto-load
    />
    <QForm @submit="onSubmit()" class="all-pointer-events">
        <QCard class="column" style="padding: 32px; z-index: 100">
            <span ref="closeButton" class="close-icon" v-close-popup>
                <QIcon name="close" size="sm" />
            </span>
            <h1 class="title">{{ t('Filter item') }}</h1>
            <VnRow>
                <VnInput :label="t('entry.buys.name')" v-model="itemFilterParams.name" />
                <VnInput :label="t('entry.buys.size')" v-model="itemFilterParams.size" />
                <VnSelect
                    :label="t('entry.buys.producer')"
                    :options="producersOptions"
                    hide-selected
                    option-label="name"
                    option-value="id"
                    v-model="itemFilterParams.producerFk"
                />
                <VnSelect
                    :label="t('entry.buys.type')"
                    :options="ItemTypesOptions"
                    hide-selected
                    option-label="name"
                    option-value="id"
                    v-model="itemFilterParams.typeFk"
                />
                <VnSelect
                    :label="t('entry.buys.color')"
                    :options="InksOptions"
                    hide-selected
                    option-label="name"
                    option-value="id"
                    v-model="itemFilterParams.inkFk"
                />
            </VnRow>
            <div class="q-mt-lg row justify-end">
                <QBtn
                    :label="t('globals.search')"
                    type="submit"
                    color="primary"
                    :disabled="isLoading"
                    :loading="isLoading"
                />
            </div>
            <QTable
                :columns="tableColumns"
                :rows="tableRows"
                :loading="loading"
                :hide-header="!tableRows || !tableRows.length > 0"
                :no-data-label="t('Enter a new search')"
                class="q-mt-lg"
                @row-click="(_, row) => selectItem(row)"
            >
                <template #body-cell-id="{ row }">
                    <QTd auto-width @click.stop>
                        <QBtn flat color="blue">{{ row.id }}</QBtn>
                        <ItemDescriptorProxy :id="row.id" />
                    </QTd>
                </template>
            </QTable>
        </QCard>
    </QForm>
</template>

<i18n>
es:
    Filter item: Filtrar artículo
    Enter a new search: Introduce una nueva búsqueda
</i18n>

<style lang="scss" scoped>
.title {
    font-size: 17px;
    font-weight: bold;
    line-height: 20px;
}

.close-icon {
    position: absolute;
    top: 20px;
    right: 20px;
    cursor: pointer;
}
</style>
