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

import { QCheckbox, QIcon } from 'quasar';
import CardSummary from 'components/ui/CardSummary.vue';
import VnLv from 'src/components/ui/VnLv.vue';

import travelService from 'src/services/travel.service';
import { toDate, toCurrency } from 'src/filters';
import { getUrl } from 'src/composables/getUrl';
import axios from 'axios';

onUpdated(() => summaryRef.value.fetch());

const route = useRoute();
const { t } = useI18n();

const $props = defineProps({
    id: {
        type: Number,
        required: false,
        default: null,
    },
});

const router = useRouter();
const entityId = computed(() => $props.id || route.params.id);
const entries = ref([]);
const summaryRef = ref();
const travel = ref();
const travelUrl = ref();

onMounted(async () => {
    travelUrl.value = (await getUrl('travel/')) + entityId.value;
});

const cloneTravel = () => {
    const stringifiedTravelData = JSON.stringify(travel.value);
    redirectToCreateView(stringifiedTravelData);
};

const cloneTravelWithEntries = () => {
    try {
        axios.post(`Travels/${$props.id}/cloneWithEntries`);
    } catch (err) {
        console.err('Error cloning travel with entries');
    }
};

const headerMenuOptions = [
    { name: t('travel.summary.cloneShipping'), action: cloneTravel },
    { name: t('travel.summary.CloneTravelAndEntries'), action: cloneTravelWithEntries },
    { name: t('travel.summary.AddEntry'), action: null },
];

const tableColumnComponents = {
    isConfirmed: {
        component: () => QCheckbox,
        props: (prop) => ({
            disable: true,
            'model-value': Boolean(prop.value),
        }),
    },
    id: {
        component: () => 'span',
        props: () => {},
        event: () => openEntryDescriptor(),
    },
    supplierName: {
        component: () => 'span',
        props: () => {},
        event: () => {},
    },
    reference: {
        component: () => 'span',
        props: () => {},
        event: () => {},
    },
    freightValue: {
        component: () => 'span',
        props: () => {},
        event: () => {},
    },
    packageValue: {
        component: () => 'span',
        props: () => {},
        event: () => {},
    },
    cc: {
        component: () => 'span',
        props: () => {},
        event: () => {},
    },
    pallet: {
        component: () => 'span',
        props: () => {},
        event: () => {},
    },
    m3: {
        component: () => 'span',
        props: () => {},
        event: () => {},
    },
    observation: {
        component: (props) => (props.value ? QIcon : null),
        props: () => ({ name: 'insert_drive_file', color: 'primary', size: '25px' }),
    },
};

const entriesTableColumns = computed(() => {
    return [
        {
            label: t('travel.summary.confirmed'),
            field: 'isConfirmed',
            name: 'isConfirmed',
            align: 'left',
        },
        {
            label: t('travel.summary.entryId'),
            field: 'id',
            name: 'id',
            align: 'left',
        },
        {
            label: t('supplier.pageTitles.supplier'),
            field: 'supplierName',
            name: 'supplierName',
            align: 'left',
        },
        {
            label: t('globals.reference'),
            field: 'reference',
            name: 'reference',
            align: 'left',
        },
        {
            label: t('travel.summary.freight'),
            field: 'freightValue',
            name: 'freightValue',
            align: 'left',
            format: (val) => {
                return toCurrency(val);
            },
        },
        {
            label: t('travel.summary.package'),
            field: 'packageValue',
            name: 'packageValue',
            align: 'left',
            format: (val) => {
                return toCurrency(val);
            },
        },
        { label: 'CC', field: 'cc', name: 'cc', align: 'left' },
        { label: 'Pallet', field: 'pallet', name: 'pallet', align: 'left' },
        { label: 'm³', field: 'm3', name: 'm3', align: 'left' },
        {
            label: '',
            field: 'observation',
            name: 'observation',
            align: 'left',
            toolTip: 'Observation three',
        },
    ];
});

const entriesTableRows = computed(() => {
    if (!entries.value && !entries.value.length > 0) return [];
    return entries.value;
});

