document.addEventListener('DOMContentLoaded', () => {
    const contentContainer = document.getElementById('content-container');
    let currentChatId = null;
    let loggedInUserId = null;
    let lastMessageId = null;

    const getLoggedInUserId = async () => {
		try {
            const response = await fetch('../php/get_session_user.php');
            const data = await response.json();
            if (data.user_id) {
                loggedInUserId = data.user_id;
            } else {
                window.location.href = '../php/logout.php';
            }
        } catch (error) {
            console.error('Error fetching logged-in user ID:', error);
        }
	};

    const getChats = async () => {
        try {
            const response = await fetch('../php/get_chats.php');
            const data = await response.json();

            if (data.success) {
                return data.chats;
            } else {
                console.error('Error fetching chats:', data.message);
                return [];
            }
        } catch (error) {
            console.error('Error fetching chats:', error);
            return [];
        }
    };

    const getMessages = async (chatId) => {
        try {
            const response = await fetch(`../php/get_messages.php?chat_id=${chatId}`);
            const data = await response.json();

            if (data.success) {
                return data.messages;
            } else {
                console.error('Error fetching messages:', data.message);
                return [];
            }
        } catch (error) {
            console.error('Error fetching messages:', error);
            return [];
        }
    };

    const sendMessage = async (chatId, message) => {
        try {
            const response = await fetch('../php/send_message.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ chat_id: chatId, message }),
            });
            const data = await response.json();

            if (data.success) {
                return data.message_id;
            } else {
                console.error('Error sending message:', data.message);
                return null;
            }
        } catch (error) {
            console.error('Error sending message:', error);
            return null;
        }
    };
	const markMessagesAsRead = async (chatId) => {
    try {
        const response = await fetch('../php/mark_messages_as_read.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ chat_id: chatId }),
        });

        const data = await response.json();

        if (data.success) {
            console.log('Ziņas marķētas kā lasītas!');
        } else {
            console.error('Error marking messages as read:', data.message);
        }
    } catch (error) {
        console.error('Error marking messages as read:', error);
    }
};
    const renderChatContent = async (chatId) => {
        const messages = await getMessages(chatId);
        lastMessageId = messages.length > 0 ? messages[messages.length - 1].id : null;
		await markMessagesAsRead(chatId);
        const chatContentHTML = `
            <div class="message-list">
                ${messages
                    .map(
                        (msg) => `
                        <div data-message-id="${msg.id}" class="${msg.sender_id === loggedInUserId ? 'my-message-container' : 'their-message-container'}">
                            <span class="message-username">${msg.sender_name}</span>
                            <div class="${msg.sender_id === loggedInUserId ? 'my-message' : 'their-message'}">
                                <span>${msg.content}</span>
                            </div>
                        </div>
                    `
                    )
                    .join('')}
            </div>
            <div class="message-input-container">
                <input type="text" id="message-input" placeholder="Raksti savu ziņu šeit..." />
                <button id="send-message-button">Sūtīt</button>
            </div>
        `;

        const chatContent = document.querySelector('.messages-content-container');
        chatContent.innerHTML = chatContentHTML;

        scrollToBottom();

        const sendMessageHandler = async () => {
            const messageInput = document.getElementById('message-input');
            const message = messageInput.value.trim();
            messageInput.value = '';

            if (message) {
                const messageId = await sendMessage(chatId, message);
                if (messageId) {
                    const messageList = document.querySelector('.message-list');
                    if (!messageList.querySelector(`[data-message-id="${messageId}"]`)) {
                        const newMessageHTML = `
                            <div data-message-id="${messageId}" class="my-message-container">
                                <span class="message-username">Tu</span>
                                <div class="my-message">${message}</div>
                            </div>
                        `;
                        messageList.insertAdjacentHTML('beforeend', newMessageHTML);
                        scrollToBottom();
                    }
                }
            }
        };

        document.getElementById('send-message-button').addEventListener('click', sendMessageHandler);

        document.getElementById('message-input').addEventListener('keydown', (event) => {
            if (event.key === 'Enter') {
                event.preventDefault();
                sendMessageHandler();
            }
        });
    };

    const fetchUsers = async (loggedInUserId) => {
        try {
            const response = await fetch(`../php/get_users.php?user_id=${loggedInUserId}`);
            const data = await response.json();

            if (data.success) {
                return data.users;
            } else {
                console.error('Error fetching users:', data.message);
                return [];
            }
        } catch (error) {
            console.error('Error fetching users:', error);
            return [];
        }
    };

    const fetchClasses = async () => {
    try {
        const response = await fetch('../php/get_all_classes.php');
        const data = await response.json();

        if (data.success) {
            return data.classes;
        } else {
            console.error('Error fetching classes:', data.message);
            return [];
        }
    } catch (error) {
        console.error('Error fetching classes:', error);
        return [];
    }
};

