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

import VnPaginate from 'src/components/ui/VnPaginate.vue';
import InvoiceOutSummary from './Card/InvoiceOutSummary.vue';
import VnSearchbar from 'src/components/ui/VnSearchbar.vue';
import VnLv from 'src/components/ui/VnLv.vue';
import CardList from 'src/components/ui/CardList.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import CustomerDescriptorProxy from '../Customer/Card/CustomerDescriptorProxy.vue';
import CreateManualInvoiceForm from 'src/components/CreateManualInvoiceForm.vue';

import InvoiceOutFilter from './InvoiceOutFilter.vue';
import { toDate, toCurrency } from 'src/filters/index';
import { useStateStore } from 'stores/useStateStore';
import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import { useSession } from 'src/composables/useSession';

const { t } = useI18n();
const router = useRouter();
const stateStore = useStateStore();
const session = useSession();
const token = session.getToken();
const { viewSummary } = useSummaryDialog();

const manualInvoiceDialogRef = ref(null);
const selectedCards = ref(new Map());

onMounted(() => (stateStore.rightDrawer = true));
onUnmounted(() => (stateStore.rightDrawer = false));

function navigate(id) {
    router.push({ path: `/invoice-out/${id}` });
}

const toggleIndividualCard = (cardData) => {
    if (selectedCards.value.has(cardData.id)) {
        selectedCards.value.delete(cardData.id);
        return;
    }
    selectedCards.value.set(cardData.id, cardData);
};

const toggleAllCards = (cardsData) => {
    const allSelected = selectedCards.value.size === cardsData.length;

    if (!allSelected) {
        // Si no todas las tarjetas están seleccionadas, selecciónalas todas
        cardsData.forEach((data) => {
            if (!selectedCards.value.has(data.id)) {
                selectedCards.value.set(data.id, data);
            }
        });
    } else {
        // Si todas las tarjetas están seleccionadas, deselecciónalas todas
        selectedCards.value.clear();
    }
};

const openPdf = () => {
    try {
        if (selectedCards.value.size === 0) return;
        const selectedCardsArray = Array.from(selectedCards.value.values());

        if (selectedCards.value.size === 1) {
            const [invoiceOut] = selectedCardsArray;
            const url = `api/InvoiceOuts/${invoiceOut.id}/download?access_token=${token}`;
            window.open(url, '_blank');
        } else {
            const invoiceOutIdsArray = selectedCardsArray.map(
                (invoiceOut) => invoiceOut.id
            );
            const invoiceOutIds = invoiceOutIdsArray.join(',');

            const params = new URLSearchParams({
                access_token: token,
                ids: invoiceOutIds,
            });

            const url = `api/InvoiceOuts/downloadZip?${params}`;
            window.open(url, '_blank');
        }
    } catch (err) {
        console.error('Error opening PDF');
    }
};

const openCreateInvoiceModal = () => {
    manualInvoiceDialogRef.value.show();
};
</script>

<template>
    <template v-if="stateStore.isHeaderMounted()">
        <Teleport to="#searchbar">
            <VnSearchbar
                :info="t('youCanSearchByInvoiceReference')"
                :label="t('searchInvoice')"
                data-key="InvoiceOutList"
            />
        </Teleport>
        <Teleport to="#actions-append">
            <div class="row q-gutter-x-sm">
                <QBtn
                    @click="stateStore.toggleRightDrawer()"
                    dense
                    flat
                    icon="menu"
                    round
                >
                    <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>
        <QScrollArea class="fit text-grey-8">
            <InvoiceOutFilter data-key="InvoiceOutList" />
        </QScrollArea>
    </QDrawer>
    <QPage>
        <VnPaginate
            auto-load
            data-key="InvoiceOutList"
            :order="['issued DESC', 'id DESC']"
            url="InvoiceOuts/filter"
        >
            <template #body="{ rows }">
                <VnSubToolbar class="bg-vn-dark justify-end">
                    <template #st-actions>
                        <QBtn
                            @click="openPdf()"
                            class="q-mr-md"
                            color="primary"
                            icon="cloud_download"
                            :disable="selectedCards.size === 0"
                        >
                            <QTooltip>{{ t('downloadPdf') }}</QTooltip>
                        </QBtn>
                        <QCheckbox
                            left-label
                            :label="t('globals.markAll')"
                            @click="toggleAllCards(rows)"
                            :model-value="selectedCards.size === rows.length"
                            class="q-mr-md"
                        />
                    </template>
                </VnSubToolbar>
                <div class="flex flex-center q-pa-md">
                    <div class="vn-card-list">
                        <CardList
                            :element="row"
                            :id="row.id"
                            :show-checkbox="true"
                            :is-selected="selectedCards.has(row.id)"
                            :key="row.id"
                            :title="row.ref"
                            @click="navigate(row.id)"
                            @toggle-card-check="toggleIndividualCard(row)"
                            v-for="row of rows"
                        >
                            <template #list-items>
                                <VnLv
                                    :label="t('invoiceOut.list.issued')"
                                    :value="toDate(row.issued)"
                                />
                                <VnLv
                                    :label="t('invoiceOut.list.amount')"
                                    :value="toCurrency(row.amount)"
                                />
                                <VnLv :label="t('invoiceOut.list.client')">
                                    <template #value>
                                        <span class="link" @click.stop>
                                            {{ row?.clientSocialName }}
                                            <CustomerDescriptorProxy
                                                :id="row?.clientFk"
                                            />
                                        </span>
                                    </template>
                                </VnLv>
                                <VnLv
                                    :label="t('invoiceOut.list.shortCreated')"
                                    :title-label="t('invoiceOut.list.created')"
                                    :value="toDate(row.created)"
                                />
                                <VnLv
                                    :label="t('invoiceOut.list.company')"
                                    :value="row.companyCode"
                                />
                                <VnLv
                                    :label="t('invoiceOut.list.shortDued')"
                                    :title-label="t('invoiceOut.list.dued')"
                                    :value="toDate(row.dued)"
                                />
                            </template>
                            <template #actions>
                                <QBtn
                                    :label="t('components.smartCard.openSummary')"
                                    @click.stop="viewSummary(row.id, InvoiceOutSummary)"
                                    color="primary"
                                    style="margin-top: 15px"
                                    type="submit"
                                />
                            </template>
                        </CardList>
                    </div>
                </div>
            </template>
        </VnPaginate>
        <QPageSticky :offset="[20, 20]">
            <QBtn fab icon="add" color="primary" @click="openCreateInvoiceModal()" />
            <QTooltip>
                {{ t('createInvoice') }}
            </QTooltip>
        </QPageSticky>

        <QDialog
            ref="manualInvoiceDialogRef"
            transition-show="scale"
            transition-hide="scale"
        >
            <CreateManualInvoiceForm />
        </QDialog>
    </QPage>
</template>

<i18n>
en:
    searchInvoice: Search issued invoice
    fileDenied: Browser denied file download...
    fileAllowed: Successful download of CSV file
    youCanSearchByInvoiceReference: You can search by invoice reference
    downloadPdf: Download PDF
    createInvoice: Make invoice
es:
    searchInvoice: Buscar factura emitida
    fileDenied: El navegador denegó la descarga de archivos...
    fileAllowed: Descarga exitosa de archivo CSV
    youCanSearchByInvoiceReference: Puedes buscar por referencia de la factura
    downloadPdf: Descargar PDF
    createInvoice: Crear factura
</i18n>
