{% extends "layout.html.twig" %}

{% block title %}Messages Inbox - Local Lendables{% endblock %}

{% block content %}

<main class="container-fluid py-2">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h2 class="giantish mb-0" style="font-family: 'Cavolini Bold', Georgia, serif !important; font-weight: bold !important; font-size: 1.4rem !important;">My Messages</h2>
                <div>
                    <button id="toggleThreadedView" class="btn btn-success small">Display Message List</button>
                </div>
            </div>
            
            <!-- Sorting Controls -->
            <div class="row mb-3">
                <div class="col-12">
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-outline-secondary btn-sm" id="sortByDate">Sort by Date</button>
                        <button type="button" class="btn btn-outline-secondary btn-sm" id="sortByUsername">Sort by Username</button>
                    </div>
                </div>
            </div>
            
            <!-- Default Two-Column View -->
            <div id="defaultView" class="row" style="display: none;">
                <!-- Received Messages Column -->
                <div class="col-md-6">
                    <div class="card h-100">
                        <div class="card-header bg-primary text-white py-2">
                            <h5 class="mb-0 small">Received Messages (Unreturned Items Only)</h5>
                        </div>
                        <div class="card-body p-2" id="receivedContainer">
                            {% if unreturnedReceived|length > 0 %}
                                {% for message in unreturnedReceived %}
                                    <div class="border-bottom py-2 mb-2 message-item" data-date="{{ message.created_at|date('Y-m-d H:i:s') }}" data-username="{{ message.sender_name }}">
                                        <div class="d-flex align-items-start">
                                            <img src="{{ message.sender_avatar }}" width="30" height="30" class="rounded me-2">
                                            <div class="flex-grow-1">
                                                <div class="d-flex justify-content-between">
                                                    <span class="fw-bold midi">{{ message.sender_name ?: "Member" }}</span>
                                                    <span class="text-muted midi">{{ message.created_at|date('M j, g:i A') }}</span>
                                                </div>
                                                {% if message.item_name %}
                                                    <div class="text-muted midi">Re: 
                                                        <a href="/item/{{ message.item_id }}?chat=open" class="text-decoration-none">{{ message.item_name }}</a>
                                                        {% if message.loan_status %}
                                                            <span class="badge bg-warning text-dark ms-1">{{ message.loan_status|title }}</span>
                                                        {% endif %}
                                                    </div>
                                                {% endif %}
                                                <div style="font-family: Helvetica, Arial, sans-serif; font-size: 1rem; line-height: 1.3;">
                                                    {{ message.preview }}
                                                </div>
                                                {% if message.item_id %}
                                                    <div class="text-end mt-1">
                                                        <a href="/item/{{ message.item_id }}#chat-section" class="btn btn-sm btn-outline-primary small">View Conversation</a>
                                                    </div>
                                                {% endif %}
                                            </div>
                                        </div>
                                    </div>
                                {% endfor %}
                            {% else %}
                                <p class="text-muted midi">No received messages for unreturned items</p>
                            {% endif %}
                        </div>
                    </div>
                </div>
                
                <!-- Sent Messages Column -->
                <div class="col-md-6">
                    <div class="card h-100">
                        <div class="card-header bg-success text-white py-2">
                            <h5 class="mb-0 small">Sent Messages (Unreturned Items Only)</h5>
                        </div>
                        <div class="card-body p-2" id="sentContainer">
                            {% if unreturnedSent|length > 0 %}
                                {% for message in unreturnedSent %}
                                    <div class="border-bottom py-2 mb-2 message-item" data-date="{{ message.created_at|date('Y-m-d H:i:s') }}" data-username="{{ message.recipient_name }}">
                                        <div class="d-flex align-items-start">
                                            <img src="{{ message.recipient_avatar }}" width="30" height="30" class="rounded me-2">
                                            <div class="flex-grow-1">
                                                <div class="d-flex justify-content-between">
                                                    <span class="fw-bold midi">To: {{ message.recipient_name ?: "Member" }}</span>
                                                    <span class="text-muted midi">{{ message.created_at|date('M j, g:i A') }}</span>
                                                </div>
                                                {% if message.item_name %}
                                                    <div class="text-muted midi">Re: 
                                                        <a href="/item/{{ message.item_id }}?chat=open" class="text-decoration-none">{{ message.item_name }}</a>
                                                        {% if message.loan_status %}
                                                            <span class="badge bg-warning text-dark ms-1">{{ message.loan_status|title }}</span>
                                                        {% endif %}
                                                    </div>
                                                {% endif %}
                                                <div style="font-family: Helvetica, Arial, sans-serif; font-size: 1rem; line-height: 1.3;">
                                                    {{ message.preview }}
                                                </div>
                                                {% if message.item_id %}
                                                    <div class="text-end mt-1">
                                                        <a href="/item/{{ message.item_id }}#chat-section" class="btn btn-sm btn-outline-success small">View Conversation</a>
                                                    </div>
                                                {% endif %}
                                            </div>
                                        </div>
                                    </div>
                                {% endfor %}
                            {% else %}
                                <p class="text-muted midi">No sent messages for unreturned items</p>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>

            <!-- Threaded View (Default View) -->
            <div id="threadedView" class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header bg-info text-white py-2">
                            <h5 class="mb-0 small">Threaded Conversations (Unreturned Items Only)</h5>
                        </div>
                        <div class="card-body p-2" id="threadedContainer">
                            {% if threadedMessages|length > 0 %}
                                {% for thread in threadedMessages %}
                                    <div class="border-bottom py-3 mb-3 thread-item" data-date="{{ thread.last_message_date|date('Y-m-d H:i:s') }}" data-username="{{ thread.owner_name }}">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <div>
                                                <h6 class="mb-1 fw-bold">
                                                    <a href="/item/{{ thread.item_id }}?chat=open" class="text-decoration-none text-dark">
                                                        {{ thread.item_name }}
                                                    </a>
                                                </h6>
                                                <div class="d-flex align-items-center">
                                                    <img src="{{ thread.owner_avatar }}" width="25" height="25" class="rounded me-2">
                                                    <span class="midi me-2">{{ thread.owner_id == user.id ? 'You' : thread.owner_show_name }}</span>
                                                    <i class="fas fa-exchange-alt text-muted me-2" style="font-size: 0.8rem;"></i>
                                                    <img src="{{ thread.borrower_avatar }}" width="25" height="25" class="rounded me-2">
                                                    <span class="midi">{{ thread.borrower_id == user.id ? 'You' : thread.borrower_show_name }}</span>
                                                    <span class="badge bg-warning text-dark ms-2">{{ thread.loan_status|title }}</span>
                                                </div>
                                            </div>
                                            <div class="text-end">
                                                <span class="text-muted midi">{{ thread.total_messages }} messages</span><br>
                                                <span class="text-muted midi">{{ thread.last_message_date|date('M j, g:i A') }}</span>
                                            </div>
                                        </div>
                                        
                                        <!-- Expandable message list -->
                                        <div class="mt-2">
                                            <button class="btn btn-sm btn-outline-secondary expand-thread" data-thread-id="{{ thread.conversation_id }}">
                                                Show {{ thread.total_messages }} Messages
                                            </button>
                                            <div class="thread-messages mt-2" id="thread-{{ thread.conversation_id }}" style="display: none;">
                                                {% for message in thread.messages %}
                                                    <div class="border-start border-2 ps-3 mb-2 {{ message.sender_id == user.id ? 'border-success' : 'border-primary' }}">
                                                        <div class="d-flex justify-content-between">
                                                            <span class="fw-bold midi">{{ message.sender_id == user.id ? 'You' : message.sender_show_name }}</span>
                                                            <span class="text-muted midi">{{ message.created_at|date('M j, g:i A') }}</span>
                                                        </div>
                                                        <div style="font-family: Helvetica, Arial, sans-serif; font-size: 0.9rem; line-height: 1.3;">
                                                            {% if message.message_type == 'audio' and message.audio_path %}
                                                                <div class="d-flex align-items-center mb-1">
                                                                    <i class="fas fa-volume-up text-primary me-2"></i>
                                                                    <audio controls class="small" style="height: 25px;">
                                                                        <source src="{{ message.audio_path }}" type="audio/wav">
                                                                        Your browser does not support audio playback.
                                                                    </audio>
                                                                </div>
                                                                {% if message.transcription %}
                                                                    <div class="text-muted small">Transcription: {{ message.transcription }}</div>
                                                                {% endif %}
                                                            {% else %}
                                                                {{ message.full_content ?: message.preview }}
                                                            {% endif %}
                                                        </div>
                                                    </div>
                                                {% endfor %}
                                                <div class="mt-2">
                                                    <a href="/item/{{ thread.item_id }}#chat-section" class="btn btn-sm btn-primary">Join Conversation</a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                {% endfor %}
                            {% else %}
                                <p class="text-muted midi">No threaded conversations for unreturned items</p>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Toggle between threaded and default views
    const toggleButton = document.getElementById('toggleThreadedView');
    const defaultView = document.getElementById('defaultView');
    const threadedView = document.getElementById('threadedView');
    let isThreadedView = true;
    
    console.log('Elements found:', {
        toggleButton: !!toggleButton,
        defaultView: !!defaultView,
        threadedView: !!threadedView
    });

    // Initialize default state - threaded view is now default
    defaultView.style.display = 'none';
    threadedView.style.display = 'block';
    toggleButton.textContent = 'Display Message List';
    toggleButton.classList.remove('btn-warning');
    toggleButton.classList.add('btn-success');

    toggleButton.addEventListener('click', function() {
        console.log('Toggle button clicked, current state:', isThreadedView);
        if (isThreadedView) {
            defaultView.style.display = 'block';
            threadedView.style.display = 'none';
            toggleButton.textContent = 'Display Threaded Messages';
            toggleButton.classList.remove('btn-success');
            toggleButton.classList.add('btn-warning');
            isThreadedView = false;
            console.log('Switched to regular view');
        } else {
            defaultView.style.display = 'none';
            threadedView.style.display = 'block';
            toggleButton.textContent = 'Display Message List';
            toggleButton.classList.remove('btn-warning');
            toggleButton.classList.add('btn-success');
            isThreadedView = true;
            console.log('Switched to threaded view');
        }
    });

    // Sorting functionality
    const sortByDateBtn = document.getElementById('sortByDate');
    const sortByUsernameBtn = document.getElementById('sortByUsername');

    function sortMessages(container, sortBy) {
        const items = Array.from(container.querySelectorAll('.message-item, .thread-item'));
        items.sort((a, b) => {
            if (sortBy === 'date') {
                const dateA = new Date(a.dataset.date);
                const dateB = new Date(b.dataset.date);
                return dateB - dateA; // Most recent first
            } else if (sortBy === 'username') {
                const nameA = a.dataset.username?.toLowerCase() || '';
                const nameB = b.dataset.username?.toLowerCase() || '';
                return nameA.localeCompare(nameB);
            }
        });

        // Re-append sorted items
        items.forEach(item => container.appendChild(item));
    }

    sortByDateBtn.addEventListener('click', function() {
        // Sort received messages
        const receivedContainer = document.getElementById('receivedContainer');
        const sentContainer = document.getElementById('sentContainer');
        const threadedContainer = document.getElementById('threadedContainer');
        
        sortMessages(receivedContainer, 'date');
        sortMessages(sentContainer, 'date');
        sortMessages(threadedContainer, 'date');
        
        // Update button states
        sortByDateBtn.classList.add('active');
        sortByUsernameBtn.classList.remove('active');
    });

    sortByUsernameBtn.addEventListener('click', function() {
        // Sort received messages
        const receivedContainer = document.getElementById('receivedContainer');
        const sentContainer = document.getElementById('sentContainer');
        const threadedContainer = document.getElementById('threadedContainer');
        
        sortMessages(receivedContainer, 'username');
        sortMessages(sentContainer, 'username');
        sortMessages(threadedContainer, 'username');
        
        // Update button states
        sortByUsernameBtn.classList.add('active');
        sortByDateBtn.classList.remove('active');
    });

    // Thread expansion functionality
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('expand-thread')) {
            e.preventDefault();
            const threadId = e.target.dataset.threadId;
            const messagesDiv = document.getElementById('thread-' + threadId);
            const button = e.target;
            
            if (messagesDiv.style.display === 'none') {
                messagesDiv.style.display = 'block';
                button.textContent = 'Hide Messages';
                button.classList.remove('btn-outline-secondary');
                button.classList.add('btn-secondary');
            } else {
                messagesDiv.style.display = 'none';
                const messageCount = messagesDiv.querySelectorAll('.border-start').length;
                button.textContent = 'Show ' + messageCount + ' Messages';
                button.classList.remove('btn-secondary');
                button.classList.add('btn-outline-secondary');
            }
        }
    });

    // Initialize with date sorting as default
    sortByDateBtn.click();
});
</script>
{% endblock %}