<script setup>
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';

import axios from 'axios';
import { useQuasar } from 'quasar';

import useNotify from 'src/composables/useNotify';
import VnSmsDialog from 'src/components/common/VnSmsDialog.vue';
import useOpenURL from 'src/composables/useOpenURL';

const $props = defineProps({
    customer: {
        type: Object,
        required: true,
    },
});
const { notify } = useNotify();
const { t } = useI18n();
const quasar = useQuasar();
const route = useRoute();

const showSmsDialog = () => {
    quasar.dialog({
        component: VnSmsDialog,
        componentProps: {
            phone: $props.customer.mobile || $props.customer.phone,
            promise: sendSms,
        },
    });
};

const sendSms = async (payload) => {
    payload.destinationFk = route.params.id;
    try {
        await axios.post(`Clients/${route.params.id}/sendSms`, payload);
        notify('globals.notificationSent', 'positive');
    } catch (error) {
        notify(error.message, 'positive');
    }
};

const openCreateForm = (type) => {
    const query = {
        table: {
            clientFk: $props.customer.id,
        },
        createForm: {
            addressId: $props.customer.defaultAddressFk,
        },
    };
    const clientFk = {
        ticket: 'clientId',
        order: 'clientFk',
    };
    const key = clientFk[type];
    if (!key) return;
    query.createForm[key] = $props.customer.id;

    const params = Object.entries(query)
        .map(([key, value]) => `${key}=${JSON.stringify(value)}`)
        .join('&');
    useOpenURL(`/#/${type}/list?${params}`);
};
</script>

<template>
    <QItem v-ripple clickable @click="openCreateForm('ticket')">
        <QItemSection>
            {{ t('globals.pageTitles.createTicket') }}
        </QItemSection>
    </QItem>
    <QItem v-ripple clickable @click="openCreateForm('order')">
        <QItemSection>
            {{ t('globals.pageTitles.createOrder') }}
        </QItemSection>
    </QItem>
    <QItem v-ripple clickable>
        <QItemSection @click="showSmsDialog()">{{ t('Send SMS') }}</QItemSection>
    </QItem>
</template>

<i18n>
es:
    Simple ticket: Ticket simple
    Send SMS: Enviar SMS
</i18n>
