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

import axios from 'axios';
import { usePrintService } from 'composables/usePrintService';
import { useDialogPluginComponent, useQuasar } from 'quasar';

import { useState } from 'src/composables/useState';
import { useValidator } from 'src/composables/useValidator';
import useNotify from 'src/composables/useNotify';

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 VnInputDate from 'src/components/common/VnInputDate.vue';
import CustomerSamplesPreview from 'src/pages/Customer/components/CustomerSamplesPreview.vue';
import FormPopup from 'src/components/FormPopup.vue';

const { dialogRef, onDialogOK } = useDialogPluginComponent();

const { notify } = useNotify();
const { t } = useI18n();
const { validate } = useValidator();
const quasar = useQuasar();
const route = useRoute();
const router = useRouter();
const state = useState();
const user = state.getUser();
const { sendEmail } = usePrintService();
const hasChanged = ref(false);
const isLoading = ref(false);
const addressess = ref([]);
const companies = ref([]);
const optionsEmailUsers = ref([]);
const optionsSamplesVisible = ref([]);
const sampleType = ref({ hasPreview: false });
const initialData = reactive({});
const entityId = computed(() => route.params.id);
const customer = computed(() => state.get('customer'));
const filterEmailUsers = { where: { userFk: user.value.id } };
const filterClientsAddresses = {
    include: [
        { relation: 'province', scope: { fields: ['name'] } },
        { relation: 'agencyMode', scope: { fields: ['name'] } },
    ],
};
const filterCompanies = { order: ['code'] };
const filterSamplesVisible = {
    fields: [
        'id',
        'code',
        'description',
        'model',
        'hasCompany',
        'hasAddress',
        'hasPreview',
        'datepickerEnabled',
    ],
    order: ['description'],
};

defineEmits(['confirm', ...useDialogPluginComponent.emits]);

onBeforeMount(async () => {
    initialData.clientFk = customer.value.id;
    initialData.recipient = customer.value.email;
    initialData.recipientId = customer.value.id;
});

const setEmailUser = (data) => {
    optionsEmailUsers.value = data;
    initialData.replyTo = data[0]?.email;
};

const setClientsAddresses = (data) => {
    initialData.addressId = data[0].id;
    addressess.value = data;
};

const setSampleType = (sampleId) => {
    hasChanged.value = true;
    const { companyFk } = user.value;
    sampleType.value = optionsSamplesVisible.value.find((option) => {
        return option.id === sampleId;
    });
    initialData.companyFk = companyFk;
    initialData.companyId = companyFk;
};

const validateMessage = () => {
    if (!initialData.recipient) return 'Email cannot be blank';
    if (!sampleType.value) return 'Choose a sample';
    if (sampleType.value.hasCompany && !initialData.companyFk) return 'Choose a company';
    if (sampleType.value.datepickerEnabled && !initialData.from) return 'Choose a date';

    return '';
};

const setParams = (params) => {
    if (sampleType.value.hasCompany) params.companyId = initialData.companyFk;
    if (sampleType.value.datepickerEnabled) params.from = initialData.from;
    if (initialData.addressId) params.addressId = initialData.addressId;
};

const getPreview = async () => {
    try {
        const params = {
            recipientId: entityId,
        };
        const validationMessage = validateMessage();
        if (validationMessage) return notify(t(validationMessage), 'negative');

        setParams(params);

        const path = `${sampleType.value.model}/${entityId.value}/${sampleType.value.code}-html`;
        const { data } = await axios.get(path, { params });

        if (!data) return;
        quasar.dialog({
            component: CustomerSamplesPreview,
            componentProps: {
                htmlContent: data,
            },
        });
    } catch (err) {
        notify('Errors getting preview', 'negative');
    }
};

const onSubmit = async () => {
    isLoading.value = true;

    try {
        const { data } = await axios.patch('ClientSamples', initialData);
        notify('globals.dataSaved', 'positive');
        onDataSaved(data);
    } catch (error) {
        notify('errors.writeRequest', 'negative');
    } finally {
        isLoading.value = false;
    }
};

const getSamples = async () => {
    try {
        const filter = { where: { id: initialData.typeFk } };
        let { data } = await axios.get('Samples', {
            params: { filter: JSON.stringify(filter) },
        });
        return data[0];
    } catch (error) {
        notify('errors.create', 'negative');
    }
};

const onDataSaved = async () => {
    try {
        const params = {
            recipientId: initialData.recipientId,
            recipient: initialData.recipient,
            replyTo: initialData.replyTo,
        };
        setParams(params);
        const samplesData = await getSamples();
        const path = `${samplesData.model}/${entityId.value}/${samplesData.code}-email`;
        await sendEmail(path, params);
        onDialogOK(params);
    } catch (error) {
        notify('errors.create', 'negative');
    }
    toCustomerSamples();
};

const updateModelValue = () => {
    hasChanged.value = true;
};

const toCustomerSamples = () => {
    router.push({ name: 'CustomerSamples' });
};
</script>

