<script setup lang="ts">
import { UpdateIcon } from '@bcc-code/icons-vue';
import { CometChatUIKitLoginListener } from '@cometchat/uikit-shared';
import { inject, Ref } from 'vue';
import chat from '../chat';
import { getAccessToken } from '../chat/accessToken';
import { getCurrentEnvironment } from '../chat/environment';
import { ChatInstance } from '../chat/types';

const chatInstance = inject<Ref<ChatInstance>>("chatInstance");

async function redirectToScheduledMessagesChat() {
    let schedMsgChatUid = CometChatUIKitLoginListener.getLoggedInUser()?.getUid()
    if (schedMsgChatUid && chatInstance) {
        let schedMsgChat;
        try {
            schedMsgChat = await chat.getGroup(schedMsgChatUid);
        } catch (error) {
            schedMsgChat = undefined;
        }
        if (!schedMsgChat) {
            const url = getCurrentEnvironment().chatApiBaseUrl + "/chats/" + schedMsgChatUid
            await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${getAccessToken()}`
                }
            }).then(async (res) => {
                if (res.ok) {
                    schedMsgChat = await chat.getGroup(schedMsgChatUid)
                }
            })

        }
        if (schedMsgChat) {
            chatInstance.value.scheduledMessageChat = schedMsgChat
            chatInstance.value.decoyAttachment = chatInstance.value.captionedAttachment
            chatInstance.value.captionedAttachment = null
            chatInstance.value.replyToMessage = null
            chatInstance.value.showScheduledMessagesChat = true
            chatInstance.value.userInput = document.querySelector<HTMLElement>(".messageinput-input")?.innerText ?? null;
        }
    }
}
</script>

<template>
    <div class="bcc-scheduled-message-icon">
        <UpdateIcon class="update-icon-style" @click="redirectToScheduledMessagesChat()"></UpdateIcon>
    </div>
</template>

<style lang="scss" scoped>
.update-icon-style {
    height: 24px;
    width: 24px;
    border: none;
    border-radius: 0;
    color: var(--cc__primary150, #3F4669);
    background: transparent;
    cursor: pointer;
    margin-right: -10px;
}
</style>
