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

import { dashIfEmpty, toCurrency } from 'src/filters';
import { toTimeFormat } from 'src/filters/date';
import { useVnConfirm } from 'composables/useVnConfirm';
import useNotify from 'src/composables/useNotify.js';
import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import ZoneSummary from 'src/pages/Zone/Card/ZoneSummary.vue';
import VnTable from 'src/components/VnTable/VnTable.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnInputTime from 'src/components/common/VnInputTime.vue';

import VnSection from 'src/components/common/VnSection.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import ZoneEventInclusionForm from './Card/ZoneEventInclusionForm.vue';
import ZoneEventExclusionForm from './Card/ZoneEventExclusionForm.vue';

const { t } = useI18n();
const router = useRouter();
const { notify } = useNotify();
const { viewSummary } = useSummaryDialog();
const { openConfirmationModal } = useVnConfirm();
const tableRef = ref();
const warehouseOptions = ref([]);
const dataKey = 'ZoneList';
const selectedRows = ref([]);
const hasSelectedRows = computed(() => selectedRows.value.length > 0);
const openInclusionForm = ref();
const showZoneEventForm = ref(false);
const zoneIds = ref({});
const tableFilter = {
    include: [
        {
            relation: 'agencyMode',
            scope: {
                fields: ['id', 'name'],
            },
        },
        {
            relation: 'address',
            scope: {
                fields: ['id', 'nickname', 'provinceFk', 'postalCode'],
                include: [
                    {
                        relation: 'province',
                        scope: {
                            fields: ['id', 'name'],
                        },
                    },
                    {
                        relation: 'postcode',
                        scope: {
                            fields: ['code', 'townFk'],
                            include: {
                                relation: 'town',
                                scope: {
                                    fields: ['id', 'name'],
                                },
                            },
                        },
                    },
                ],
            },
        },
    ],
};

const columns = computed(() => [
    {
        align: 'left',
        name: 'id',
        label: t('list.id'),
        chip: {
            condition: () => true,
        },
        isId: true,
        columnFilter: {
            inWhere: true,
        },
    },
    {
        align: 'left',
        name: 'name',
        label: t('list.name'),
        isTitle: true,
        create: true,
        columnFilter: {
            optionLabel: 'name',
            optionValue: 'id',
        },
    },
    {
        align: 'left',
        name: 'agencyModeFk',
        label: t('list.agency'),
        cardVisible: true,
        columnFilter: {
            component: 'select',
            inWhere: true,
            attrs: {
                url: 'AgencyModes',
                fields: ['id', 'name'],
            },
        },
        columnField: {
            component: null,
        },
        format: (row, dashIfEmpty) => dashIfEmpty(row?.agencyMode?.name),
    },
    {
        align: 'left',
        name: 'price',
        label: t('list.price'),
        cardVisible: true,
        format: (row) => toCurrency(row.price),
        columnFilter: {
            inWhere: true,
        },
        columnClass: 'shrink-column',
    },
    {
        align: 'left',
        name: 'hour',
        label: t('list.close'),
        cardVisible: true,
        format: (row) => toTimeFormat(row.hour),
        columnFilter: false,
    },
    {
        align: 'left',
        name: 'addressFk',
        label: t('list.addressFk'),
        cardVisible: true,
        columnFilter: false,
        columnClass: 'expand',
    },
    {
        align: 'right',
        name: 'tableActions',
        actions: [
            {
                title: t('components.smartCard.viewSummary'),
                icon: 'preview',
                action: (row) => viewSummary(row.id, ZoneSummary),
                isPrimary: true,
            },
            {
                title: t('globals.clone'),
                icon: 'vn:clone',
                action: (row) => handleClone(row.id),
                isPrimary: true,
            },
        ],
    },
]);

async function clone(id) {
    const { data } = await axios.post(`Zones/${id}/clone`);
    notify(t('globals.dataSaved'), 'positive');
    router.push({ name: 'ZoneBasicData', params: { id: data.id } });
}
const handleClone = (id) => {
    openConfirmationModal(
        t('list.confirmCloneTitle'),
        t('list.confirmCloneSubtitle'),
        () => clone(id),
    );
};

function formatRow(row) {
    if (!row?.address) return '-';
    return dashIfEmpty(`${row?.address?.nickname},
            ${row?.address?.postcode?.town?.name} (${row?.address?.province?.name})`);
}

