<script setup>
import { ref, onBeforeMount } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { useQuasar } from 'quasar';

import TransferInvoiceForm from 'src/components/TransferInvoiceForm.vue';
import RefundInvoiceForm from 'src/components/RefundInvoiceForm.vue';
import SendEmailDialog from 'components/common/SendEmailDialog.vue';

import useNotify from 'src/composables/useNotify';
import { usePrintService } from 'composables/usePrintService';
import { useVnConfirm } from 'composables/useVnConfirm';
import { getUrl } from 'src/composables/getUrl';
import axios from 'axios';

onBeforeMount(async () => (salixUrl.value = await getUrl('')));

const $props = defineProps({
    invoiceOutData: {
        type: Object,
        default: () => {},
    },
    menuRef: {
        type: Object,
        default: () => {},
    },
});

const { notify } = useNotify();
const router = useRouter();
const { t } = useI18n();
const { openReport, sendEmail } = usePrintService();
const { openConfirmationModal } = useVnConfirm();
const quasar = useQuasar();
const salixUrl = ref();
const invoiceFormType = ref('pdf');
const defaultEmailAddress = ref($props.invoiceOutData.client?.email);

const showInvoicePdf = () => {
    openReport(`InvoiceOuts/${$props.invoiceOutData.id}/download`, {}, '_blank');
};

const showInvoiceCsv = () => {
    openReport(`InvoiceOuts/${$props.invoiceOutData.ref}/invoice-csv`, {
        recipientId: $props.invoiceOutData.client.id,
    });
};

const showSendInvoiceDialog = (type) => {
    invoiceFormType.value = type;
    quasar.dialog({
        component: SendEmailDialog,
        componentProps: {
            data: {
                address: defaultEmailAddress.value,
            },
            promise: sendEmailInvoice,
        },
    });
};

const sendEmailInvoice = async ({ address }) => {
    try {
        if (!address) notify(`The email can't be empty`, 'negative');

        if (invoiceFormType.value === 'pdf') {
            return sendEmail(`InvoiceOuts/${$props.invoiceOutData.ref}/invoice-email`, {
                recipientId: $props.invoiceOutData.client.id,
                recipient: address,
            });
        } else {
            return sendEmail(
                `InvoiceOuts/${$props.invoiceOutData.ref}/invoice-csv-email`,
                {
                    recipientId: $props.invoiceOutData.client.id,
                    recipient: address,
                }
            );
        }
    } catch (err) {
        console.error('Error sending email', err);
    }
};

const redirectToInvoiceOutList = () => {
    router.push({ name: 'InvoiceOutList' });
};

const deleteInvoice = async () => {
    try {
        await axios.post(`InvoiceOuts/${$props.invoiceOutData.id}/delete`);
        notify(t('InvoiceOut deleted'), 'positive');
    } catch (err) {
        console.error('Error deleting invoice out', err);
    }
};

const bookInvoice = async () => {
    try {
        await axios.post(`InvoiceOuts/${$props.invoiceOutData.ref}/book`);
        notify(t('InvoiceOut booked'), 'positive');
    } catch (err) {
        console.error('Error booking invoice out', err);
    }
};

const generateInvoicePdf = async () => {
    try {
        await axios.post(`InvoiceOuts/${$props.invoiceOutData.id}/createPdf`);
        notify(t('The invoice PDF document has been regenerated'), 'positive');
    } catch (err) {
        console.error('Error generating invoice out pdf', err);
    }
};

const refundInvoice = async (withWarehouse) => {
    try {
        const params = { ref: $props.invoiceOutData.ref, withWarehouse: withWarehouse };
        const { data } = await axios.post('InvoiceOuts/refund', params);
        location.href = window.origin + `/#/ticket/${data[0].id}/sale`;
        notify(
            t('refundInvoiceSuccessMessage', {
                refundTicket: data[0].id,
            }),
            'positive'
        );
    } catch (err) {
        console.error('Error generating invoice out pdf', err);
    }
};

const showTransferInvoiceForm = async () => {
    quasar.dialog({
        component: TransferInvoiceForm,
        componentProps: {
            invoiceOutData: $props.invoiceOutData,
        },
    });
};

const showRefundInvoiceForm = () => {
    quasar.dialog({
        component: RefundInvoiceForm,
        componentProps: {
            invoiceOutData: $props.invoiceOutData,
        },
    });
};
</script>