async function setTravelData(data) {
    if (data) {
        travel.value = data;
        const entriesResponse = await travelService.getTravelEntries(travel.value.id);
        if (entriesResponse.data) entries.value = entriesResponse.data;
    }
}

const redirectToCreateView = (queryParams) => {
    router.push({ name: 'TravelCreate', query: { travelData: queryParams } });
};

const openEntryDescriptor = () => {};
</script>

<template>
    <CardSummary
        ref="summaryRef"
        :url="`Travels/${entityId}/getTravel`"
        @on-fetch="(data) => setTravelData(data)"
    >
        <template #header-left>
            <a class="header link" :href="travelUrl">
                <QIcon name="open_in_new" color="white" size="sm" />
            </a>
        </template>
        <template #header>
            <span>{{ travel.ref }} - {{ travel.id }}</span>
        </template>

        <template #header-right>
            <QBtn color="white" dense flat icon="more_vert" round size="md">
                <QTooltip>
                    {{ t('components.cardDescriptor.moreOptions') }}
                </QTooltip>
                <QMenu>
                    <QList dense v-for="option in headerMenuOptions" :key="option">
                        <QItem v-ripple clickable @click="option.action">
                            {{ option.name }}
                        </QItem>
                    </QList>
                </QMenu>
            </QBtn>
        </template>

        <template #body>
            <QCard class="vn-one">
                <VnLv :label="t('globals.shipped')" :value="toDate(travel.shipped)" />
                <VnLv
                    :label="t('globals.wareHouseOut')"
                    :value="travel.warehouseOut?.name"
                />
                <VnLv :label="t('travel.summary.delivered')" class="q-mb-xs">
                    <template #value>
                        <QCheckbox
                            v-model="travel.isDelivered"
                            disable
                            dense
                            class="full-width q-my-xs"
                        />
                    </template>
                </VnLv>
            </QCard>
            <QCard class="vn-one">
                <VnLv :label="t('globals.landed')" :value="toDate(travel.landed)" />
                <VnLv
                    :label="t('globals.wareHouseIn')"
                    :value="travel.warehouseIn?.name"
                />
                <VnLv :label="t('travel.summary.received')" class="q-mb-xs">
                    <template #value>
                        <QCheckbox
                            v-model="travel.isReceived"
                            disable
                            dense
                            class="full-width q-mb-xs"
                        />
                    </template>
                </VnLv>
            </QCard>
            <QCard class="vn-one">
                <VnLv :label="t('globals.agency')" :value="travel.agency?.name" />
                <VnLv :label="t('globals.reference')" :value="travel.ref" />
                <VnLv label="m³" :value="travel.m3" />
                <VnLv :label="t('globals.totalEntries')" :value="travel.m3" />
            </QCard>
            <QCard class="full-width" v-if="entriesTableRows.length > 0">
                <a class="header" :href="travelUrl + 'entry'">
                    {{ t('travel.summary.entries') }}
                    <QIcon name="open_in_new" color="primary" />
                </a>
                <QTable
                    :rows="entriesTableRows"
                    :columns="entriesTableColumns"
                    hide-bottom
                    row-key="id"
                    class="full-width q-mt-md"
                >
                    <template #body-cell="props">
                        <QTd :props="props">
                            <component
                                :is="
                                    tableColumnComponents[props.col.name].component(props)
                                "
                                v-bind="
                                    tableColumnComponents[props.col.name].props(props)
                                "
                                @click="
                                    tableColumnComponents[props.col.name].event(props)
                                "
                                class="col-content"
                            >
                                <template
                                    v-if="
                                        props.col.name !== 'observation' &&
                                        props.col.name !== 'isConfirmed'
                                    "
                                    >{{ props.value }}</template
                                >
                                <QTooltip v-if="props.col.toolTip">{{
                                    props.col.toolTip
                                }}</QTooltip>
                            </component>
                        </QTd>
                    </template>
                </QTable>
            </QCard>
        </template>
    </CardSummary>
</template>
<style lang="scss" scoped></style>
