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

import CardList from 'src/components/ui/CardList.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnConfirm from 'src/components/ui/VnConfirm.vue';

import { currency, formatDateTitle } from 'src/lib/filters.js';
import { tpvStore } from 'stores/tpv';

const { t } = useI18n();
const route = useRoute();
const jApi = inject('jApi');

const showAmountToPayDialog = ref(null);
const amountToPay = ref(null);
const orders = ref(null);
const debt = ref(0);
const tpv = tpvStore();

onMounted(async () => {
    await tpv.check(route);

    orders.value = await jApi.query('CALL myTicket_list(NULL, NULL)');
    debt.value = await jApi.getValue('SELECT -myClient_getDebt(NULL)');
});

const onPayClick = async () => {
    showAmountToPayDialog.value = true;

    if (debt.value <= 0) {
        amountToPay.value = -debt.value;
    }
};

const onConfirmPay = async () => {
    if (amountToPay.value) {
        const amount = amountToPay.value.toString().replace('.', ',');
        amountToPay.value = parseFloat(amount);
        await tpv.pay(amountToPay.value);
    }
};
</script>

<template>
    <Teleport :to="$actions">
        <div class="balance">
            <span class="label">{{ t('balance') }}</span>
            <span class="amount" :class="{ negative: debt < 0 }">
                {{ currency(debt || 0) }}
            </span>
            <QIcon name="info" class="info" size="sm">
                <QTooltip max-width="450px">
                    {{ t('paymentInfo') }}
                </QTooltip>
            </QIcon>
        </div>
        <QBtn
            icon="payments"
            :label="t('makePayment')"
            @click="onPayClick()"
            rounded
            no-caps
        >
            <QTooltip>
                {{ t('makePayment') }}
            </QTooltip>
        </QBtn>
        <QBtn
            :to="{ name: 'basket' }"
            icon="shopping_cart"
            :label="t('shoppingCart')"
            rounded
            no-caps
        >
            <QTooltip>
                {{ t('shoppingCart') }}
            </QTooltip>
        </QBtn>
    </Teleport>
    <QPage class="vn-w-sm">
        <div
            v-if="!orders?.length"
            class="text-subtitle1 text-center text-grey-7 q-pa-md"
        >
            {{ t('noOrdersFound') }}
        </div>
        <QList v-if="orders?.length">
            <CardList
                v-for="order in orders"
                :key="order.id"
                :to="`ticket/${order.id}`"
                tag="label"
            >
                <template #content>
                    <QItemLabel
                        class="full-width text-bold q-mb-sm flex row justify-between"
                    >
                        <span>{{ formatDateTitle(order.landed) }}</span>
                        <span>{{ currency(order.total) }}</span>
                    </QItemLabel>
                    <QItemLabel>#{{ order.id }}</QItemLabel>
                    <QItemLabel>{{ order.nickname }}</QItemLabel>
                    <QItemLabel>{{ order.agency }}</QItemLabel>
                </template>
            </CardList>
        </QList>
        <QPageSticky>
            <QBtn
                fab
                icon="add_shopping_cart"
                color="accent"
                :to="{ name: 'catalog' }"
                :title="t('startOrder')"
            />
        </QPageSticky>
        <VnConfirm
            v-model="showAmountToPayDialog"
            :message="t('amountToPay')"
            :promise="onConfirmPay"
        >
            <template #customHTML>
                <VnInput
                    v-model="amountToPay"
                    :clearable="false"
                    class="full-width"
                />
            </template>
        </VnConfirm>
    </QPage>
</template>

<style lang="scss" scoped>
.balance {
    margin-right: 8px;
    white-space: nowrap;
    display: inline-block;

    & > * {
        vertical-align: middle;
    }
    & > .amount {
        padding: 4px;
        margin: 0 4px;

        &.negative {
            background-color: #e55;
            border-radius: 2px;
            box-shadow: 0 0 5px #333;
        }
    }
    & > .info {
        cursor: pointer;
    }
}
</style>

<i18n lang="yaml">
en-US:
    startOrder: Start order
    noOrdersFound: No orders found
    makePayment: Make payment
    shoppingCart: Shopping cart
    balance: 'Balance:'
    paymentInfo: >-
        The amount shown is your slope (negative) or favorable balance today, it
        disregards future orders. For get your order shipped, this amount must be
        equal to or greater than 0. If you want to make a down payment, click the
        payment button, delete the suggested amount and enter the amount you want.
    amountToPay: 'Amount to pay (€):'
es-ES:
    startOrder: Empezar pedido
    noOrdersFound: No se encontrado pedidos
    makePayment: Realizar pago
    shoppingCart: Cesta de la compra
    balance: 'Saldo:'
    paymentInfo: >-
        La cantidad mostrada es tu saldo pendiente (negativa) o favorable a día de
        hoy, no tiene en cuenta pedidos del futuro. Para que tu pedido sea enviado,
        esta cantidad debe ser igual o mayor que 0. Si quieres realizar una entrega a
        cuenta, pulsa el botón de pago, borra la cantidad sugerida e introduce la
        cantidad que desees.
    amountToPay: 'Cantidad a pagar (€):'
ca-ES:
    startOrder: Començar encàrrec
    noOrdersFound: No s'han trobat comandes
    makePayment: Realitzar pagament
    shoppingCart: Cistella de la compra
    balance: 'Saldo:'
    paymentInfo: >-
        La quantitat mostrada és el teu saldo pendent (negatiu) o favorable a dia
        d'avui, no té en compte comandes del futur. Perquè la teva comanda sigui
        enviat, aquesta quantitat ha de ser igual o més gran que 0. Si vols fer un
        lliurament a compte, prem el botó de pagament, esborra la quantitat suggerida
        e introdueix la quantitat que vulguis.
    amountToPay: 'Quantitat a pagar (€):'
fr-FR:
    startOrder: Acheter
    noOrdersFound: Aucune commande trouvée
    makePayment: Effectuer un paiement
    shoppingCart: Panier
    balance: 'Balance:'
    paymentInfo: >-
        Le montant indiqué est votre pente (négative) ou balance favorable
        aujourd'hui, ne tient pas compte pour les commandes futures. Obtenir votre
        commande est expédiée, ce montant doit être égal ou supérieur à 0. Si vous
        voulez faire un versement, le montant suggéré effacé et entrez le montant que
        vous souhaitez.
    amountToPay: 'Montant à payer (€):'
pt-PT:
    startOrder: Iniciar encomenda
    noOrdersFound: Nenhum pedido encontrado
    makePayment: Realizar pagamento
    shoppingCart: Cesta da compra
    balance: 'Saldo:'
    paymentInfo: >-
        A quantidade mostrada é seu saldo pendente (negativo) ou favorável a dia de
        hoje, não se vincula a pedidos futuros. Para que seu pedido seja enviado, esta
        quantidade deve ser igual ou superior a 0. Se queres realizar um depósito à
        conta, clique no botão de pagamento, apague a quantidade sugerida e introduza
        a quantidade que deseje.
    amountToPay: 'Valor a pagar (€):'
</i18n>
