document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('searchInput');
    const userFilter = document.getElementById('userFilter');
    const reloadButton = document.getElementById('reloadSessions');
    const sessionsContainer = document.getElementById('sessionsContainer');
    const messagesContainer = document.getElementById('messagesContainer');

    let selectedSessionId = null;

    function loadSessions() {
        const searchTerm = searchInput.value;
        const userFilterValue = userFilter.value;

        fetch(`admin/sessions.php?search=${searchTerm}&user_filter=${userFilterValue}`, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displaySessions(data.sessions);
            } else {
                console.error('Error loading sessions:', data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
    }

    function displaySessions(sessions) {
        sessionsContainer.innerHTML = '';
        sessions.forEach(session => {
            const sessionCard = document.createElement('div');
            sessionCard.className = `bg-white rounded-lg shadow-md p-4 mb-4 hover:shadow-lg transition duration-300 cursor-pointer ${selectedSessionId === session.id ? 'border-2 border-blue-500' : ''}`;
            sessionCard.innerHTML = `
                <h3 class="text-lg font-semibold mb-2">Session ID: ${session.id}</h3>
                <p>Username: ${session.username}</p>
                <p>Messages: ${session.message_count}</p>
                <p>Start Time: ${session.start_time}</p>
                <p>Last Use Time: ${session.last_use_time}</p>
            `;
            sessionCard.addEventListener('click', () => loadMessages(session.id));
            sessionsContainer.appendChild(sessionCard);
        });
    }

    function loadMessages(sessionId) {
        selectedSessionId = sessionId;
        fetch(`admin/get_messages.php?session_id=${sessionId}`, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayMessages(data.messages);
            } else {
                console.error('Error loading messages:', data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
        loadSessions(); // Refresh sessions to update selected state
    }

    function displayMessages(messages) {
        messagesContainer.innerHTML = '';
        messages.forEach(message => {
            const messageDiv = document.createElement('div');
            messageDiv.className = `mb-4 p-2 rounded-lg ${message.sender === 'user' ? 'bg-blue-100 ml-auto' : 'bg-gray-100'}`;
            messageDiv.style.maxWidth = '70%';
            messageDiv.innerHTML = `
                <p class="text-sm">${message.message}</p>
                <p class="text-xs text-gray-500 mt-1">${message.timestamp}</p>
            `;
            messagesContainer.appendChild(messageDiv);
        });
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    searchInput.addEventListener('input', debounce(loadSessions, 300));
    userFilter.addEventListener('change', loadSessions);
    reloadButton.addEventListener('click', loadSessions);

    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // Initial load
    loadSessions();
});