<script setup>
import { onMounted, onUnmounted, computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useStateStore } from 'stores/useStateStore';
import InvoiceOutGlobalForm from './InvoiceOutGlobalForm.vue';
import { useInvoiceOutGlobalStore } from 'src/stores/invoiceOutGlobal.js';
import { storeToRefs } from 'pinia';
import { QBadge, QBtn } from 'quasar';
import CustomerDescriptor from 'src/pages/Customer/Card/CustomerDescriptor.vue';
import RightMenu from 'src/components/common/RightMenu.vue';

const stateStore = useStateStore();
const { t } = useI18n();
const invoiceOutGlobalStore = useInvoiceOutGlobalStore();

// invoiceOutGlobalStore state and getters
const {
    status,
    getPercentage,
    getAddressNumber,
    getNAddresses,
    nPdfs,
    totalPdfs,
    errors,
    addresses,
} = storeToRefs(invoiceOutGlobalStore);

const selectedCustomerId = ref(null);

const tableColumnComponents = {
    clientId: {
        component: QBtn,
        props: { flat: true, class: 'link' },
        event: (prop) => selectCustomerId(prop.value),
    },
    clientName: {
        component: 'span',
        props: {},
    },
    id: {
        component: 'span',
        props: {},
    },
    nickname: {
        component: 'span',
        props: {},
    },
    message: {
        component: QBadge,
        props: { color: 'red' },
    },
};

const columns = computed(() => [
    {
        align: 'left',
        name: 'clientId',
        label: 'Id',
        field: 'clientId',
    },
    {
        label: t('invoiceOut.globalInvoices.table.client'),
        field: 'clientName',
        name: 'clientName',
        align: 'left',
    },
    {
        label: t('invoiceOut.globalInvoices.table.addressId'),
        field: 'id',
        name: 'id',
        align: 'left',
    },
    {
        label: t('invoiceOut.globalInvoices.table.streetAddress'),
        field: 'nickname',
        name: 'nickname',
        align: 'left',
    },
    { label: 'Error', field: 'message', name: 'message', align: 'left' },
]);

const rows = computed(() => {
    if (!errors && !errors.length > 0) return [];
    return errors.value.map((row) => {
        return {
            ...row.client,
            message: row.message,
        };
    });
});

const selectCustomerId = (id) => {
    selectedCustomerId.value = id;
};

const statusText = computed(() => {
    const baseStatus = t(`status.${status.value}`);
    const clientId =
        status.value === 'invoicing'
            ? addresses.value[getAddressNumber.value]?.clientId || ''
            : '';

    return clientId ? `${baseStatus} ${clientId}`.trim() : baseStatus;
});

onMounted(() => (stateStore.rightDrawer = true));
onUnmounted(() => {
    stateStore.rightDrawer = false;
    invoiceOutGlobalStore.$reset();
});
</script>

<template>
    <RightMenu>
        <template #right-panel>
            <InvoiceOutGlobalForm />
        </template>
    </RightMenu>
    <QPage class="column items-center q-pa-md">
        <QCard v-if="status" class="card">
            <QCardSection class="card-section">
                <span class="text">{{ statusText }}</span>
                <span class="text">{{
                    t('invoiceOut.globalInvoices.statusCard.percentageText', {
                        getPercentage: getPercentage,
                        getAddressNumber: getAddressNumber,
                        getNAddresses: getNAddresses,
                    })
                }}</span>
                <span class="text">{{
                    t('invoiceOut.globalInvoices.statusCard.pdfsNumberText', {
                        nPdfs: nPdfs,
                        totalPdfs: totalPdfs,
                    })
                }}</span>
            </QCardSection>
        </QCard>

        <QTable
            v-if="rows.length > 0"
            :rows="rows"
            :columns="columns"
            row-key="id"
            class="full-width q-mt-md"
        >
            <template #body-cell="props">
                <QTd :props="props">
                    <component
                        :is="tableColumnComponents[props.col.name].component"
                        v-bind="tableColumnComponents[props.col.name].props"
                        @click="tableColumnComponents[props.col.name].event(props)"
                        class="col-content"
                    >
                        {{ props.value }}
                        <QPopupProxy>
                            <CustomerDescriptor
                                v-if="selectedCustomerId === props.value"
                                :id="selectedCustomerId"
                            />
                        </QPopupProxy>
                    </component>
                </QTd>
            </template>
        </QTable>
    </QPage>
</template>

<style lang="scss" scoped>
.card {
    display: flex;
    justify-content: center;
    width: 100%;
    background-color: var(--vn-section-color);
    padding: 16px;

    .card-section {
        display: flex;
        flex-direction: column;
        padding: 0px;
    }

    .text {
        font-size: 14px;
        color: var(--vn-text-color);
    }
}

.col-content {
    border-radius: 4px;
    padding: 6px;
}
</style>

<i18n>
en:
    status:
        packageInvoicing: Build packaging tickets
        invoicing: Invoicing client
        stopping: Stopping process
        done: Ended process
    of: of

es:
    status:
        packageInvoicing: Generación de tickets de empaque
        invoicing: Facturando a cliente
        stopping: Deteniendo proceso
        done: Proceso detenido
    of: de
</i18n>
