<script setup lang="ts">
import chat from "../chat";
import { Group } from "@cometchat/chat-sdk-javascript";
import { computed, inject, nextTick, onMounted, Ref, ref, watch, watchEffect } from 'vue';
import { ChatInstance } from '../chat/types';
import BccAttachmentBox from "./BccAttachmentBox.vue";
import BccChatSendButton from "./BccChatSendButton.vue";
import { getMessageComposerConfiguration, getMessageListConfiguration, getThreadedMessagesConfiguration } from "../chat/uiKit";
import { CometChatMessages } from "../chat/cometChatPatches";
import { MessageComposerConfiguration } from "@cometchat/uikit-shared";

const props = defineProps({
    chatUid: { type: String, required: true },
    chatGroup: { type: Group, required: true },
    hideDeletedMessages: { type: Boolean, required: false, default: false }
})

const isOffline = computed(() => chat.onlineStatus.value === 'offline');

const chatGroup = ref<Group>();

const chatInstance = inject<Ref<ChatInstance>>("chatInstance");
const messageComposerConfiguration = getMessageComposerConfiguration(chatInstance);
const messageListConfiguration = getMessageListConfiguration(props.hideDeletedMessages, chatInstance, chatGroup);
const threadedMessagesConfiguration = getThreadedMessagesConfiguration(chatGroup);
threadedMessagesConfiguration.messageComposerConfiguration = getThreadedMessageComposerConfig();

onMounted(async () => {
    chatGroup.value = props.chatGroup
    // attachEventlisteners();

    messageComposerConfiguration.value.text = chatInstance?.value.userInput ?? '';

    await nextTick();
    if (chatInstance?.value.decoyAttachment) {
        chatInstance.value.captionedAttachment = chatInstance.value.decoyAttachment
        chatInstance.value.decoyAttachment = null
    }
})

// onUnmounted(() => {
//     detachEventlisteners();
// })

watch(() => props.chatGroup,
    (group) => {
        chatGroup.value = group;
    }
);

watchEffect(() => {
    if (chatInstance && chatInstance.value.captionedAttachment) {
        messageComposerConfiguration.value.headerView = {
            componentName: BccAttachmentBox,
            props: {
                captionedAttachment: chatInstance.value.captionedAttachment
            }
        }

        messageComposerConfiguration.value.sendButtonView = {
            componentName: BccChatSendButton,
            props: {
                chatUid: props.chatUid
            }
        };
        // detachEventlisteners()
        // attachEventlisteners()
    } else {
        if (chatInstance && chatInstance.value.replyToMessage) {
            messageComposerConfiguration.value.headerView = {
                componentName: "bcc-reply-box",
                props: {
                    replyToMessage: chatInstance.value.replyToMessage,
                }
            };
        } else {
            messageComposerConfiguration.value.headerView = undefined;
        }
        messageComposerConfiguration.value.sendButtonView = undefined;
    }
});

function getThreadedMessageComposerConfig(): MessageComposerConfiguration {
    let composerConfig = { ...messageComposerConfiguration.value }
    composerConfig.auxilaryButtonView = undefined
    return composerConfig;
}

// Holding functionality temporarily disabled due to some bugs
//
// function attachEventlisteners() {
//     const interval = setInterval(() => {
//         const btns = document.querySelectorAll('.cc-messagecomposer-wrapper__sendbutton');
//         const sendButton = btns[btns.length - 1]
//         document.querySelector("body")?.addEventListener("contextmenu", (event) => event.preventDefault());

//         if (sendButton) {
//             sendButton.addEventListener("pointerdown", onMouseDown);
//             sendButton.addEventListener("pointerup", clearTimer);
//             sendButton.addEventListener("mouseleave", clearTimer);
//             sendButton.addEventListener("contextmenu", onContextMenu);
//             clearInterval(interval)
//         }
//     }, 500);
// }

// function detachEventlisteners() {
//     const btns = document.querySelectorAll('.cc-messagecomposer-wrapper__sendbutton');
//     const sendButton = btns[btns.length - 1]

//     if (sendButton) {
//         sendButton.removeEventListener("pointerdown", onMouseDown);
//         sendButton.removeEventListener("pointerup", clearTimer);
//         sendButton.removeEventListener("mouseleave", clearTimer);
//         sendButton.removeEventListener("contextmenu", onContextMenu);
//     }
// }

// function closeModal() {
//     showModal.value = false;
// }

// const showModal = ref(false);
// let timerId: string | number | NodeJS.Timeout | null | undefined;
// const duration = 500;
// let longPressDetected = false;

// const openPopup = () => {
//     showModal.value = true;
// }

// const onMouseDown = (event: Event) => {
//     const userInput = document.querySelector(".messageinput-input")?.innerText;
//     event.preventDefault();
//     event.stopPropagation();
//     if (userInput) {
//         // Only handle long press when there is user input
//         timerId = setTimeout(() => {
//             longPressDetected = true;
//             openPopup();
//         }, duration); // assuming duration is 500ms for long press
//     }
// };

// const onContextMenu = (event: Event) => {
//     if (longPressDetected) {
//         // Prevent context menu only when long press is detected
//         event.preventDefault();
//         event.stopPropagation();
//     }
// };

// const clearTimer = (event: Event) => {
//     event.preventDefault();
//     event.stopPropagation();
//     if (timerId !== null) {
//         clearTimeout(timerId);
//         timerId = null;
//     }
// }

const showAlert = ref<boolean>(false)

// function scheduleMessage(scheduleDate?: string) {
//     if (scheduleDate && chatInstance) {
//         sendScheduledMessage(scheduleDate, props.chatUid, chatInstance).then((msgSuccessful) => {
//             if (!msgSuccessful) {
//                 showModal.value = false
//                 showAlert.value = true
//                 setTimeout(() => showAlert.value = false, 3000)
//             }
//         })
//     }
// }

function isChannel(): boolean {
    return (props.chatGroup.getMetadata() as any)?.isChannel;
}

function isParticipant(): boolean {
    //if not part of the group return true anyway since getScope dosen't exist when not in the group
    if (!chatGroup.value?.getHasJoined()) {
        return true
    }
    return chatGroup.value?.getScope() == "participant";
}
</script>

<template>
    <div :class="'bcc-chat-message-list' + (isOffline ? ' offline' : '')">
        <CometChatMessages :hideMessageHeader="true" :disableSoundForMessages="true"
            :messageComposerConfiguration="messageComposerConfiguration"
            :messageListConfiguration="messageListConfiguration"
            :threadedMessagesConfiguration="threadedMessagesConfiguration"
            :hideMessageComposer="(isParticipant() && isChannel())" :hideDetails="true" :group="chatGroup" />
        <div v-if="chat.onlineStatus.value === 'offline' || !chat.connected.value"
            class="bcc-chat-message-composer-offline">
            <span v-if="isOffline">Waiting for network...</span>
            <span v-else>Connecting... </span>
        </div>
        <!-- <BccScheduledMessageModal v-if="showModal" @close="closeModal()" @send="scheduleMessage">
        </BccScheduledMessageModal>
        <BccAlert class="absolute top-0 w-[97%] mx-2 mt-1" icon closeButton context="danger" :open="showAlert"
            @close="showAlert = false">
            {{ localize("ERROR_SENDING_SCHEDULED_MESSAGE") }}
        </BccAlert> -->
    </div>
</template>