const exprBuilder = (param, value) => {
    switch (param) {
        case 'name':
            return {
                name: { like: `%${value}%` },
            };
        case 'code':
            return {
                code: { like: `%${value}%` },
            };
        case 'id':
        case 'price':
        case 'agencyModeFk':
            return {
                [param]: value,
            };
        case 'search':
            return /^\d+$/.test(value) ? { id: value } : { name: { like: `%${value}%` } };
    }
};

function openForm(value, rows) {
    zoneIds.value = rows.map((row) => row.id);
    openInclusionForm.value = value;
    showZoneEventForm.value = true;
}

const closeEventForm = () => {
    showZoneEventForm.value = false;
};
</script>

<template>
    <VnSection
        :data-key="dataKey"
        :columns="columns"
        prefix="zone"
        :array-data-props="{
            url: 'Zones',
            order: ['id ASC'],
            userFilter: tableFilter,
            exprBuilder,
        }"
    >
        <template #body>
            <VnSubToolbar>
                <template #st-actions>
                    <QBtnGroup style="column-gap: 10px">
                        <QBtn
                            color="primary"
                            icon-right="event_available"
                            :disable="!hasSelectedRows"
                            @click="openForm(true, selectedRows)"
                        >
                            <QTooltip>{{ t('list.includeEvent') }}</QTooltip>
                        </QBtn>
                        <QBtn
                            color="primary"
                            icon-right="event_busy"
                            :disable="!hasSelectedRows"
                            @click="openForm(false, selectedRows)"
                        >
                            <QTooltip>{{ t('list.excludeEvent') }}</QTooltip>
                        </QBtn>
                    </QBtnGroup>
                </template>
            </VnSubToolbar>
            <div class="table-container">
                <div class="column items-center">
                    <VnTable
                        ref="tableRef"
                        :data-key="dataKey"
                        :columns="columns"
                        redirect="Zone"
                        :create="{
                            urlCreate: 'Zones',
                            title: t('list.createZone'),
                            onDataSaved: ({ id }) => tableRef.redirect(`${id}/location`),
                            formInitialData: {},
                        }"
                        table-height="85vh"
                        v-model:selected="selectedRows"
                        :table="{
                            'row-key': 'id',
                            selection: 'multiple',
                        }"
                    >
                        <template #column-addressFk="{ row }">
                            {{ dashIfEmpty(formatRow(row)) }}
                        </template>
                        <template #more-create-dialog="{ data }">
                            <VnSelect
                                url="AgencyModes"
                                v-model="data.agencyModeFk"
                                option-value="id"
                                option-label="name"
                                :label="t('list.agency')"
                            />
                            <VnInput
                                v-model="data.price"
                                :label="t('list.price')"
                                min="0"
                                type="number"
                                required="true"
                            />
                            <VnInput
                                v-model="data.bonus"
                                :label="t('zone.bonus')"
                                min="0"
                                type="number"
                            />
                            <VnInput
                                v-model="data.travelingDays"
                                :label="t('zone.travelingDays')"
                                type="number"
                                min="0"
                            />
                            <VnInputTime v-model="data.hour" :label="t('list.close')" />
                            <VnSelect
                                url="Warehouses"
                                v-model="data.warehouseFK"
                                option-value="id"
                                option-label="name"
                                :label="t('list.warehouse')"
                                :options="warehouseOptions"
                            />
                            <QCheckbox
                                v-model="data.isVolumetric"
                                :label="t('list.isVolumetric')"
                                :toggle-indeterminate="false"
                            />
                        </template>
                    </VnTable>
                </div>
            </div>
        </template>
    </VnSection>
    <QDialog v-model="showZoneEventForm" @hide="closeEventForm()">
        <ZoneEventInclusionForm
            v-if="openInclusionForm"
            :event="'event'"
            :is-masive-edit="true"
            :zone-ids="zoneIds"
            @close-form="closeEventForm"
        />
        <ZoneEventExclusionForm
            v-else
            :zone-ids="zoneIds"
            :is-masive-edit="true"
            @close-form="closeEventForm"
        />
    </QDialog>
</template>

<style lang="scss" scoped>
.table-container {
    display: flex;
    justify-content: center;
}
.column {
    display: flex;
    flex-direction: column;
    align-items: center;
    min-width: 70%;
}

:deep(.shrink-column) {
    width: 8%;
}
</style>

<i18n>
es:
    Search zone: Buscar zona
    You can search zones by id or name: Puedes buscar zonas por id o nombre
</i18n>
