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

import FetchData from 'components/FetchData.vue';
import TableVisibleColumns from 'src/components/common/TableVisibleColumns.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import CustomerDescriptorProxy from 'src/pages/Customer/Card/CustomerDescriptorProxy.vue';
import TicketDescriptorProxy from 'src/pages/Ticket/Card/TicketDescriptorProxy.vue';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';
import VnPaginate from 'components/ui/VnPaginate.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import VnSearchbar from 'src/components/ui/VnSearchbar.vue';

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

const router = useRouter();
const stateStore = useStateStore();
const { t } = useI18n();
const { openConfirmationModal } = useVnConfirm();
const { notify } = useNotify();

const paginateRef = ref(null);
const agencyModesOptions = ref([]);
const visibleColumns = ref([]);
const allColumnNames = ref([]);

const arrayData = useArrayData('WeeklyTickets');
const { store } = arrayData;

const weekdays = [
    { id: 0, name: t('weekdays.mon') },
    { id: 1, name: t('weekdays.tue') },
    { id: 2, name: t('weekdays.wed') },
    { id: 3, name: t('weekdays.thu') },
    { id: 4, name: t('weekdays.fri') },
    { id: 5, name: t('weekdays.sat') },
    { id: 6, name: t('weekdays.sun') },
];

const exprBuilder = (param, value) => {
    switch (param) {
        case 'clientName':
            return { 'c.name': value };
        case 'nickName':
            return { 'u.name': value };
    }
};

const params = reactive({});

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

const getInputEvents = (col) => ({ 'keyup.enter': () => applyColumnFilter(col) });

const columns = computed(() => [
    {
        label: t('weeklyTickets.id'),
        name: 'id',
        field: 'ticketFk',
        align: 'left',
        sortable: true,
        columnFilter: null,
    },
    {
        label: t('weeklyTickets.client'),
        name: 'client',
        field: 'clientName',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('weeklyTickets.shipment'),
        name: 'shipment',
        field: 'weekDay',
        align: 'left',
        sortable: true,
        columnFilter: null,
    },
    {
        label: t('weeklyTickets.agency'),
        name: 'agency',
        field: 'agencyModeFk',
        align: 'left',
        sortable: true,
        columnFilter: null,
    },
    {
        label: t('weeklyTickets.warehouse'),
        name: 'warehouse',
        field: 'warehouseName',
        align: 'left',
        sortable: true,
        columnFilter: null,
    },
    {
        label: t('weeklyTickets.salesperson'),
        field: 'salesperson',
        name: 'salesperson',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            filterParamKey: 'nickName',
            attrs: {
                dense: true,
            },
        },
    },
    {
        label: '',
        name: 'actions',
        align: 'left',
        columnFilter: null,
    },
]);

const redirectToTicketSummary = (ticketFk) =>
    router.push({ name: 'TicketSummary', params: { id: ticketFk } });

const deleteWeekly = async (ticketFk) => {
    try {
        await axios.delete(`TicketWeeklies/${ticketFk}`);
        notify(t('globals.dataSaved'), 'positive');
        const ticketIndex = store.data.findIndex((e) => e.ticketFk == ticketFk);
        store.data.splice(ticketIndex, 1);
    } catch (err) {
        console.error('Error deleting weekly', err);
    }
};

const onUpdate = async (ticketFk, field, value) => {
    try {
        const params = { ticketFk, [field]: value };
        await axios.patch('TicketWeeklies', params);
    } catch (err) {
        console.error('Error updating weekly', err);
    }
};

onMounted(async () => {
    stateStore.rightDrawer = true;
    const filteredColumns = columns.value.filter((col) => col.name !== 'actions');
    allColumnNames.value = filteredColumns.map((col) => col.name);
});

onUnmounted(() => (stateStore.rightDrawer = false));
</script>

