<script setup>
import { ref, reactive, useAttrs, onBeforeMount, capitalize } from 'vue';
import axios from 'axios';
import { dashIfEmpty, 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({
    'say-simple': {
        icon: 'vn:saysimple',
        url: null,
        channel: props.channel,
    },
    sip: { icon: 'phone', href: `sip:${props.phoneNumber}` },
});

const attrs = useAttrs();
const types = Object.keys(config)
    .filter((key) => key in attrs)
    .sort();
const activeTypes = types.length ? types : ['sip'];

onBeforeMount(async () => {
    if (!phone.value) return;

    for (const type of activeTypes) {
        if (type === 'say-simple') {
            let { channel } = config[type];
            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(type) {
    if (config[type].url) useOpenURL(config[type].url);
    else if (config[type].href) window.location.href = config[type].href;
}
</script>

<template>
    <div class="flex items-center gap-2">
        <template v-for="type in activeTypes">
            <QBtn
                :key="type"
                v-if="phone"
                flat
                round
                :icon="config[type].icon"
                size="sm"
                color="primary"
                padding="none"
                @click.stop="() => handleClick(type)"
            >
                <QTooltip>
                    {{ capitalize(type).replace('-', '') }}
                </QTooltip>
            </QBtn></template
        >
        <span>{{ dashIfEmpty(phone) }}</span>
    </div>
</template>
