{% extends 'base.html' %}
{% load static %}

{% block title %}Create New AI Agent{% endblock %}

{% block content %}
<div class="container-fluid h-100">
    <div class="row h-100">
        <main class="col-12 h-100" style="padding-top: 60px;">
            <div class="chat-container h-100 d-flex flex-column">
                <div class="chat-messages flex-grow-1 overflow-auto">
                    <div class="message-bubble received">
                        <p>Hello! I'm here to help you create a new AI agent. What is the agent's purpose?</p>
                    </div>
                </div>
                <div class="chat-input-container">
                    {% csrf_token %}
                    <div class="input-group">
                        <input type="text" id="userInput" class="form-control" placeholder="Describe your agent...">
                        <button class="btn btn-primary" id="sendButton">Send</button>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const sendButton = document.getElementById('sendButton');
    const userInput = document.getElementById('userInput');
    const chatMessages = document.querySelector('.chat-messages');

    sendButton.addEventListener('click', sendMessage);
    userInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });

    function sendMessage() {
        const messageText = userInput.value.trim();
        if (messageText === '') return;

        // Display user's message
        const userMessageBubble = document.createElement('div');
        userMessageBubble.className = 'message-bubble sent';
        userMessageBubble.innerHTML = `<p>${messageText}</p>`;
        chatMessages.appendChild(userMessageBubble);

        userInput.value = '';
        chatMessages.scrollTop = chatMessages.scrollHeight;

        // Get CSRF token
        const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

        // Send message to server and get response
        fetch('{% url 'create_agent' %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRFToken': csrftoken
            },
            body: `message=${encodeURIComponent(messageText)}`
        })
        .then(response => response.json())
        .then(data => {
            const botMessageBubble = document.createElement('div');
            botMessageBubble.className = 'message-bubble received';
            botMessageBubble.innerHTML = `<p>${data.message}</p>`;
            chatMessages.appendChild(botMessageBubble);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        });
    }
});
</script>
{% endblock %}