{% extends 'example/base.html' %}

{% block title %}Chat Demo - Django-Chain Examples{% endblock %}

{% block content %}
<div id="alerts"></div>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
    <h1 class="h2">
        <i class="fas fa-comment-dots me-2"></i>Chat Demo
    </h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
            <button class="btn btn-sm btn-outline-secondary" onclick="clearChat()">
                <i class="fas fa-trash me-1"></i>Clear Chat
            </button>
            <button class="btn btn-sm btn-outline-primary" onclick="newSession()">
                <i class="fas fa-plus me-1"></i>New Session
            </button>
        </div>
    </div>
</div>

<div class="row">
    <!-- Chat Interface -->
    <div class="col-md-8">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-comments me-2"></i>Chat Interface
                </h5>
                <small class="text-muted">
                    Session: <span id="current-session">Not started</span>
                </small>
            </div>
            <div class="card-body">
                <!-- Chat Messages -->
                <div id="chat-messages" class="mb-3" style="height: 400px; overflow-y: auto; border: 1px solid #e9ecef; border-radius: 0.375rem; padding: 1rem;">
                    <div class="text-center text-muted">
                        <i class="fas fa-comment-alt fa-2x mb-2"></i>
                        <p>Start a conversation by typing a message below.</p>
                    </div>
                </div>

                <!-- Message Input -->
                <div class="input-group">
                    <input type="text" id="message-input" class="form-control"
                           placeholder="Type your message here..."
                           onkeypress="if(event.key==='Enter') sendMessage()">
                    <button class="btn btn-primary" onclick="sendMessage()" id="send-btn">
                        <i class="fas fa-paper-plane me-1"></i>Send
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Session Info & Recent Sessions -->
    <div class="col-md-4">
        <!-- Current Session Info -->
        <div class="card mb-3">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-info-circle me-2"></i>Session Information
                </h6>
            </div>
            <div class="card-body">
                <div id="session-info">
                    <p class="text-muted">No active session</p>
                </div>
            </div>
        </div>

        <!-- Recent Sessions -->
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-history me-2"></i>Recent Sessions
                </h6>
            </div>
            <div class="card-body">
                {% if recent_sessions %}
                    <div class="list-group list-group-flush">
                        {% for session in recent_sessions %}
                            <div class="list-group-item list-group-item-action p-2"
                                 onclick="loadSession('{{ session.session_id }}')"
                                 style="cursor: pointer;">
                                <div class="d-flex w-100 justify-content-between">
                                    <h6 class="mb-1">{{ session.title|truncatechars:20 }}</h6>
                                    <small>{{ session.created_at|date:"M d" }}</small>
                                </div>
                                <p class="mb-1 text-muted small">
                                    {{ session.messages.count }} messages
                                </p>
                                <small class="text-muted">{{ session.session_id|truncatechars:12 }}</small>
                            </div>
                        {% endfor %}
                    </div>
                {% else %}
                    <p class="text-muted small">No recent sessions</p>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- Demo Instructions -->
<div class="row mt-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-lightbulb me-2"></i>How to Use This Demo
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6>Features Demonstrated:</h6>
                        <ul class="list-unstyled">
                            <li><i class="fas fa-check text-success me-2"></i>Persistent chat sessions</li>
                            <li><i class="fas fa-check text-success me-2"></i>Message history storage</li>
                            <li><i class="fas fa-check text-success me-2"></i>Real-time LLM responses</li>
                            <li><i class="fas fa-check text-success me-2"></i>Session management</li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <h6>Try These Examples:</h6>
                        <ul class="list-unstyled">
                            <li><button class="btn btn-sm btn-outline-primary mb-1" onclick="sendExampleMessage('Hello! Can you help me understand Django-Chain?')">Ask about Django-Chain</button></li>
                            <li><button class="btn btn-sm btn-outline-primary mb-1" onclick="sendExampleMessage('What can you help me with?')">General capabilities</button></li>
                            <li><button class="btn btn-sm btn-outline-primary mb-1" onclick="sendExampleMessage('Explain how LLM workflows work')">Technical explanation</button></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentSessionId = null;
let messageCount = 0;

function sendMessage() {
    const messageInput = document.getElementById('message-input');
    const message = messageInput.value.trim();

    if (!message) return;

    // Clear input and disable send button
    messageInput.value = '';
    document.getElementById('send-btn').disabled = true;

    // Add user message to chat
    addMessageToChat('user', message);

    // Send to API
    const data = {
        message: message,
        session_id: currentSessionId
    };

    makeApiCall('{% url "example:chat_demo" %}', 'POST', data)
        .done(function(response) {
            // Add assistant response
            addMessageToChat('assistant', response.response);

            // Update session info
            currentSessionId = response.session_id;
            messageCount = response.message_count;
            updateSessionInfo();
        })
        .always(function() {
            // Re-enable send button
            document.getElementById('send-btn').disabled = false;
            messageInput.focus();
        });
}

function sendExampleMessage(message) {
    document.getElementById('message-input').value = message;
    sendMessage();
}

function addMessageToChat(role, content) {
    const chatMessages = document.getElementById('chat-messages');

    // Clear welcome message if this is the first message
    if (messageCount === 0 && role === 'user') {
        chatMessages.innerHTML = '';
    }

    const messageDiv = document.createElement('div');
    messageDiv.className = `mb-3 ${role === 'user' ? 'text-end' : ''}`;

    const isUser = role === 'user';
    const bgClass = isUser ? 'bg-primary text-white' : 'bg-light';
    const icon = isUser ? 'fas fa-user' : 'fas fa-robot';
    const alignment = isUser ? 'ms-auto' : 'me-auto';

    messageDiv.innerHTML = `
        <div class="d-inline-block p-3 rounded ${bgClass}" style="max-width: 70%;">
            <div class="d-flex align-items-start">
                <i class="${icon} me-2 mt-1"></i>
                <div class="flex-grow-1">
                    <small class="d-block mb-1 ${isUser ? 'text-white-50' : 'text-muted'}">${isUser ? 'You' : 'Assistant'}</small>
                    <div>${content}</div>
                </div>
            </div>
        </div>
    `;

    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

function updateSessionInfo() {
    const sessionInfo = document.getElementById('session-info');
    const currentSession = document.getElementById('current-session');

    if (currentSessionId) {
        currentSession.textContent = currentSessionId.substring(0, 8) + '...';
        sessionInfo.innerHTML = `
            <p><strong>Session ID:</strong> ${currentSessionId.substring(0, 12)}...</p>
            <p><strong>Messages:</strong> ${messageCount}</p>
            <p><strong>Status:</strong> <span class="badge bg-success">Active</span></p>
        `;
    }
}

function clearChat() {
    document.getElementById('chat-messages').innerHTML = `
        <div class="text-center text-muted">
            <i class="fas fa-comment-alt fa-2x mb-2"></i>
            <p>Start a conversation by typing a message below.</p>
        </div>
    `;
    messageCount = 0;
}

function newSession() {
    currentSessionId = null;
    messageCount = 0;
    clearChat();
    document.getElementById('current-session').textContent = 'Not started';
    document.getElementById('session-info').innerHTML = '<p class="text-muted">No active session</p>';
    showAlert('New session ready! Send a message to begin.', 'info');
}

function loadSession(sessionId) {
    // This would require additional API endpoint to load session history
    showAlert('Loading session history... (Feature coming soon)', 'info');
}

// Focus on message input when page loads
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('message-input').focus();
});
</script>
{% endblock %}