const fetchUsersByLevel = async (level, classId = null) => {
    try {
        const url = `../php/get_users_by_level.php?level=${level}` + (classId ? `&class_id=${classId}` : '');
        const response = await fetch(url);
        const data = await response.json();

        if (data.success) {
            return data.users;
        } else {
            console.error('Error fetching users:', data.message);
            return [];
        }
    } catch (error) {
        console.error('Error fetching users:', error);
        return [];
    }
};


const openNewChatModal = async () => {
    const classes = await fetchClasses();

    const modalHTML = `
        <div class="modal-overlay">
            <div class="modal-content">
			<span class="close-modal">&times;</span>
                <h3>Sākt jaunu saraksti</h3>
                <label for="user-level-select">Lietotāja tips:</label>
                <select id="user-level-select">
                    <option value="2">Skolotāji</option>
                    <option value="3">Administrātori</option>
                    <option value="1">Skolnieki</option>
                </select>

                <div id="class-select-container" style="display: none;">
                    <label for="class-select">Grupa:</label>
                    <select id="class-select">
                        ${classes.map((cls) => `<option value="${cls.id}">${cls.class_name}</option>`).join('')}
                    </select>
                </div>

                <div id="user-list-container" style="display: none;">
                    <h4>Lietotāji</h4>
                    <ul id="user-list"></ul>
                </div>

                <div id="group-name-container" style="display: none;">
                    <label for="group-name-input">Grupas nosaukums</label>
                    <input type="text" id="group-name-input" placeholder="Ievadi grupas nosaukumu" />
                </div>

                <button id="create-chat-button" class="button" disabled>Izveidot</button>
            </div>
        </div>
    `;

    document.body.insertAdjacentHTML('beforeend', modalHTML);

    const userLevelSelect = document.getElementById('user-level-select');
    const classSelectContainer = document.getElementById('class-select-container');
    const classSelect = document.getElementById('class-select');
    const userListContainer = document.getElementById('user-list-container');
    const userList = document.getElementById('user-list');
    const groupNameContainer = document.getElementById('group-name-container');
    const groupNameInput = document.getElementById('group-name-input');
    const createChatButton = document.getElementById('create-chat-button');

    const selectedUsers = new Set();

    const updateUserList = async (level, classId = null) => {
        const users = await fetchUsersByLevel(level, classId);
        userList.innerHTML = users
            .map(
                (user) => `
                    <li class="user-item" data-user-id="${user.id}">
                        <input type="checkbox" class="user-checkbox" value="${user.id}" />
                        ${user.username}
                    </li>
                `
            )
            .join('');
        userListContainer.style.display = users.length > 0 ? 'block' : 'none';

        document.querySelectorAll('.user-checkbox').forEach((checkbox) => {
            checkbox.addEventListener('change', (event) => {
                const userId = event.target.value;
                if (event.target.checked) {
                    selectedUsers.add(userId);
                } else {
                    selectedUsers.delete(userId);
                }
                updateGroupLogic();
            });
        });
    };

    const updateGroupLogic = () => {
        if (selectedUsers.size > 1) {
            groupNameContainer.style.display = 'block';
            createChatButton.disabled = !groupNameInput.value.trim();
        } else {
            groupNameContainer.style.display = 'none';
            createChatButton.disabled = selectedUsers.size === 0;
        }
    };

    groupNameInput.addEventListener('input', () => {
        createChatButton.disabled = selectedUsers.size > 1 && !groupNameInput.value.trim();
    });

    createChatButton.addEventListener('click', async () => {
        const users = Array.from(selectedUsers);
        if (users.length === 1) {
            await createNewChat(users[0]);
        } else if (users.length > 1) {
            const groupName = groupNameInput.value.trim();
            if (groupName) {
                await createNewGroupChat(users, groupName);
            }
        }
        closeModal();
        initializeMessagesView();
    });

    userLevelSelect.addEventListener('change', async (event) => {
        const level = event.target.value;
        if (level === "1") {
            classSelectContainer.style.display = 'block';
            userListContainer.style.display = 'none';
        } else {
            classSelectContainer.style.display = 'none';
            await updateUserList(level);
        }
    });

    classSelect.addEventListener('change', async (event) => {
        const classId = event.target.value;
        await updateUserList(1, classId);
    });

    document.querySelector('.close-modal').addEventListener('click', closeModal);
};

