<script setup>
import { onBeforeMount, ref, inject } from 'vue';
import { useI18n } from 'vue-i18n';

import { useAppStore } from 'stores/app';
import TicketDetails from 'src/pages/Ecomerce/TicketDetails.vue';
import { storeToRefs } from 'pinia';
import { useRoute } from 'vue-router';

const jApi = inject('jApi');
const { t } = useI18n();
const appStore = useAppStore();
const route = useRoute();
const { basketOrderId, isHeaderMounted } = storeToRefs(appStore);

const rows = ref([]);
const ticket = ref({});
const orderId = ref(null);

onBeforeMount(async () => {
    await appStore.check();
    orderId.value = route.params.id || basketOrderId.value;
    if (orderId.value) await fetchData();
});

const getOrder = async () => {
    try {
        const [data] = await jApi.query(
            `SELECT o.id, o.sent,
            ag.description agency, v.code method,
            ad.nickname, ad.postalCode, ad.city, ad.street
            FROM myOrder o
            JOIN vn.agencyMode ag ON ag.id = o.agencyModeFk
            LEFT JOIN myAddress ad ON ad.id = o.addressFk
            JOIN vn.deliveryMethod v ON v.id = o.deliveryMethodFk
            WHERE o.id = #id;`,
            { id: orderId.value }
        );
        const { sent, method, agency, id, nickname, street, postalCode, city } =
            data;
        const taxBase = rows.value.reduce(
            (acc, row) => acc + row.price * row.quantity,
            0
        );
        const formattedData = {
            id,
            landed: new Date(sent),
            agency,
            method,
            nickname,
            street,
            postalCode,
            city,
            taxBase
        };
        ticket.value = formattedData;
    } catch (error) {
        console.error(error);
    }
};

const getItems = async () => {
    try {
        const data = await jApi.query(
            `SELECT bi.id, bi.amount, bi.price, i.longName item,
            i.tag5, i.value5, i.tag6, i.value6, i.tag7, i.value7,
            i.image, im.updated
						FROM myOrderRow bi
            JOIN vn.item i ON i.id = bi.itemFk
            LEFT JOIN image im
            ON im.collectionFk = 'catalog'
            AND im.name = i.image
						WHERE orderFk = #id`,
            { id: orderId.value }
        );

        const formattedData = data.map(i => {
            const { amount: quantity, ...item } = i;

            const formattedItem = {
                quantity,
                ...item
            };
            return formattedItem;
        });

        rows.value = formattedData;
    } catch (error) {
        console.error(error);
    }
};

const fetchData = async () => {
    await getItems();
    await getOrder();
};
</script>

<template>
    <Teleport v-if="isHeaderMounted" to="#actions">
        <QBtn
            icon="settings"
            :label="t('configureOrder')"
            :to="{ name: 'checkout', params: { id: orderId } }"
            rounded
            no-caps
        >
            <QTooltip>{{ t('configureOrder') }}</QTooltip>
        </QBtn>
        <QBtn
            icon="shopping_bag"
            :label="t('catalog')"
            :to="{ name: 'catalog' }"
            rounded
            no-caps
        >
            <QTooltip>{{ t('catalog') }}</QTooltip>
        </QBtn>
        <QBtn
            icon="shopping_cart_checkout"
            :label="t('checkout')"
            :to="{ name: 'confirm', params: { id: orderId } }"
            rounded
            no-caps
            data-testid="basketToConfirmBtn"
        >
            <QTooltip>{{ t('checkout') }}</QTooltip>
        </QBtn>
    </Teleport>
    <QPage>
        <TicketDetails
            :rows="rows"
            :ticket="ticket"
            :show-tax="false"
            can-delete-items
            @on-row-deleted="fetchData"
        />
    </QPage>
</template>

<i18n lang="yaml">
en-US:
    configureOrder: Configure order
    checkout: Checkout
es-ES:
    configureOrder: Configurar pedido
    checkout: Finalizar pedido
ca-ES:
    configureOrder: Configurar encàrrec
    checkout: Finalitzar comanda
fr-FR:
    configureOrder: Définissez l'ordre
    checkout: Finir la commande
pt-PT:
    configureOrder: Configurar encomenda
    checkout: Finalizar encomenda
</i18n>