<template>
    <FetchData
        url="AgencyModes/isActive"
        :filter="{ fields: ['id', 'name'], order: 'name' }"
        auto-load
        @on-fetch="(data) => (agencyModesOptions = data)"
    />
    <VnSearchbar
        data-key="WeeklyTickets"
        :label="t('weeklyTickets.search')"
        :info="t('weeklyTickets.searchInfo')"
    />
    <VnSubToolbar>
        <template #st-data>
            <TableVisibleColumns
                :all-columns="allColumnNames"
                table-code="itemsIndex"
                labels-traductions-path="weeklyTickets"
                @on-config-saved="visibleColumns = [...$event, 'actions']"
            />
        </template>
    </VnSubToolbar>
    <QPage class="column items-center q-pa-md">
        <VnPaginate
            ref="paginateRef"
            data-key="WeeklyTickets"
            url="TicketWeeklies/filter"
            :order="['weekDay', 'ticketFk']"
            :limit="20"
            :expr-builder="exprBuilder"
            :user-params="params"
            :offset="50"
            auto-load
        >
            <template #body="{ rows }">
                <QTable
                    :rows="rows"
                    :columns="columns"
                    row-key="id"
                    :pagination="{ rowsPerPage: 0 }"
                    class="full-width q-mt-md"
                    :visible-columns="visibleColumns"
                    :no-data-label="t('globals.noResults')"
                    @row-click="(_, row) => redirectToTicketSummary(row.ticketFk)"
                >
                    <template #top-row="{ cols }">
                        <QTr>
                            <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-id="{ row }">
                        <QTd @click.stop>
                            <QBtn flat color="primary">
                                {{ row.ticketFk }}
                                <TicketDescriptorProxy :id="row.ticketFk" />
                            </QBtn>
                        </QTd>
                    </template>
                    <template #body-cell-salesperson="{ row }">
                        <QTd @click.stop>
                            <QBtn flat color="primary">
                                {{ row.userName }}
                                <WorkerDescriptorProxy :id="row.workerFk" />
                            </QBtn>
                        </QTd>
                    </template>
                    <template #body-cell-client="{ row }">
                        <QTd @click.stop>
                            <QBtn flat color="primary" dense>
                                {{ row.clientName }}
                                <CustomerDescriptorProxy :id="row.clientFk" />
                            </QBtn>
                        </QTd>
                    </template>
                    <template #body-cell-shipment="{ row }">
                        <QTd @click.stop>
                            <VnSelect
                                :options="weekdays"
                                hide-selected
                                option-label="name"
                                option-value="id"
                                v-model="row.weekDay"
                                @update:model-value="
                                    onUpdate(row.ticketFk, 'weekDay', $event)
                                "
                            />
                        </QTd>
                    </template>
                    <template #body-cell-agency="{ row }">
                        <QTd @click.stop>
                            <VnSelect
                                :options="agencyModesOptions"
                                hide-selected
                                option-label="name"
                                option-value="id"
                                v-model="row.agencyModeFk"
                                @update:model-value="
                                    onUpdate(row.ticketFk, 'agencyModeFk', $event)
                                "
                            />
                        </QTd>
                    </template>
                    <template #body-cell-actions="{ row }">
                        <QTd>
                            <QIcon
                                @click.stop="
                                    openConfirmationModal(
                                        t('You are going to delete this weekly ticket'),
                                        t(
                                            'This ticket will be removed from weekly tickets! Continue anyway?'
                                        ),
                                        () => deleteWeekly(row.ticketFk)
                                    )
                                "
                                class="q-ml-sm cursor-pointer"
                                color="primary"
                                name="delete"
                                size="sm"
                            >
                                <QTooltip>
                                    {{ t('globals.delete') }}
                                </QTooltip>
                            </QIcon>
                        </QTd>
                    </template>
                </QTable>
            </template>
        </VnPaginate>
    </QPage>
</template>

<i18n>
es:
    You are going to delete this weekly ticket: Vas a eliminar este ticket programado
    This ticket will be removed from weekly tickets! Continue anyway?: Este ticket se eliminará de tickets programados! ¿Continuar de todas formas?
</i18n>
