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

import FetchData from 'components/FetchData.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnInput from 'src/components/common/VnInput.vue';
import FormModelPopup from './FormModelPopup.vue';
import VnInputDate from './common/VnInputDate.vue';

const emit = defineEmits(['onDataSaved']);

const { t } = useI18n();
const router = useRouter();

const manualInvoiceFormData = reactive({
    maxShipped: Date.vnNew(),
});

const formModelPopupRef = ref();
const invoiceOutSerialsOptions = ref([]);
const taxAreasOptions = ref([]);
const ticketsOptions = ref([]);
const clientsOptions = ref([]);
const isLoading = computed(() => formModelPopupRef.value?.isLoading);

const onDataSaved = async (formData, requestResponse) => {
    emit('onDataSaved', formData, requestResponse);
    if (requestResponse && requestResponse.id)
        router.push({ name: 'InvoiceOutSummary', params: { id: requestResponse.id } });
};
</script>

<template>
    <FetchData
        url="InvoiceOutSerials"
        :filter="{ where: { code: { neq: 'R' } }, order: ['code'] }"
        @on-fetch="(data) => (invoiceOutSerialsOptions = data)"
        auto-load
    />
    <FetchData
        url="TaxAreas"
        :filter="{ order: ['code'] }"
        @on-fetch="(data) => (taxAreasOptions = data)"
        auto-load
    />
    <FormModelPopup
        ref="formModelPopupRef"
        :title="t('Create manual invoice')"
        url-create="InvoiceOuts/createManualInvoice"
        model="invoiceOut"
        :form-initial-data="manualInvoiceFormData"
        @on-data-saved="onDataSaved"
    >
        <template #form-inputs="{ data }">
            <span v-if="isLoading" class="text-primary invoicing-text">
                <QIcon name="warning" class="fill-icon q-mr-sm" size="md" />
                {{ t('Invoicing in progress...') }}
            </span>
            <VnRow>
                <VnSelect
                    :label="t('Ticket')"
                    :options="ticketsOptions"
                    hide-selected
                    option-label="id"
                    option-value="id"
                    v-model="data.ticketFk"
                    @update:model-value="data.clientFk = null"
                    url="Tickets"
                    :where="{ refFk: null }"
                    :fields="['id', 'nickname']"
                    :filter-options="{ order: 'shipped DESC' }"
                >
                    <template #option="scope">
                        <QItem v-bind="scope.itemProps">
                            <QItemSection>
                                <QItemLabel> #{{ scope.opt?.id }} </QItemLabel>
                                <QItemLabel caption>{{ scope.opt?.nickname }}</QItemLabel>
                            </QItemSection>
                        </QItem>
                    </template>
                </VnSelect>
                <span class="row items-center" style="max-width: max-content">{{
                    t('Or')
                }}</span>
                <VnSelect
                    :label="t('Client')"
                    :options="clientsOptions"
                    hide-selected
                    option-label="name"
                    option-value="id"
                    v-model="data.clientFk"
                    @update:model-value="data.ticketFk = null"
                    url="Clients"
                    :fields="['id', 'name']"
                    :filter-options="{ order: 'name ASC' }"
                />
                <VnInputDate :label="t('Max date')" v-model="data.maxShipped" />
            </VnRow>
            <VnRow>
                <VnSelect
                    :label="t('Serial')"
                    :options="invoiceOutSerialsOptions"
                    hide-selected
                    option-label="description"
                    option-value="code"
                    v-model="data.serial"
                />
                <VnSelect
                    :label="t('Area')"
                    :options="taxAreasOptions"
                    hide-selected
                    option-label="code"
                    option-value="code"
                    v-model="data.taxArea"
                />
            </VnRow>
            <VnRow>
                <VnInput
                    :label="t('Reference')"
                    type="textarea"
                    v-model="data.reference"
                    fill-input
                    autogrow
                />
            </VnRow>
        </template>
    </FormModelPopup>
</template>

<style lang="scss" scoped>
.invoicing-text {
    display: flex;
    justify-content: center;
    align-items: center;
    color: $primary;
    font-size: 24px;
    margin-bottom: 8px;
}
</style>

<i18n>
es:
    Create manual invoice: Crear factura manual
    Ticket: Ticket
    Client: Cliente
    Max date: Fecha límite
    Serial: Serie
    Area: Area
    Reference: Referencia
    Or: O
    Invoicing in progress...: Facturación en progreso...
</i18n>