<template>
    <QItem v-ripple clickable>
        <QItemSection @click="showTransferInvoiceForm()">{{
            t('Transfer invoice to...')
        }}</QItemSection>
    </QItem>
    <QItem v-ripple clickable>
        <QItemSection>{{ t('Show invoice...') }}</QItemSection>
        <QItemSection side>
            <QIcon name="keyboard_arrow_right" />
        </QItemSection>
        <QMenu anchor="top end" self="top start">
            <QList>
                <QItem v-ripple clickable @click="showInvoicePdf()">
                    <QItemSection>{{ t('As PDF') }}</QItemSection>
                </QItem>
                <QItem v-ripple clickable @click="showInvoiceCsv()">
                    <QItemSection>{{ t('As CSV') }}</QItemSection>
                </QItem>
            </QList>
        </QMenu>
    </QItem>
    <QItem v-ripple clickable>
        <QItemSection>{{ t('Send invoice...') }}</QItemSection>
        <QItemSection side>
            <QIcon name="keyboard_arrow_right" />
        </QItemSection>
        <QMenu anchor="top end" self="top start">
            <QList>
                <QItem v-ripple clickable @click="showSendInvoiceDialog('pdf')">
                    <QItemSection>{{ t('Send PDF') }}</QItemSection>
                </QItem>
                <QItem v-ripple clickable @click="showSendInvoiceDialog('csv')">
                    <QItemSection>{{ t('Send CSV') }}</QItemSection>
                </QItem>
            </QList>
        </QMenu>
    </QItem>
    <QItem
        v-ripple
        clickable
        @click="
            openConfirmationModal(
                t('Confirm deletion'),
                t('Are you sure you want to delete this invoice?'),
                deleteInvoice,
                redirectToInvoiceOutList
            )
        "
    >
        <QItemSection>{{ t('Delete invoice') }}</QItemSection>
    </QItem>
    <QItem
        v-ripple
        clickable
        @click="
            openConfirmationModal(
                '',
                t('Are you sure you want to book this invoice?'),
                bookInvoice
            )
        "
    >
        <QItemSection>{{ t('Book invoice') }}</QItemSection>
    </QItem>
    <QItem
        v-ripple
        clickable
        @click="
            openConfirmationModal(
                t('Generate PDF invoice document'),
                t('Are you sure you want to generate/regenerate the PDF invoice?'),
                generateInvoicePdf
            )
        "
    >
        <QItemSection>{{ t('Generate PDF invoice') }}</QItemSection>
    </QItem>
    <QItem v-ripple clickable>
        <QItemSection>{{ t('Refund') }}</QItemSection>
        <QItemSection side>
            <QIcon name="keyboard_arrow_right" />
        </QItemSection>
        <QMenu anchor="top end" self="top start">
            <QList>
                <QItem v-ripple clickable @click="refundInvoice(true)">
                    <QItemSection>{{ t('With warehouse, no invoice') }}</QItemSection>
                </QItem>
                <QItem v-ripple clickable @click="refundInvoice(false)">
                    <QItemSection>{{ t('Without warehouse, no invoice') }}</QItemSection>
                </QItem>
                <QItem v-ripple clickable @click="showRefundInvoiceForm()">
                    <QItemSection>{{ t('Invoiced') }}</QItemSection>
                </QItem>
            </QList>
        </QMenu>
        <QTooltip>
            {{ t('Create a single ticket with all the content of the current invoice') }}
        </QTooltip>
    </QItem>
</template>

<i18n>
es:
    Transfer invoice to...: Transferir factura a...
    Show invoice...: Ver factura...
    Send invoice...: Enviar factura...
    Delete invoice: Eliminar factura
    Book invoice: Asentar factura
    Generate PDF invoice: Generar PDF factura
    Refund: Abono
    As PDF: como PDF
    As CSV: como CSV
    Send PDF: Enviar PDF
    Send CSV: Enviar CSV
    With warehouse, no invoice: Con almacén, sin factura
    Without warehouse, no invoice: Sin almacén, sin factura
    Invoiced: Facturado
    InvoiceOut deleted: Factura eliminada
    Confirm deletion: Confirmar eliminación
    Are you sure you want to delete this invoice?: Estas seguro de eliminar esta factura?
    Are you sure you want to book this invoice?: Estas seguro de querer asentar esta factura?
    InvoiceOut booked: Factura asentada
    Generate PDF invoice document: Generar PDF de la factura
    Are you sure you want to generate/regenerate the PDF invoice?: ¿Seguro que quieres generar/regenerar el PDF de la factura?
    The invoice PDF document has been regenerated: El documento PDF de la factura ha sido regenerado
    Create a single ticket with all the content of the current invoice: Crear un ticket único con todo el contenido de la factura actual
    refundInvoiceSuccessMessage: Se ha creado el siguiente ticket de abono {refundTicket}
    The email can't be empty: El email no puede estar vacío

en:
    refundInvoiceSuccessMessage: The following refund ticket have been created {refundTicket}
</i18n>
