<script setup>
import axios from 'axios';
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';
import { useStateStore } from 'stores/useStateStore';
import { useArrayData } from 'composables/useArrayData';
import VnPaginate from 'components/ui/VnPaginate.vue';
import VnConfirm from 'components/ui/VnConfirm.vue';
import CustomerDescriptorProxy from '../Card/CustomerDescriptorProxy.vue';
import { toDate, toCurrency } from 'filters/index';
import CustomerPaymentsFilter from './CustomerPaymentsFilter.vue';

const stateStore = useStateStore();
const quasar = useQuasar();
const { t } = useI18n();
const arrayData = useArrayData('CustomerTransactions');

async function confirm(transaction) {
    quasar
        .dialog({
            component: VnConfirm,
            componentProps: {
                data: transaction,
                title: t('Confirm transaction'),
                promise: confirmTransaction,
            },
        })
        .onOk((row) => (row.isConfirmed = true));
}

async function confirmTransaction({ id }) {
    await axios.post('Clients/confirmTransaction', { id });
    quasar.notify({
        message: t('Payment confirmed'),
        type: 'positive',
    });
}

const grid = ref(false);
const columns = computed(() => [
    {
        name: 'id',
        label: t('Transaction ID'),
        field: (row) => row.id,
        sortable: true,
    },
    {
        name: 'customerId',
        label: t('Customer ID'),
        field: (row) => row.clientFk,
        align: 'right',
        sortable: true,
    },
    {
        name: 'customer',
        label: t('Customer Name'),
        field: (row) => row.customerName,
    },
    {
        name: 'state',
        label: t('State'),
        field: (row) => row.isConfirmed,
        format: (value) => (value ? t('Confirmed') : t('Unconfirmed')),
        align: 'left',
        sortable: true,
    },
    {
        name: 'dated',
        label: t('Dated'),
        field: (row) => toDate(row.created),
        sortable: true,
    },
    {
        name: 'amount',
        label: t('Amount'),
        field: (row) => row.amount,
        format: (value) => toCurrency(value),
        sortable: true,
    },
    {
        name: 'actions',
        label: t('Actions'),
        grid: false,
    },
]);
const isLoading = computed(() => arrayData.isLoading.value);

function stateColor(row) {
    if (row.isConfirmed) return 'positive';
    return 'primary';
}
</script>

<template>
    <template v-if="stateStore.isHeaderMounted()">
        <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
        :breakpoint="1600"
    >
        <QScrollArea class="fit text-grey-8">
            <CustomerPaymentsFilter data-key="CustomerTransactions" />
        </QScrollArea>
    </QDrawer>
    <QPage class="column items-center q-pa-md customer-payments">
        <div class="vn-card-list">
            <QToolbar class="q-pa-none justify-end">
                <QBtn
                    @click="arrayData.refresh()"
                    :loading="isLoading"
                    icon="refresh"
                    color="primary"
                    class="q-mr-sm"
                    round
                    dense
                />
                <QBtn @click="grid = !grid" icon="list" color="primary" round dense>
                    <QTooltip>{{ t('Change view') }}</QTooltip>
                </QBtn>
            </QToolbar>
            <VnPaginate
                data-key="CustomerTransactions"
                url="Clients/transactions"
                order="created DESC"
                :limit="20"
                :offset="50"
                :auto-load="!!$route?.query.params"
            >
                <template #body="{ rows }">
                    <QTable
                        :dense="$q.screen.lt.md"
                        :columns="columns"
                        :rows="rows"
                        row-key="id"
                        :pagination="{ rowsPerPage: 0 }"
                        :grid="grid || $q.screen.lt.sm"
                        class="q-mt-xs custom-table"
                        hide-pagination
                    >
                        <template #body-cell-actions="{ row }">
                            <QTd auto-width class="text-center">
                                <QBtn
                                    v-if="!row.isConfirmed"
                                    icon="check"
                                    @click="confirm(row)"
                                    color="primary"
                                    size="md"
                                    round
                                    flat
                                    dense
                                >
                                    <QTooltip>{{ t('Confirm transaction') }}</QTooltip>
                                </QBtn>
                            </QTd>
                        </template>
                        <template #body-cell-id="{ row }">
                            <QTd auto-width align="right">
                                <span>
                                    {{ row.id }}
                                </span>
                            </QTd>
                        </template>
                        <template #body-cell-customerId="{ row }">
                            <QTd align="right">
                                <span class="link">
                                    {{ row.clientFk }}
                                    <CustomerDescriptorProxy :id="row.clientFk" />
                                </span>
                            </QTd>
                        </template>
                        <template #body-cell-customer="{ row }">
                            <QTd auto-width align="left" :title="row.customerName">
                                <span>
                                    {{ row.customerName }}
                                </span>
                            </QTd>
                        </template>
                        <template #body-cell-state="{ row }">
                            <QTd auto-width class="text-center">
                                <QBadge :color="stateColor(row)">
                                    {{
                                        row.isConfirmed
                                            ? t('Confirmed')
                                            : t('Unconfirmed')
                                    }}
                                </QBadge>
                            </QTd>
                        </template>
                        <template #item="{ cols, row }">
                            <div class="q-mb-md col-12">
                                <QCard class="q-pa-none">
                                    <QItem class="q-pa-none items-start">
                                        <QItemSection class="q-pa-none">
                                            <QList>
                                                <template
                                                    v-for="col of cols"
                                                    :key="col.name"
                                                >
                                                    <QItem
                                                        v-if="col.grid !== false"
                                                        class="q-pa-none"
                                                    >
                                                        <QItemSection>
                                                            <QItemLabel caption>
                                                                {{ col.label }}
                                                            </QItemLabel>
                                                            <QItemLabel
                                                                v-if="col.name == 'state'"
                                                            >
                                                                <QBadge
                                                                    :color="
                                                                        stateColor(row)
                                                                    "
                                                                >
                                                                    {{ col.value }}
                                                                </QBadge>
                                                            </QItemLabel>
                                                            <QItemLabel
                                                                v-if="col.name != 'state'"
                                                            >
                                                                {{ col.value }}
                                                            </QItemLabel>
                                                        </QItemSection>
                                                    </QItem>
                                                </template>
                                            </QList>
                                        </QItemSection>
                                        <template v-if="!row.isConfirmed">
                                            <QSeparator vertical />
                                            <QCardActions
                                                vertical
                                                class="justify-between"
                                            >
                                                <QBtn
                                                    icon="check"
                                                    @click="confirm(row)"
                                                    color="primary"
                                                    size="md"
                                                    round
                                                    flat
                                                    dense
                                                >
                                                    <QTooltip>
                                                        {{ t('Confirm transaction') }}
                                                    </QTooltip>
                                                </QBtn>
                                            </QCardActions>
                                        </template>
                                    </QItem>
                                </QCard>
                            </div>
                        </template>
                    </QTable>
                </template>
            </VnPaginate>
        </div>
    </QPage>
</template>

<style lang="scss">
.customer-payments {
    .q-table--dense .q-table th:first-child {
        padding-left: 0;
    }
    td {
        max-width: 130px;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}
</style>

<i18n>
es:
    Web Payments: Pagos Web
    Confirm transaction: Confirmar transacción
    Transaction ID: ID transacción
    Customer ID: ID cliente
    Customer Name: Nombre cliente
    State: Estado
    Dated: Fecha
    Amount: Importe
    Actions: Acciones
    Confirmed: Confirmada
    Unconfirmed: Sin confirmar
    Change view: Cambiar vista
    Payment confirmed: Pago confirmado
</i18n>