const createNewGroupChat = async (userIds, groupName) => {
    try {
        const response = await fetch('../php/create_group_chat.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                logged_in_user_id: loggedInUserId,
                user_ids: userIds,
                group_name: groupName,
            }),
        });

        const data = await response.json();

        if (data.success) {
            console.log('Group chat created successfully.');
        } else {
            console.error('Error creating group chat:', data.message);
        }
    } catch (error) {
        console.error('Error creating group chat:', error);
    }
};

    const closeModal = () => {
        const modal = document.querySelector('.modal-overlay');
        if (modal) {
            modal.remove();
        }
    };

    const createNewChat = async (selectedUserId) => {
    try {
        const response = await fetch('../php/create_chat.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                logged_in_user_id: loggedInUserId,
                selected_user_id: selectedUserId,
            }),
        });

        const data = await response.json();

        if (data.success) {
			closeModal();
            renderChatContent(data.conversation_id);
            return true;
        } else if (data.conversation_id) {
			closeModal();
            renderChatContent(data.conversation_id);
            return false;
        } else {
            console.error('Error creating new chat:', data.message);
            return false;
        }
    } catch (error) {
        console.error('Error creating new chat:', error);
        return false;
    }
};



    const renderSidebar = (chats) => {
        const sidebarContainer = document.createElement('div');
        sidebarContainer.classList.add('messages-sidebar');

        const header = document.createElement('h3');
        header.classList.add('sidebar-header');
        header.textContent = 'Sarakstes';

        const newChatButton = document.createElement('button');
        newChatButton.classList.add('new-chat-button');
        newChatButton.textContent = '+';
        newChatButton.addEventListener('click', openNewChatModal);
        header.appendChild(newChatButton);

        const chatList = document.createElement('ul');
        chatList.classList.add('chat-list');

        chats.forEach((chat) => {
            const chatItem = document.createElement('li');
            chatItem.classList.add('chat-item');
            chatItem.setAttribute('data-chat-id', chat.conversation_id);
            chatItem.textContent = chat.is_group ? chat.conversation_name : chat.participant_name;

            if (chat.unread_count > 0) {
                const unreadMarker = document.createElement('span');
                unreadMarker.classList.add('unread-marker');
                unreadMarker.textContent = chat.unread_count;
                chatItem.appendChild(unreadMarker);
            }

            chatItem.addEventListener('click', () => {
                currentChatId = chat.conversation_id;
                renderChatContent(chat.conversation_id);
            });

            chatList.appendChild(chatItem);
        });

        sidebarContainer.appendChild(header);
        sidebarContainer.appendChild(chatList);

        const sidebarWrapper = document.querySelector('.messages-sidebar-container');
        sidebarWrapper.innerHTML = '';
        sidebarWrapper.appendChild(sidebarContainer);
    };

    const initializeMessagesView = async () => {
        contentContainer.innerHTML = `
            <div class="messages-container">
                <div class="messages-sidebar-container"></div>
                <div class="messages-content-container">
                    <p>Izvēlaties lietotāju vai grupu, lai apskatītu sarakstes!</p>
                </div>
            </div>
        `;

        await getLoggedInUserId();
        const chats = await getChats();
        renderSidebar(chats);

        setInterval(() => {
    if (localStorage.getItem('selectedContent') === 'messages') {
        fetchNewMessages();
        refreshChats();
    }
}, 3000);

    };

