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

import CardList from 'src/components/ui/CardList.vue';
import { currency, formatDateTitle } from 'src/lib/filters.js';
import { useVnConfirm } from 'src/composables/useVnConfirm.js';
import useNotify from 'src/composables/useNotify.js';
import { useAppStore } from 'src/stores/app.js';

const jApi = inject('jApi');
const { t } = useI18n();
const { openConfirmationModal } = useVnConfirm();
const { notify } = useNotify();
const store = useAppStore();
const router = useRouter();

const orders = ref([]);

const getOrders = async () => {
    try {
        orders.value = await jApi.query(
            `SELECT o.id, o.sent, o.deliveryMethodFk, o.taxableBase,
        a.nickname, am.description agency
        FROM myOrder o
        JOIN myAddress a ON a.id = o.addressFk
        JOIN vn.agencyMode am ON am.id = o.agencyModeFk
        WHERE NOT o.isConfirmed
        ORDER BY o.sent DESC`
        );
    } catch (error) {
        console.error('Error getting orders:', error);
    }
};

const removeOrder = async (id, index) => {
    try {
        await jApi.execQuery(
            `START TRANSACTION;
            DELETE FROM hedera.myOrder WHERE ((id = #id));
            COMMIT`,
            {
                id
            }
        );
        orders.value.splice(index, 1);
        notify(t('dataSaved'), 'positive');
    } catch (error) {
        console.error('Error removing order:', error);
    }
};

const loadOrder = orderId => {
    store.loadIntoBasket(orderId);
    router.push({ name: 'catalog' });
};

onMounted(async () => {
    getOrders();
});
</script>

<template>
    <Teleport :to="$actions">
        <QBtn
            :to="{ name: 'checkout' }"
            icon="add_shopping_cart"
            :label="t('newOrder')"
            rounded
            no-caps
        >
            <QTooltip>
                {{ t('newOrder') }}
            </QTooltip>
        </QBtn>
    </Teleport>
    <QPage class="vn-w-sm">
        <CardList
            v-for="(order, index) in orders"
            :key="index"
            :to="{ name: 'basket', params: { id: order.id } }"
        >
            <template #content>
                <QItemLabel class="text-bold q-mb-sm">
                    {{
                        formatDateTitle(order.sent)
                    }}
                </QItemLabel>
                <QItemLabel> #{{ order.id }} </QItemLabel>
                <QItemLabel>{{ order.nickname }}</QItemLabel>
                <QItemLabel>{{ order.agency }}</QItemLabel>
                <QItemLabel>{{ currency(order.taxableBase) }}</QItemLabel>
            </template>
            <template #actions>
                <QBtn
                    icon="delete"
                    flat
                    rounded
                    @click.stop.prevent="
                        openConfirmationModal(
                            null,
                            t('areYouSureDeleteOrder'),
                            () => removeOrder(order.id, index)
                        )
                    "
                />
                <QBtn
                    icon="shopping_bag"
                    flat
                    rounded
                    @click.stop.prevent="loadOrder(order.id)"
                />
            </template>
        </CardList>
    </QPage>
</template>

<style lang="scss" scoped></style>

<i18n lang="yaml">
en-US:
    newOrder: New order
    areYouSureDeleteOrder: Are you sure you want to delete the order?
es-ES:
    newOrder: Nuevo pedido
    areYouSureDeleteOrder: ¿Seguro que quieres borrar el pedido?
ca-ES:
    newOrder: Nova comanda
    areYouSureDeleteOrder: Segur que vols esborrar la comanda?
fr-FR:
    newOrder: Nouvelle commande
    areYouSureDeleteOrder: Êtes-vous sûr de vouloir supprimer la commande?
pt-PT:
    newOrder: Novo pedido
    areYouSureDeleteOrder: Tem certeza de que deseja excluir o pedido?
</i18n>
