<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: true,
    },
    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 = `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
                    outlined
                    dense
                />
            </QCardSection>
            <QCardSection class="q-pb-xs">
                <VnInput :label="t('Phone')" v-model="phone" is-outlined />
            </QCardSection>
            <QCardSection class="q-pb-xs">
                <VnInput v-model="subject" :label="t('Subject')" is-outlined />
            </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
                    outlined
                    autofocus
                >
                    <template #append>
                        <QIcon
                            v-if="message !== ''"
                            name="close"
                            @click="message = ''"
                            class="cursor-pointer"
                        />
                    </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
es:
    Send SMS: Enviar SMS
    Language: Idioma
    Phone: Móvil
    Subject: Asunto
    Message: Mensaje
    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: 'Es necesario un importe mínimo de 50€ (Sin IVA) en su pedido
            { orderId } del día { shipped } para recibirlo sin portes adicionales.'
        orderChanges: 'Pedido {orderId} día { shipped }: { 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
    templates:
        pendingPayment: 'Votre commande est en attente de paiement.
            Veuillez vous connecter sur le site web et effectuer le paiement par carte. Merci beaucoup.'
        minAmount: 'Un montant minimum de 50€ (TVA non incluse) est requis pour votre commande
            { orderId } du { shipped } afin de la recevoir sans frais de port supplémentaires.'
        orderChanges: 'Commande { orderId } du { shipped }: { changes }'
    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
    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 { shipped } para recebê-lo sem custos de envio adicionais.'
        orderChanges: 'Pedido { orderId } dia { shipped }: { changes }'
    en: Inglês
    es: Espanhol
    fr: Francês
    pt: Português
</i18n>
