<script setup>
import VnPaginate from 'components/ui/VnPaginate.vue';
import { useStateStore } from 'stores/useStateStore';
import { useI18n } from 'vue-i18n';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { dashIfEmpty, toDateHour } from 'src/filters';
import { useQuasar } from 'quasar';
import toCurrency from 'filters/toCurrency';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import SupplierDescriptorProxy from 'pages/Supplier/Card/SupplierDescriptorProxy.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue';
import RoadmapFilter from 'pages/Route/Roadmap/RoadmapFilter.vue';
import VnConfirm from 'components/ui/VnConfirm.vue';
import axios from 'axios';
import VnInputDate from 'components/common/VnInputDate.vue';
import {useSummaryDialog} from "composables/useSummaryDialog";
import RoadmapSummary from "pages/Route/Roadmap/RoadmapSummary.vue";
import {useRouter} from "vue-router";

const stateStore = useStateStore();
const { t } = useI18n();
const quasar = useQuasar();
const router = useRouter();
const { viewSummary } = useSummaryDialog();

const to = Date.vnNew();
to.setDate(to.getDate() + 1);
to.setHours(0, 0, 0, 0);

const from = Date.vnNew();
from.setDate(from.getDate());
from.setHours(0, 0, 0, 0);

onMounted(() => (stateStore.rightDrawer = true));
onUnmounted(() => (stateStore.rightDrawer = false));

const selectedRows = ref([]);
const columns = computed(() => [
    {
        name: 'roadmap',
        label: t('Roadmap'),
        field: (row) => row.name,
        sortable: true,
        align: 'left',
    },
    {
        name: 'ETD',
        label: t('ETD'),
        field: (row) => toDateHour(row.etd),
        sortable: true,
        align: 'left',
    },
    {
        name: 'carrier',
        label: t('Carrier'),
        field: (row) => row.supplier?.nickname,
        sortable: true,
        align: 'left',
    },
    {
        name: 'plate',
        label: t('Plate'),
        field: (row) => row.tractorPlate,
        sortable: true,
        align: 'left',
    },
    {
        name: 'price',
        label: t('Price'),
        field: (row) => toCurrency(row.price),
        sortable: true,
        align: 'left',
    },
    {
        name: 'observations',
        label: t('Observations'),
        field: (row) => dashIfEmpty(row.observations),
        sortable: true,
        align: 'left',
    },
    {
        name: 'actions',
        label: '',
        sortable: false,
        align: 'right',
    },
]);

const refreshKey = ref(0);
const isCloneDialogOpen = ref(false);
const etdDate = ref(null);

const filter = {
    include: { relation: 'supplier', scope: { fields: ['nickname'] } },
    where: {
        and: [{ etd: { gte: from } }, { etd: { lte: to } }],
    },
};

const cloneSelection = async () => {
    await axios.post('Roadmaps/clone', {
        etd: etdDate.value,
        ids: selectedRows.value.map((row) => row?.id),
    });
    refreshKey.value++;
    etdDate.value = null;
};

const removeSelection = async () => {
    await Promise.all(
        selectedRows.value.map((roadmap) => {
            axios.delete(`Roadmaps/${roadmap.id}`);
        })
    );
};

function confirmRemove() {
    quasar
        .dialog({
            component: VnConfirm,
            componentProps: {
                title: t('Selected roadmaps will be removed'),
                message: t('Are you sure you want to continue?'),
                promise: removeSelection,
            },
        })
        .onOk(() => refreshKey.value++);
}

function navigateToRoadmapSummary(event, row) {
    router.push({ name: 'RoadmapSummary', params: { id: row.id } })
}
</script>

