{% extends 'base.html' %}

{% block content %}
<div class="row">
    <div class="col-md-3">
        <div class="card mb-3">
            <div class="card-header">
                <h5 class="mb-0">Collection: {{ collection.name }}</h5>
            </div>
            <div class="card-body">
                <p class="text-muted">{{ collection.description }}</p>
                <div class="mb-3">
                    <label for="model-select" class="form-label">Select Model:</label>
                    <select class="form-select mb-3" id="model-select" name="model_key">
                        <option value="tinyllama">TinyLlama 1.1B</option>
                        <option value="capybara">Capybara Hermes</option>
                    </select>
                </div>
                <a href="{% url 'document_collections:detail' collection.pk %}" class="btn btn-secondary btn-sm">View Collection</a>
            </div>
        </div>
    </div>
    
    <div class="col-md-9">
        <div class="card">
            <div class="card-header">
                <h3 class="mb-0">Chat Session</h3>
            </div>
            <div class="card-body">
                <div id="chat-messages" class="mb-3" style="height: 400px; overflow-y: auto;">
                    {% for message in session.messages.all %}
                        <div class="mb-2">
                            {% if message.is_user %}
                                <div class="d-flex justify-content-end">
                                    <div class="card bg-primary text-white" style="max-width: 75%;">
                                        <div class="card-body py-2 px-3">
                                            {{ message.content }}
                                        </div>
                                    </div>
                                </div>
                            {% else %}
                                <div class="d-flex justify-content-start">
                                    <div class="card bg-light" style="max-width: 75%;">
                                        <div class="card-body py-2 px-3">
                                            {{ message.content }}
                                        </div>
                                    </div>
                                </div>
                            {% endif %}
                        </div>
                    {% endfor %}
                </div>
                
                <form id="chat-form" class="mt-3">
                    {% csrf_token %}
                    <input type="hidden" id="session_id" name="session_id" value="{{ session.id }}">
                    <div class="input-group">
                        <input type="text" id="message" name="message" class="form-control" placeholder="Type your message..." required>
                        <button type="submit" class="btn btn-primary" id="send-button">
                            <span class="button-text">Send</span>
                            <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const chatMessages = document.getElementById('chat-messages');
    const chatForm = document.getElementById('chat-form');
    const sendButton = document.getElementById('send-button');
    const messageInput = document.getElementById('message');
    const sessionInput = document.getElementById('session_id');
    const modelSelect = document.getElementById('model-select');
    const buttonText = sendButton.querySelector('.button-text');
    const spinner = sendButton.querySelector('.spinner-border');

    function scrollToBottom() {
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    function setLoading(isLoading) {
        messageInput.disabled = isLoading;
        sendButton.disabled = isLoading;
        modelSelect.disabled = isLoading;
        buttonText.classList.toggle('d-none', isLoading);
        spinner.classList.toggle('d-none', !isLoading);
    }

    function appendMessage(content, isUser) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'mb-2';
        
        const messageHTML = isUser ?
            `<div class="d-flex justify-content-end">
                <div class="card bg-primary text-white" style="max-width: 75%;">
                    <div class="card-body py-2 px-3">${content}</div>
                </div>
            </div>` :
            `<div class="d-flex justify-content-start">
                <div class="card bg-light" style="max-width: 75%;">
                    <div class="card-body py-2 px-3">${content}</div>
                </div>
            </div>`;
            
        messageDiv.innerHTML = messageHTML;
        chatMessages.appendChild(messageDiv);
        scrollToBottom();
    }

    chatForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const message = messageInput.value.trim();
        const sessionId = sessionInput.value;
        const modelKey = modelSelect.value;
        
        console.log('Sending message:', message);
        console.log('Session ID:', sessionId);
        console.log('Model:', modelKey);
        
        if (!message || !sessionId) {
            console.error('Missing required fields');
            return;
        }

        setLoading(true);
        appendMessage(message, true);
        messageInput.value = '';

        try {
            const formData = new FormData();
            formData.append('message', message);
            formData.append('session_id', sessionId);
            formData.append('model_key', modelKey);
            
            const response = await fetch('{% url "chat:send_message" %}', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                }
            });
            
            const data = await response.json();
            console.log('Response:', data);
            
            if (response.ok && data.status === 'success') {
                appendMessage(data.response, false);
            } else {
                console.error('Server error:', data);
                appendMessage(`Error: ${data.error || 'Unknown error occurred'}`, false);
            }
        } catch (error) {
            console.error('Request error:', error);
            appendMessage(`Error: ${error.message}`, false);
        } finally {
            setLoading(false);
            messageInput.focus();
        }
    });

    // Initial scroll to bottom
    scrollToBottom();
});
</script>
{% endblock %}
{% endblock %}