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

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

import { toDateFormat } from 'src/filters/date.js';
import { dashIfEmpty } from 'src/filters';
import { useArrayData } from 'src/composables/useArrayData';
import useNotify from 'src/composables/useNotify.js';
import { useVnConfirm } from 'composables/useVnConfirm';
import axios from 'axios';
import { useStateStore } from 'stores/useStateStore';

const stateStore = useStateStore();

const route = useRoute();
const { t } = useI18n();
const { notify } = useNotify();
const { openConfirmationModal } = useVnConfirm();

const rowsSelected = ref([]);

const exprBuilder = (param, value) => {
    switch (param) {
        case 'parking':
        case 'shelving':
        case 'label':
        case 'packing':
        case 'itemFk':
            return { [param]: value };
    }
};

const params = reactive({ itemFk: route.params.id });

const arrayData = useArrayData('ItemShelvings', {
    url: 'ItemShelvingPlacementSupplyStocks',
    userParams: params,
    exprBuilder: exprBuilder,
});
const rows = computed(() => arrayData.store.data || []);

const applyColumnFilter = async (col) => {
    try {
        const paramKey = col.columnFilter?.filterParamKey || col.field;
        params[paramKey] = col.columnFilter.filterValue;
        await arrayData.addFilter({ filter: null, params });
    } catch (err) {
        console.error('Error applying column filter', err);
    }
};

const getInputEvents = (col) => {
    return col.columnFilter.type === 'select'
        ? { 'update:modelValue': () => applyColumnFilter(col) }
        : {
              'keyup.enter': () => applyColumnFilter(col),
          };
};

const columns = computed(() => [
    {
        label: t('shelvings.created'),
        name: 'created',
        field: 'created',
        align: 'left',
        sortable: true,
        columnFilter: null,
        format: (val) => toDateFormat(val),
    },

    {
        label: t('shelvings.item'),
        name: 'item',
        field: 'itemFk',
        align: 'left',
        sortable: true,
        columnFilter: null,
    },
    {
        label: t('shelvings.concept'),
        name: 'concept',
        align: 'left',
        sortable: true,
        columnFilter: null,
    },
    {
        label: t('shelvings.parking'),
        name: 'parking',
        field: 'parking',
        align: 'left',
        sortable: true,
        format: (val) => dashIfEmpty(val),
        columnFilter: {
            component: VnSelect,
            type: 'select',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                url: 'parkings',
                fields: ['code'],
                'sort-by': 'code ASC',
                'option-value': 'code',
                'option-label': 'code',
                dense: true,
            },
        },
    },
    {
        label: t('shelvings.shelving'),
        name: 'shelving',
        field: 'shelving',
        align: 'left',
        sortable: true,
        format: (val) => dashIfEmpty(val),
        columnFilter: {
            component: VnSelect,
            type: 'select',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                url: 'shelvings',
                fields: ['code'],
                'sort-by': 'code ASC',
                'option-value': 'code',
                'option-label': 'code',
                dense: true,
            },
        },
    },
    {
        label: t('shelvings.label'),
        name: 'label',
        align: 'left',
        sortable: true,
        format: (_, row) => (row.stock / row.packing).toFixed(2),
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterParamKey: 'label',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
    },
    {
        label: t('shelvings.packing'),
        field: 'packing',
        name: 'packing',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
        format: (val) => dashIfEmpty(val),
    },
]);

const totalLabels = computed(() =>
    rows.value.reduce((acc, row) => acc + row.stock / row.packing, 0).toFixed(2)
);

const removeLines = async () => {
    try {
        const itemShelvingIds = rowsSelected.value.map((row) => row.itemShelvingFk);
        await axios.post('ItemShelvings/deleteItemShelvings', { itemShelvingIds });
        rowsSelected.value = [];
        notify('shelvings.shelvingsRemoved', 'positive');
        await arrayData.fetch({ append: false });
    } catch (err) {
        console.error('Error removing lines', err);
    }
};
onMounted(async () => {
    await arrayData.fetch({ append: false });
});
</script>

<template>
    <template v-if="stateStore.isHeaderMounted()">
        <Teleport to="#st-data">
            <div class="q-pa-md q-mr-lg q-ma-xs" style="border: 2px solid #222">
                <QCardSection horizontal>
                    <span class="text-weight-bold text-subtitle1 text-center full-width">
                        {{ t('shelvings.total') }}
                    </span>
                </QCardSection>
                <QCardSection class="column items-center" horizontal>
                    <div>
                        <span class="details-label"
                            >{{ t('shelvings.totalLabels') }}
                        </span>
                        <span>: {{ totalLabels }}</span>
                    </div></QCardSection
                >
            </div>
        </Teleport>
        <Teleport to="#st-actions">
            <QBtn
                color="primary"
                icon="delete"
                :disabled="!rowsSelected.length"
                @click="
                    openConfirmationModal(
                        t('shelvings.removeConfirmTitle'),
                        t('shelvings.removeConfirmSubtitle'),
                        removeLines
                    )
                "
            >
                <QTooltip>
                    {{ t('shelvings.removeLines') }}
                </QTooltip>
            </QBtn>
        </Teleport>
    </template>
    <QPage class="column items-center q-pa-md">
        <QTable
            :rows="rows"
            :columns="columns"
            row-key="id"
            :pagination="{ rowsPerPage: 0 }"
            class="full-width q-mt-md"
            selection="multiple"
            v-model:selected="rowsSelected"
            :no-data-label="t('globals.noResults')"
        >
            <template #top-row="{ cols }">
                <QTr>
                    <QTd />
                    <QTd
                        v-for="(col, index) in cols"
                        :key="index"
                        style="max-width: 100px"
                    >
                        <component
                            :is="col.columnFilter.component"
                            v-if="col.columnFilter"
                            v-model="col.columnFilter.filterValue"
                            v-bind="col.columnFilter.attrs"
                            v-on="col.columnFilter.event(col)"
                            dense
                        />
                    </QTd>
                </QTr>
            </template>
            <template #body-cell-concept="{ row }">
                <QTd @click.stop>
                    <span class="link">{{ row.longName }}</span>
                    <ItemDescriptorProxy :id="row.itemFk" />
                </QTd>
            </template>
        </QTable>
    </QPage>
</template>
