<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 VnInputDate from 'src/components/common/VnInputDate.vue';
import VnSelectFilter from 'components/common/VnSelectFilter.vue';
import TravelDescriptorProxy from 'src/pages/Travel/Card/TravelDescriptorProxy.vue';

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

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

const { t } = useI18n();

const travelFilter = {
    include: [
        {
            relation: 'agency',
            scope: {
                fields: ['name'],
            },
        },
        {
            relation: 'warehouseIn',
            scope: {
                fields: ['name'],
            },
        },
        {
            relation: 'warehouseOut',
            scope: {
                fields: ['name'],
            },
        },
    ],
};

const travelFilterParams = reactive({});
const closeButton = ref(null);
const isLoading = ref(false);
const agenciesOptions = ref([]);
const warehousesOptions = ref([]);
const tableRows = ref([]);
const loading = ref(false);

const tableColumns = computed(() => [
    {
        label: t('entry.basicData.id'),
        name: 'id',
        field: 'id',
        align: 'left',
    },
    {
        label: t('entry.basicData.warehouseOut'),
        name: 'warehouseOutFk',
        field: 'warehouseOutFk',
        align: 'left',
        format: (val) =>
            warehousesOptions.value.find((warehouse) => warehouse.id === val).name,
    },
    {
        label: t('entry.basicData.warehouseIn'),
        name: 'warehouseInFk',
        field: 'warehouseInFk',
        align: 'left',
        format: (val) =>
            warehousesOptions.value.find((warehouse) => warehouse.id === val).name,
    },
    {
        label: t('entry.basicData.shipped'),
        name: 'shipped',
        field: 'shipped',
        align: 'left',
        format: (val) => toDate(val),
    },
    {
        label: t('entry.basicData.landed'),
        name: 'landed',
        field: 'landed',
        align: 'left',
        format: (val) => toDate(val),
    },
]);

const fetchResults = async () => {
    try {
        let filter = travelFilter;
        const params = travelFilterParams;
        const where = {};
        for (let key in params) {
            const value = params[key];
            if (!value) continue;

            switch (key) {
                case 'agencyModeFk':
                case 'warehouseInFk':
                case 'warehouseOutFk':
                case 'shipped':
                case 'landed':
                    where[key] = value;
            }
        }

        filter.where = where;
        const { data } = await axios.get('Travels', {
            params: { filter: JSON.stringify(filter) },
        });
        tableRows.value = data;
    } catch (err) {
        console.error('Error fetching travels');
    }
};

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

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

<template>
    <FetchData
        url="AgencyModes"
        @on-fetch="(data) => (agenciesOptions = data)"
        :filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }"
        auto-load
    />
    <FetchData
        url="Warehouses"
        :filter="{ fields: ['id', 'name'] }"
        order="name"
        @on-fetch="(data) => (warehousesOptions = data)"
        auto-load
    />
    <QForm @submit="fetchResults()" 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 travels') }}</h1>
            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnSelectFilter
                        :label="t('entry.basicData.agency')"
                        :options="agenciesOptions"
                        hide-selected
                        option-label="name"
                        option-value="id"
                        v-model="travelFilterParams.agencyModeFk"
                    />
                </div>
                <div class="col">
                    <VnSelectFilter
                        :label="t('entry.basicData.warehouseOut')"
                        :options="warehousesOptions"
                        hide-selected
                        option-label="name"
                        option-value="id"
                        v-model="travelFilterParams.warehouseOutFk"
                    />
                </div>
                <div class="col">
                    <VnSelectFilter
                        :label="t('entry.basicData.warehouseIn')"
                        :options="warehousesOptions"
                        hide-selected
                        option-label="name"
                        option-value="id"
                        v-model="travelFilterParams.warehouseInFk"
                    />
                </div>
                <div class="col">
                    <VnInputDate
                        :label="t('entry.basicData.shipped')"
                        v-model="travelFilterParams.shipped"
                    />
                </div>
                <div class="col">
                    <VnInputDate
                        :label="t('entry.basicData.landed')"
                        v-model="travelFilterParams.landed"
                    />
                </div>
            </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"
                :pagination="{ rowsPerPage: 0 }"
                :loading="loading"
                :hide-header="!tableRows || !tableRows.length > 0"
                :no-data-label="t('Enter a new search')"
                class="q-mt-lg"
                @row-click="(_, row) => selectTravel(row)"
            >
                <template #body-cell-id="{ row }">
                    <QTd auto-width @click.stop>
                        <QBtn flat color="blue">{{ row.id }}</QBtn>
                        <TravelDescriptorProxy :id="row.id" />
                    </QTd>
                </template>
            </QTable>
        </QCard>
    </QForm>
</template>

<i18n>
es:
    Filter travels: Filtro envíos
    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>