const fetchNewMessages = async () => {
    if (localStorage.getItem('selectedContent') !== 'messages') return;
    if (!currentChatId) return;

    const messages = await getMessages(currentChatId);
    const newMessages = messages.filter((msg) => msg.id > lastMessageId);

    if (newMessages.length > 0) {
        lastMessageId = newMessages[newMessages.length - 1].id;

        const messageList = document.querySelector('.message-list');
        newMessages.forEach((msg) => {
            if (!messageList.querySelector(`[data-message-id="${msg.id}"]`)) {
                const newMessageHTML = `
                    <div data-message-id="${msg.id}" class="${msg.sender_id === loggedInUserId ? 'my-message-container' : 'their-message-container'}">
                        <span class="message-username">${msg.sender_name}</span>
                        <div class="${msg.sender_id === loggedInUserId ? 'my-message' : 'their-message'}">
                            <span>${msg.content}</span>
                        </div>
                    </div>
                `;
                messageList.insertAdjacentHTML('beforeend', newMessageHTML);
            }
        });

        scrollToBottom(); 

        const activeChatItem = document.querySelector(`[data-chat-id="${currentChatId}"]`);
        const unreadMarker = activeChatItem.querySelector('.unread-marker');
        if (unreadMarker) {
            unreadMarker.remove();
        }

        await markMessagesAsRead(currentChatId);
    }
};


let displayedChatIds = new Set();

const refreshChats = async () => {
    if (localStorage.getItem('selectedContent') !== 'messages') return;

    try {
        const chats = await getChats();

        const sidebarContainer = document.querySelector('.chat-list');
        const existingChatIds = new Set(
            Array.from(sidebarContainer.querySelectorAll('.chat-item')).map((item) =>
                item.getAttribute('data-chat-id')
            )
        );

        const fetchedChatIds = new Set(chats.map((chat) => String(chat.conversation_id)));

        chats.forEach((chat) => {
            const chatId = String(chat.conversation_id);

            if (!existingChatIds.has(chatId)) {
                const chatItem = document.createElement('li');
                chatItem.classList.add('chat-item');
                chatItem.setAttribute('data-chat-id', chatId);
                chatItem.textContent = chat.is_group ? chat.conversation_name : chat.participant_name;

                if (chat.unread_count > 0) {
                    const unreadMarker = document.createElement('span');
                    unreadMarker.classList.add('unread-marker');
                    unreadMarker.textContent = chat.unread_count;
                    chatItem.appendChild(unreadMarker);
                }

                chatItem.addEventListener('click', () => {
                    currentChatId = chat.conversation_id;
                    renderChatContent(chat.conversation_id);
                });

                sidebarContainer.appendChild(chatItem);
            } else {
                const existingItem = sidebarContainer.querySelector(`[data-chat-id="${chatId}"]`);
                const unreadMarker = existingItem.querySelector('.unread-marker');

                if (chat.unread_count > 0) {
                    if (!unreadMarker) {
                        const newUnreadMarker = document.createElement('span');
                        newUnreadMarker.classList.add('unread-marker');
                        newUnreadMarker.textContent = chat.unread_count;
                        existingItem.appendChild(newUnreadMarker);
                    } else {
                        unreadMarker.textContent = chat.unread_count;
                    }
                } else if (unreadMarker) {
                    unreadMarker.remove();
                }

                if (chatId === String(currentChatId)) {
                    existingItem.classList.add('active-chat');
                } else {
                    existingItem.classList.remove('active-chat');
                }
            }
        });

        existingChatIds.forEach((chatId) => {
            if (!fetchedChatIds.has(chatId)) {
                const staleChatItem = sidebarContainer.querySelector(`[data-chat-id="${chatId}"]`);
                if (staleChatItem) staleChatItem.remove();
            }
        });
    } catch (error) {
        console.error('Error refreshing chats:', error);
    }
};


    const scrollToBottom = () => {
        const messageList = document.querySelector('.message-list');
        if (messageList) {
            messageList.scrollTop = messageList.scrollHeight;
        }
    };
	document.querySelectorAll('.sidebar button').forEach((button) => {
        button.addEventListener('click', (event) => {
            const content = event.target.getAttribute('data-content');
            if (content === 'messages') {
                initializeMessagesView();
                localStorage.setItem('selectedContent', content);
            }
        });
    });

    const savedContent = localStorage.getItem('selectedContent') || 'feed';
    if (savedContent === 'messages') {
        initializeMessagesView();
    }
});