<template>
    <FetchData
        :filter="filterEmailUsers"
        @on-fetch="setEmailUser"
        auto-load
        url="EmailUsers"
    />
    <FetchData
        :filter="filterClientsAddresses"
        :url="`Clients/${entityId}/addresses`"
        @on-fetch="setClientsAddresses"
        auto-load
    />
    <FetchData
        :filter="filterCompanies"
        @on-fetch="(data) => (companies = data)"
        auto-load
        url="Companies"
    />
    <FetchData
        :filter="filterSamplesVisible"
        @on-fetch="(data) => (optionsSamplesVisible = data)"
        auto-load
        url="Samples/visible"
    />

    <QDialog ref="dialogRef">
        <FormPopup
            :default-cancel-button="false"
            :default-submit-button="false"
            @on-submit="onSubmit()"
        >
            <template #custom-buttons>
                <QBtn
                    :disabled="isLoading || !sampleType?.hasPreview"
                    :label="t('Preview')"
                    :loading="isLoading"
                    @click.stop="getPreview()"
                    color="primary"
                    flat
                    icon="preview" /><QBtn
                    :disabled="!hasChanged"
                    :label="t('globals.save')"
                    :loading="isLoading"
                    @click="onSubmit"
                    color="primary"
                    icon="save"
            /></template>
            <template #form-inputs>
                <div class="col">
                    <VnSelect
                        :label="t('Sample')"
                        :options="optionsSamplesVisible"
                        @update:model-value="setSampleType"
                        hide-selected
                        option-label="description"
                        option-value="id"
                        v-model="initialData.typeFk"
                    />
                </div>

                <VnRow>
                    <div class="col">
                        <VnInput
                            :label="t('Recipient')"
                            @update:model-value="updateModelValue"
                            clearable
                            required="true"
                            v-model="initialData.recipient"
                        >
                            <template #append>
                                <QIcon name="info" class="cursor-pointer">
                                    <QTooltip>{{
                                        t('Its only used when sample is sent')
                                    }}</QTooltip>
                                </QIcon>
                            </template>
                        </VnInput>
                    </div>
                    <div class="col">
                        <VnInput
                            :label="t('Reply to')"
                            @update:model-value="updateModelValue"
                            clearable
                            required="true"
                            v-model="initialData.replyTo"
                        >
                            <template #append>
                                <QIcon name="info" class="cursor-pointer">
                                    <QTooltip>{{
                                        t('To who should the recipient replay?')
                                    }}</QTooltip>
                                </QIcon>
                            </template>
                        </VnInput>
                    </div>
                </VnRow>

                <VnRow
                    class="row q-gutter-md q-mb-md"
                    v-if="sampleType?.hasCompany || sampleType?.datepickerEnabled"
                >
                    <div class="col">
                        <VnSelect
                            :label="t('Company')"
                            :options="companies"
                            :rules="validate('entry.companyFk')"
                            hide-selected
                            option-label="code"
                            option-value="id"
                            required="true"
                            v-model="initialData.companyFk"
                            v-if="sampleType.hasCompany"
                        />
                    </div>
                    <div class="col">
                        <VnSelect
                            :label="t('Address')"
                            :options="addressess"
                            hide-selected
                            option-label="nickname"
                            option-value="id"
                            required="true"
                            v-model="initialData.addressId"
                            v-if="sampleType.id === 20"
                        >
                            <template #option="scope">
                                <QItem v-bind="scope.itemProps">
                                    <QItemSection>
                                        <QItemLabel>
                                            {{
                                                `${scope.opt.nickname}, ${scope.opt.street}, ${scope.opt.city}, ${scope.opt.province.name} - ${scope.opt.agencyMode.name}`
                                            }}
                                        </QItemLabel>
                                    </QItemSection>
                                </QItem>
                            </template>
                            <template #append>
                                <QIcon name="edit" class="cursor-pointer">
                                    <QTooltip>{{ t('Edit address') }}</QTooltip>
                                </QIcon>
                            </template>
                        </VnSelect>
                    </div>
                </VnRow>

                <VnRow
                    class="row q-gutter-md q-mb-md"
                    v-if="sampleType?.datepickerEnabled"
                >
                    <div class="col">
                        <VnInputDate
                            :label="t('Since')"
                            required="true"
                            v-model="initialData.from"
                        />
                    </div> </VnRow
            ></template>
        </FormPopup>
    </QDialog>
</template>

<i18n>
es:
    New sample: Crear plantilla
    Sample: Plantilla
    Recipient: Destinatario
    Reply to: Responder a
    Company: Empresa
    Address: Dirección
    Since: Desde
    Its only used when sample is sent: Se utiliza únicamente cuando se envía la plantilla
    To who should the recipient replay?: ¿A quien debería responder el destinatario?
    Edit address: Editar dirección
    Preview: Vista previa
    Email cannot be blank: Debes introducir un email
    Choose a sample: Selecciona una plantilla
    Choose a company: Selecciona una empresa
    Choose a date: Selecciona una fecha
</i18n>
