<script setup>
import { onMounted, ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { storeToRefs } from 'pinia';

import FetchData from 'components/FetchData.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnInputDate from 'components/common/VnInputDate.vue';

import { useInvoiceOutGlobalStore } from 'src/stores/invoiceOutGlobal.js';

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

// invoiceOutGlobalStore state and getters
const { initialDataLoading, formInitialData, status } =
    storeToRefs(invoiceOutGlobalStore);

// invoiceOutGlobalStore actions
const { makeInvoice, setStatusValue } = invoiceOutGlobalStore;

const clientsToInvoice = ref('all');
const companiesOptions = ref([]);
const printersOptions = ref([]);
const serialTypesOptions = ref([]);

const handleInvoiceOutSerialsFetch = (data) => {
    serialTypesOptions.value = Array.from(
        new Set(data.map((item) => item.type).filter((type) => type)),
    );
};

const formData = ref({});

const optionsInitialData = computed(() => {
    const optionsArrays = [
        companiesOptions.value,
        printersOptions.value,
        serialTypesOptions.value,
    ];
    return optionsArrays.every((arr) => arr.length > 0);
});

const getStatus = computed({
    get() {
        return status.value;
    },
    set(value) {
        setStatusValue(value.value);
    },
});

onMounted(async () => {
    await invoiceOutGlobalStore.init();
    formData.value = { invoiceDate: formInitialData.value.invoiceDate };
});
</script>

<template>
    <FetchData
        url="Companies"
        @on-fetch="(data) => (companiesOptions = data)"
        auto-load
    />
    <FetchData url="Printers" @on-fetch="(data) => (printersOptions = data)" auto-load />
    <FetchData
        url="invoiceOutSerials"
        @on-fetch="handleInvoiceOutSerialsFetch"
        auto-load
    />
    <QForm
        v-if="!initialDataLoading && optionsInitialData"
        @submit="makeInvoice(formData, clientsToInvoice)"
        class="form-container q-pa-md"
        style="max-width: 256px"
    >
        <div class="column q-gutter-y-sm">
            <QRadio
                v-model="clientsToInvoice"
                dense
                val="all"
                :label="t('allClients')"
                :dark="true"
            />
            <QRadio
                v-model="clientsToInvoice"
                dense
                val="one"
                :label="t('oneClient')"
                :dark="true"
                class="q-mb-sm"
            />
            <VnSelect
                v-if="clientsToInvoice === 'one'"
                :label="t('client')"
                v-model="formData.clientId"
                url="Clients"
                option-value="id"
                option-label="name"
                hide-selected
                dense
                filled
                data-cy="InvoiceOutGlobalClientSelect"
            >
                <template #option="scope">
                    <QItem v-bind="scope.itemProps">
                        <QItemSection>
                            <QItemLabel>
                                #{{ scope.opt?.id }} {{ scope.opt?.name }}
                            </QItemLabel>
                        </QItemSection>
                    </QItem>
                </template>
            </VnSelect>
            <VnSelect
                :label="t('invoiceOutSerialType')"
                v-model="formData.serialType"
                @update:model-value="
                    invoiceOutGlobalStore.fetchInvoiceOutConfig(formData)
                "
                :options="serialTypesOptions"
                option-value="type"
                option-label="type"
                hide-selected
                dense
                filled
                data-cy="InvoiceOutGlobalSerialSelect"
            />
            <VnInputDate
                v-model="formData.invoiceDate"
                :label="t('invoiceDate')"
                filled
            />
            <VnInputDate
                v-model="formData.maxShipped"
                :label="t('maxShipped')"
                filled
                data-cy="InvoiceOutGlobalMaxShippedDate"
            />
            <VnSelect
                :label="t('company')"
                v-model="formData.companyFk"
                :options="companiesOptions"
                option-label="code"
                dense
                filled
                data-cy="InvoiceOutGlobalCompanySelect"
            />
            <VnSelect
                :label="t('printer')"
                v-model="formData.printer"
                :options="printersOptions"
                dense
                filled
                data-cy="InvoiceOutGlobalPrinterSelect"
            />
        </div>
        <QBtn
            v-if="!getStatus || getStatus === 'stopping'"
            :label="t('invoiceOut')"
            type="submit"
            color="primary"
            class="q-mt-md full-width"
            unelevated
            filled
            dense
            data-cy="formSubmitBtn"
        />
        <QBtn
            v-else
            :label="t('stop')"
            color="primary"
            class="q-mt-md full-width"
            unelevated
            filled
            dense
            @click="getStatus = 'stopping'"
            data-cy="formStopBtn"
        />
    </QForm>
</template>

<style scoped>
.form-container * {
    max-width: 100%;
}
</style>

<i18n>
en:
    invoiceDate: Invoice date
    maxShipped: Max date ticket
    allClients: All clients
    oneClient: One client
    company: Company
    printer: Printer
    invoiceOut: Invoice out
    client: Client
    invoiceOutSerialType: Serial Type
    stop: Stop

es:
    invoiceDate: Fecha de factura
    maxShipped: Fecha límite ticket
    allClients: Todos los clientes
    oneClient: Un solo cliente
    company: Empresa
    printer: Impresora
    invoiceOut: Facturar
    client: Cliente
    invoiceOutSerialType: Tipo de Serie
    stop: Parar
</i18n>
