<script setup lang="ts">
import { localize } from "@cometchat/uikit-resources";
import { SendIcon } from "@cometchat/chat-uikit-vue";
import { getCurrentInstance, inject, onBeforeUnmount, onMounted, Ref, ref, watchEffect } from "vue";
import { ChatInstance } from '../chat/types';
import { rescheduleMessage, sendScheduledMessage } from '../chat/scheduledMessage';
import BccScheduledMessageModal from './BccScheduledMessageModal.vue';

const props = defineProps({
    chatUid: { type: String, required: true }
})

const isReschedule = ref<boolean>(false);

const chatInstance = inject<Ref<ChatInstance>>("chatInstance");
const vueInstance: any = getCurrentInstance();
const msgComposerData = vueInstance?.parent?.type?.name === "CometChatMessageComposer" && vueInstance?.parent?.setupState;
const msgComposerProps = vueInstance?.parent?.type?.name === "CometChatMessageComposer" && vueInstance?.parent?.props;
const showModal = ref(false);

const sendButtonIconURL = SendIcon;
const sendButtonStyle = {
    height: "24px",
    width: "24px",
    border: "none",
    borderRadius: "0",
    buttonIconTint: "var(--cc__primary150, #57639e)",
    background: "transparent"
}

function sendMessage() {
    if (msgComposerData.messageToBeEdited && msgComposerData.showPreview) {
        msgComposerData?.customSendMethod(msgComposerData.inputRef.innerText)
    } else {
        openModal();
    }
}

function sendMessageOnEnter(textEnteredEvent: CustomEventInit) {
    if (!msgComposerData) return;
    msgComposerData.messageText = textEnteredEvent.detail.value;
    sendMessage()
    msgComposerData.showMentionsCountWarning = false;
    msgComposerData.showListForMentions = false;
}

const originalSendMessageOnEnter = msgComposerData?.sendMessageOnEnter;
onMounted(() => {
    if (!msgComposerData) return;
    msgComposerData.sendMessageOnEnter = sendMessageOnEnter;
});
onBeforeUnmount(() => {
    msgComposerData.sendMessageOnEnter = originalSendMessageOnEnter;
});

watchEffect(async () => {
    if (chatInstance && chatInstance.value.rescheduleInfo) {
        isReschedule.value = true;
        showModal.value = true;
    } else {
        isReschedule.value = false;
        showModal.value = false;
    }
})


function openModal() {
    const userInput = document.querySelector(".messageinput-input")?.innerText;
    if ((userInput && userInput !== "") || msgComposerProps.headerView !== undefined) {
        showModal.value = true;
    }
}

function closeModal() {
    showModal.value = false;
    if (chatInstance) chatInstance.value.rescheduleInfo = null;
}

function scheduleMessage(scheduleDate?: string) {
    if (scheduleDate && chatInstance) {
        sendScheduledMessage(scheduleDate, props.chatUid, chatInstance).then((msgSuccessful) => {
            if (!msgSuccessful) {
                showModal.value = false
                chatInstance.value.showAlert = true
                setTimeout(() => chatInstance.value.showAlert = false, 5000)
            } else {
                showModal.value = false
                msgComposerData.messageText = "";
                msgComposerData.textRef = "";
                msgComposerData.inputRef?.emptyInputField();
            }
        });
    }
}

function reschedule(scheduleDate?: string) {
    if (scheduleDate && chatInstance && chatInstance.value.rescheduleInfo) {
        rescheduleMessage(scheduleDate, props.chatUid, chatInstance.value.rescheduleInfo.rescheduleMuid, chatInstance.value.rescheduleInfo.messageId).then((successful) => {
            if (!successful) {
                showModal.value = false
                chatInstance.value.showRescheduleAlert = true
                setTimeout(() => chatInstance.value.showRescheduleAlert = false, 5000)
            } else {
                showModal.value = false
            }
        })
    }
}
</script>

<template>
    <div class="cc-messagecomposer-wrapper__sendbutton" ref="sendButton">
        <cometchat-button :iconURL="sendButtonIconURL" :buttonStyle="sendButtonStyle"
            :hoverText="localize('SCHEDULE_MESSAGE')" @click="sendMessage()" />
    </div>
    <BccScheduledMessageModal v-if="showModal" @close="closeModal()" @schedule="scheduleMessage" @reschedule="reschedule" :isReschedule="isReschedule">
    </BccScheduledMessageModal>
</template>
