<script setup>
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useDialogPluginComponent } from 'quasar';

import VnInput from 'src/components/common/VnInput.vue';

const { dialogRef, onDialogOK } = useDialogPluginComponent();
const { t, availableLocales } = useI18n();

defineEmits(['confirm', ...useDialogPluginComponent.emits]);
const props = defineProps({
    subject: {
        type: String,
        required: false,
        default: 'Verdnatura',
    },
    phone: {
        type: String,
        required: true,
    },
    template: {
        type: String,
        required: false,
        default: '',
    },
    locale: {
        type: String,
        required: false,
        default: 'es',
    },
    data: {
        type: Object,
        required: false,
        default: null,
    },
    promise: {
        type: Function,
        required: true,
    },
});

const maxLength = 160;
const locale = ref(props.locale);
const subject = ref(props.subject);
const phone = ref(props.phone);
const message = ref('');

updateMessage();

function updateMessage() {
    const params = props.data;
    const key = props.template ? `templates['${props.template}']` : '';

    message.value = t(key, params, { locale: locale.value });
}

const totalLength = computed(() => message.value.length);
const color = computed(() => {
    if (totalLength.value == maxLength) return 'negative';
    if ((totalLength.value / maxLength) * 100 > 90) return 'warning';
    return 'positive';
});

const languages = availableLocales.map((locale) => ({ label: t(locale), value: locale }));

const isLoading = ref(false);
async function send() {
    const response = {
        destination: phone.value,
        message: message.value,
    };
    if (props.promise) {
        isLoading.value = true;

        try {
            Object.assign(response, props.data);
            await props.promise(response);
        } finally {
            isLoading.value = false;
        }
    }

    onDialogOK(response);
}
</script>

<template>
    <QDialog ref="dialogRef">
        <QCard class="q-pa-sm">
            <QCardSection class="row items-center q-pb-none">
                <span class="text-h6 text-grey">
                    {{ t('Send SMS') }}
                </span>
                <QSpace />
                <QBtn icon="close" :disable="isLoading" flat round dense v-close-popup />
            </QCardSection>
            <QCardSection class="q-pb-xs">
                <QSelect
                    :label="t('Language')"
                    :options="languages"
                    v-model="locale"
                    @update:model-value="updateMessage()"
                    emit-value
                    map-options
                    :input-debounce="0"
                    rounded
                    dense
                />
            </QCardSection>
            <QCardSection class="q-pb-xs">
                <VnInput :label="t('Phone')" v-model="phone" />
            </QCardSection>
            <QCardSection class="q-pb-xs">
                <VnInput v-model="subject" :label="t('Subject')" />
            </QCardSection>
            <QCardSection class="q-mb-md" q-input>
                <QInput
                    :label="t('Message')"
                    v-model="message"
                    type="textarea"
                    :maxlength="maxLength"
                    :counter="true"
                    :autogrow="true"
                    :bottom-slots="true"
                    :rules="[(value) => value.length < maxLength || 'Error!']"
                    stack-label
                    autofocus
                >
                    <template #append>
                        <QIcon
                            v-if="message !== ''"
                            name="close"
                            @click="message = ''"
                            class="cursor-pointer"
                        />
                        <QIcon name="info" class="cursor-pointer">
                            <QTooltip>
                                {{ t('messageTooltip') }}
                            </QTooltip>
                        </QIcon>
                    </template>
                    <template #counter>
                        <QChip :color="color" dense>
                            {{ totalLength }}/{{ maxLength }}
                        </QChip>
                    </template>
                </QInput>
            </QCardSection>
            <QCardActions align="right">
                <QBtn
                    :label="t('globals.cancel')"
                    color="primary"
                    :disable="isLoading"
                    flat
                    v-close-popup
                />
                <QBtn
                    :label="t('globals.confirm')"
                    @click="send()"
                    :loading="isLoading"
                    color="primary"
                    unelevated
                />
            </QCardActions>
        </QCard>
    </QDialog>
</template>

<style lang="scss" scoped>
.q-chip {
    transition: background 0.36s;
}
.q-card {
    width: 500px;
}
</style>

<i18n>
en:
    templates:
        pendingPayment: 'Your order is pending of payment.
            Please, enter the website and make the payment with a credit card. Thank you.'
        minAmount: 'A minimum amount of 50€ (VAT excluded) is required for your order
            { orderId } of { shipped } to receive it without additional shipping costs.'
        orderChanges: 'Order {orderId} of { shipped }: { changes }'
    en: English
    es: Spanish
    fr: French
    pt: Portuguese
    messageTooltip: Special characters like accents counts as multiple
es:
    Send SMS: Enviar SMS
    Language: Idioma
    Phone: Móvil
    Subject: Asunto
    Message: Mensaje
    messageTooltip: Carácteres especiales como acentos cuentan como varios
    templates:
        pendingPayment: 'Su pedido está pendiente de pago.
            Por favor, entre en la página web y efectue el pago con tarjeta. Muchas gracias.'
        minAmount: 'Te recordamos que tu pedido {orderId} es inferior a 50€.
            Te recomendamos amplíes para no generar costes extra, provocarán un incremento de tu tarifa.
            ¡Un saludo!'
        orderChanges: 'Pedido {orderId} con llegada estimada día { landing }: { changes }'
    en: Inglés
    es: Español
    fr: Francés
    pt: Portugués
fr:
    Send SMS: Envoyer SMS
    CustomerDefaultLanguage: Ce client utilise l'{locale} comme langue par défaut
    Language: Langage
    Phone: Mobile
    Subject: Affaire
    Message: Message
    messageTooltip: Les caractères spéciaux comme les accents comptent comme plusieurs
    templates:
        pendingPayment: 'Verdnatura : Commande en attente de règlement. Veuillez régler votre commande avant 9h.
            Sinon elle sera décalée en fonction de vos jours de livraison . Merci'
        minAmount: 'Verdnatura vous rappelle :
            Montant minimum nécessaire de 50 euros pour recevoir la commande { orderId } livraison { landing }.
            Merci.'
        orderChanges: 'Commande {orderId} livraison {landing} indisponible/s. Désolés pour le dérangement.'
    en: Anglais
    es: Espagnol
    fr: Français
    pt: Portugais
pt:
    Send SMS: Enviar SMS
    CustomerDefaultLanguage: Este cliente utiliza o <strong>{locale}</strong> como seu idioma padrão
    Language: Linguagem
    Phone: Móvel
    Subject: Assunto
    Message: Mensagem
    messageTooltip: Caracteres especiais como acentos contam como vários
    templates:
        pendingPayment: 'Seu pedido está pendente de pagamento.
            Por favor, acesse o site e faça o pagamento com cartão. Muito obrigado.'
        minAmount: 'É necessário um valor mínimo de 50€ (sem IVA) em seu pedido
            { orderId } do dia { landing } para recebê-lo sem custos de envio adicionais.'
        orderChanges: 'Pedido { orderId } com chegada dia { landing }: { changes }'
    en: Inglês
    es: Espanhol
    fr: Francês
    pt: Português
</i18n>
