<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 VnSelectFilter from 'src/components/common/VnSelectFilter.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
    />
    <FetchData
        url="Tickets"
        :filter="{ fields: ['id', 'nickname'], order: 'shipped DESC', limit: 30 }"
        @on-fetch="(data) => (ticketsOptions = data)"
        auto-load
    />
    <FetchData
        url="Clients"
        :filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }"
        @on-fetch="(data) => (clientsOptions = 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 class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnSelectFilter
                        :label="t('Ticket')"
                        :options="ticketsOptions"
                        hide-selected
                        option-label="id"
                        option-value="id"
                        v-model="data.ticketFk"
                        @update:model-value="data.clientFk = null"
                    >
                        <template #option="scope">
                            <QItem v-bind="scope.itemProps">
                                <QItemSection>
                                    <QItemLabel> #{{ scope.opt?.id }} </QItemLabel>
                                    <QItemLabel caption>{{
                                        scope.opt?.nickname
                                    }}</QItemLabel>
                                </QItemSection>
                            </QItem>
                        </template>
                    </VnSelectFilter>
                </div>
                <span class="row items-center" style="max-width: max-content">{{
                    t('Or')
                }}</span>
                <div class="col">
                    <VnSelectFilter
                        :label="t('Client')"
                        :options="clientsOptions"
                        hide-selected
                        option-label="name"
                        option-value="id"
                        v-model="data.clientFk"
                        @update:model-value="data.ticketFk = null"
                    />
                </div>
                <div class="col">
                    <VnInputDate :label="t('Max date')" v-model="data.maxShipped" />
                </div>
            </VnRow>
            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnSelectFilter
                        :label="t('Serial')"
                        :options="invoiceOutSerialsOptions"
                        hide-selected
                        option-label="description"
                        option-value="code"
                        v-model="data.serial"
                        :required="true"
                    />
                </div>
                <div class="col">
                    <VnSelectFilter
                        :label="t('Area')"
                        :options="taxAreasOptions"
                        hide-selected
                        option-label="code"
                        option-value="code"
                        v-model="data.taxArea"
                        :required="true"
                    />
                </div>
            </VnRow>
            <VnRow class="row q-gutter-md q-mb-md">
                <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>