<template>
    <template v-if="stateStore.isHeaderMounted()">
        <Teleport to="#searchbar">
            <VnSearchbar
                data-key="RoadmapList"
                :label="t('Search roadmaps')"
                :info="t('You can search by roadmap reference')"
            />
        </Teleport>
        <Teleport to="#actions-append">
            <div class="row q-gutter-x-sm">
                <QBtn
                    flat
                    @click="stateStore.toggleRightDrawer()"
                    round
                    dense
                    icon="menu"
                >
                    <QTooltip bottom anchor="bottom right">
                        {{ t('globals.collapseMenu') }}
                    </QTooltip>
                </QBtn>
            </div>
        </Teleport>
    </template>
    <QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above>
        <QScrollArea class="fit text-grey-8">
            <RoadmapFilter data-key="RoadmapList" />
        </QScrollArea>
    </QDrawer>
    <QDialog v-model="isCloneDialogOpen">
        <QCard style="min-width: 350px">
            <QCardSection>
                <p class="text-h6 q-ma-none">
                    {{ t('Select the estimated date of departure (ETD)') }}
                </p>
            </QCardSection>

            <QCardSection class="q-pt-none">
                <VnInputDate :label="t('ETD')" v-model="etdDate" autofocus />
            </QCardSection>
            <QCardActions align="right">
                <QBtn flat :label="t('Cancel')" v-close-popup class="text-primary" />
                <QBtn color="primary" v-close-popup @click="cloneSelection">
                    {{ t('Clone') }}
                </QBtn>
            </QCardActions>
        </QCard>
    </QDialog>
    <QPage class="column items-center">
        <VnSubToolbar class="bg-vn-dark justify-end">
            <template #st-actions>
                <QBtn
                    icon="vn:clone"
                    color="primary"
                    class="q-mr-sm"
                    :disable="!selectedRows?.length"
                    @click="isCloneDialogOpen = true"
                >
                    <QTooltip>{{ t('Clone Selected Routes') }}</QTooltip>
                </QBtn>
                <QBtn
                    icon="delete"
                    color="primary"
                    class="q-mr-sm"
                    :disable="!selectedRows?.length"
                    @click="confirmRemove"
                >
                    <QTooltip>{{ t('Delete roadmap(s)') }}</QTooltip>
                </QBtn>
            </template>
        </VnSubToolbar>
        <div class="route-list">
            <VnPaginate
                :key="refreshKey"
                data-key="RoadmapList"
                url="Roadmaps"
                :limit="20"
                :filter="filter"
                auto-load
            >
                <template #body="{ rows }">
                    <div class="q-pa-md">
                        <QTable
                            v-model:selected="selectedRows"
                            :columns="columns"
                            :rows="rows"
                            flat
                            row-key="id"
                            selection="multiple"
                            :rows-per-page-options="[0]"
                            hide-pagination
                            :pagination="{ sortBy: 'ID', descending: true }"
                            @row-click="navigateToRoadmapSummary"
                        >
                            <template #body-cell-carrier="props">
                                <QTd :props="props">
                                    <span v-if="props.value" class="link" @click.stop>
                                        {{ props.value }}
                                        <SupplierDescriptorProxy
                                            :id="props.row?.supplier?.id"
                                        />
                                    </span>
                                </QTd>
                            </template>
                            <template #body-cell-actions="props">
                                <QTd :props="props">
                                    <div class="flex items-center table-actions">
                                        <QIcon
                                            name="preview"
                                            size="xs"
                                            color="primary"
                                            @click.stop="viewSummary(props?.row?.id, RoadmapSummary)"
                                            class="cursor-pointer"
                                        >
                                            <QTooltip>{{ t('Preview') }}</QTooltip>
                                        </QIcon>
                                    </div>
                                </QTd>
                            </template>
                        </QTable>
                    </div>
                </template>
            </VnPaginate>
        </div>
        <QPageSticky :offset="[20, 20]">
            <RouterLink :to="{ name: 'RouteRoadmapCreate' }">
                <QBtn fab icon="add" color="primary" />
                <QTooltip>
                    {{ t('Create roadmap') }}
                </QTooltip>
            </RouterLink>
        </QPageSticky>
    </QPage>
</template>

<style lang="scss" scoped>
.route-list {
    width: 100%;
}

.table-actions {
    gap: 12px;
}
</style>
<i18n>
es:
    Search roadmaps: Buscar troncales
    You can search by roadmap reference: Puedes buscar por referencia de la troncal
    Delete roadmap(s): Eliminar troncal(es)
    Selected roadmaps will be removed: Las troncales seleccionadas serán eliminadas
    Are you sure you want to continue?: ¿Seguro que quieres continuar?
    The date can't be empty: La fecha no puede estar vacía
    Clone Selected Routes: Clonar rutas seleccionadas
    Create roadmap: Crear troncal
    Roadmap: Troncal
    Carrier: Transportista
    Plate: Matrícula
    Price: Precio
    Observations: Observaciones
    Preview: Vista previa
</i18n>
