<script setup>
import {useDialogPluginComponent} from 'quasar';
import {useI18n} from 'vue-i18n';
import {computed, ref} from 'vue';
import VnInput from 'components/common/VnInput.vue';
import axios from 'axios';
import useNotify from "composables/useNotify";

const MESSAGE_MAX_LENGTH = 160;

const {t} = useI18n();
const {notify} = useNotify();
const props = defineProps({
    title: {
        type: String,
        required: true,
    },
    url: {
        type: String,
        required: true,
    },
    destination: {
        type: String,
        required: true,
    },
    destinationFk: {
        type: String,
        required: true,
    },
    data: {
        type: Object,
        default: () => ({}),
    },
});

const emit = defineEmits([...useDialogPluginComponent.emits, 'sent']);
const {dialogRef, onDialogHide} = useDialogPluginComponent();

const smsRules = [
    (val) => (val && val.length > 0) || t("The message can't be empty"),
    (val) =>
        (val && new Blob([val]).size <= MESSAGE_MAX_LENGTH) ||
        t("The message it's too long"),
];

const message = ref('');

const charactersRemaining = computed(
    () => MESSAGE_MAX_LENGTH - new Blob([message.value]).size
);

const charactersChipColor = computed(() => {
    if (charactersRemaining.value < 0) {
        return 'negative';
    }
    if (charactersRemaining.value <= 25) {
        return 'warning';
    }
    return 'primary';
});

const onSubmit = async () => {
    if (!props.destination) {
        throw new Error(`The destination can't be empty`);
    }

    if (!message.value) {
        throw new Error(`The message can't be empty`);
    }

    if (charactersRemaining.value < 0) {
        throw new Error(`The message it's too long`);
    }

    const response = await axios.post(props.url, {
        destination: props.destination,
        destinationFk: props.destinationFk,
        message: message.value,
        ...props.data,
    });

    if (response.data) {
        emit('sent', response.data);
        notify('globals.smsSent', 'positive');
    }
    emit('ok', response.data);
    emit('hide', response.data);
};
</script>

<template>
    <QDialog ref="dialogRef" @hide="onDialogHide">
        <QCard class="full-width dialog">
            <QCardSection class="row">
                <span v-if="title" class="text-h6">{{ title }}</span>
                <QSpace />
                <QBtn icon="close" flat round dense v-close-popup />
            </QCardSection>
            <QForm @submit="onSubmit">
                <QCardSection>
                    <VnInput
                        v-model="message"
                        type="textarea"
                        :rules="smsRules"
                        :label="t('Message')"
                        :placeholder="t('Message')"
                        :rows="5"
                        required
                        clearable
                        no-error-icon
                    >
                        <template #append>
                            <QIcon name="info">
                                <QTooltip>
                                    {{
                                        t(
                                            'Special characters like accents counts as a multiple'
                                        )
                                    }}
                                </QTooltip>
                            </QIcon>
                        </template>
                    </VnInput>
                    <p class="q-mb-none q-mt-md">
                        {{ t('Characters remaining') }}:
                        <QChip :color="charactersChipColor">
                            {{ charactersRemaining }}
                        </QChip>
                    </p>
                </QCardSection>
                <QCardActions align="right">
                    <QBtn type="button" flat v-close-popup class="text-primary">
                        {{ t('globals.cancel') }}
                    </QBtn>
                    <QBtn type="submit" color="primary">{{ t('Send') }}</QBtn>
                </QCardActions>
            </QForm>
        </QCard>
    </QDialog>
</template>

<style lang="scss" scoped>
.dialog {
    max-width: 450px;
}
</style>
<i18n>
es:
    Message: Mensaje
    Send: Enviar
    Characters remaining: Carácteres restantes
    Special characters like accents counts as a multiple: Carácteres especiales como los acentos cuentan como varios
    The destination can't be empty: El destinatario no puede estar vacio
    The message can't be empty: El mensaje no puede estar vacio
    The message it's too long: El mensaje es demasiado largo
</i18n>
