<script setup>
import { ref, reactive, useAttrs, onBeforeMount, capitalize } from 'vue';
import axios from 'axios';
import { parsePhone } from 'src/filters';
import useOpenURL from 'src/composables/useOpenURL';

const props = defineProps({
    phoneNumber: { type: [String, Number], default: null },
    channel: { type: Number, default: null },
    country: { type: String, default: null },
});

const phone = ref(props.phoneNumber);
const config = reactive({
    sip: { icon: 'phone', href: `sip:${props.phoneNumber}` },
    'say-simple': {
        icon: 'vn:saysimple',
        url: null,
        channel: props.channel,
    },
});
const type = Object.keys(config).find((key) => key in useAttrs()) || 'sip';

onBeforeMount(async () => {
    if (!phone.value) return;
    let { channel } = config[type];

    if (type === 'say-simple') {
        const { url, defaultChannel } = (await axios.get('SaySimpleConfigs/findOne'))
            .data;
        if (!channel) channel = defaultChannel;

        phone.value = await parsePhone(props.phoneNumber, props.country.toLowerCase());
        config[
            type
        ].url = `${url}?customerIdentity=%2B${phone.value}&channelId=${channel}`;
    }
});

function handleClick() {
    if (config[type].url) useOpenURL(config[type].url);
    else if (config[type].href) window.location.href = config[type].href;
}
</script>
<template>
    <QBtn
        v-if="phone"
        flat
        round
        :icon="config[type].icon"
        size="sm"
        color="primary"
        padding="none"
        @click.stop="handleClick"
    >
        <QTooltip>
            {{ capitalize(type).replace('-', '') }}
        </QTooltip>
    </QBtn>
</template>
