<!DOCTYPE html>
<html lang="en">
<head>
    <title>Create New Agent</title>
    {{template "old/views/partials/header"}}
    <script src="/old/public/js/wizard.js"></script>
    <link rel="stylesheet" href="/old/public/css/wizard.css">
    <script src="/old/public/js/connector-templates.js"></script>
    <script src="/old/public/js/agent-form.js"></script>
</head>
<body>
    {{template "old/views/partials/menu"}}
    <div class="container">
        <div class="section-box">
            <h1>Create New Agent</h1>
            
            <form id="create-agent-form" action="/api/agent/create" method="POST">
                {{template "old/views/partials/agent-form" . }}

                <button type="submit" id="create-button" data-original-text="<i class='fas fa-robot'></i> Create Agent">
                    <i class="fas fa-robot"></i> Create Agent
                </button>
            </form>
        </div>

        <!-- Response Messages Container -->
        <div id="response-container">
            <!-- Alert messages will be shown here -->
            <div id="success-alert" class="alert alert-success" style="display: none;">
                Agent created successfully! Redirecting to agent list...
            </div>
            
            <div id="error-alert" class="alert alert-error" style="display: none;">
                <span id="error-message">Error creating agent.</span>
            </div>
        </div>
    </div>

    <!-- Toast notification container -->
    <div id="toast" class="toast">
        <span id="toast-message"></span>
    </div>

    <script>
        const actions = `{{ range .Actions }}<option value="{{.}}">{{.}}</option>{{ end }}`;
        const connectors = `{{ range .Connectors }}<option value="{{.}}">{{.}}</option>{{ end }}`;
        const promptBlocks = `{{ range .PromptBlocks }}<option value="{{.}}">{{.}}</option>{{ end }}`;

        document.addEventListener('DOMContentLoaded', function() {
            // Initialize common form components
            initAgentFormCommon({
                actions: actions,
                connectors: connectors,
                promptBlocks: promptBlocks
            });
            
            // Form submission handling
            const form = document.getElementById('create-agent-form');
            
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                
                // Show loading state
                const createButton = document.getElementById('create-button');
                const originalButtonText = createButton.innerHTML;
                createButton.setAttribute('data-original-text', originalButtonText);
                createButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Creating...';
                createButton.disabled = true;
                
                // Build a structured data object
                const formData = new FormData(form);
                const jsonData = AgentFormUtils.processFormData(formData);
                
                // Process special fields
                jsonData.connectors = AgentFormUtils.processConnectors(createButton);
                if (jsonData.connectors === null) return; // Validation failed
                
                jsonData.mcp_servers = AgentFormUtils.processMCPServers();
                
                jsonData.actions = AgentFormUtils.processActions(createButton);
                if (jsonData.actions === null) return; // Validation failed
                
                jsonData.promptblocks = AgentFormUtils.processPromptBlocks(createButton);
                if (jsonData.promptblocks === null) return; // Validation failed
                                
                // Send the structured data as JSON
                fetch('/api/agent/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(jsonData)
                })
                .then(response => response.json())
                .then(data => {
                    const successAlert = document.getElementById('success-alert');
                    const errorAlert = document.getElementById('error-alert');
                    const errorMessage = document.getElementById('error-message');
                    
                    // Hide both alerts initially
                    successAlert.style.display = 'none';
                    errorAlert.style.display = 'none';
                    
                    if (data.status === "ok") {
                        // Show success toast
                        showToast('Agent created successfully!', 'success');
                        
                        // Show success message
                        successAlert.style.display = 'block';
                        
                        // Redirect to agent list page after a delay
                        setTimeout(() => {
                            window.location.href = '/old/agents';
                        }, 2000);
                    } else if (data.error) {
                        // Show error toast
                        showToast('Error: ' + data.error, 'error');
                        
                        // Show error message
                        errorMessage.textContent = data.error;
                        errorAlert.style.display = 'block';
                        
                        // Restore button state
                        createButton.innerHTML = originalButtonText;
                        createButton.disabled = false;
                    } else {
                        // Handle unexpected response format
                        showToast('Unexpected response format', 'error');
                        errorMessage.textContent = "Unexpected response format";
                        errorAlert.style.display = 'block';
                        
                        // Restore button state
                        createButton.innerHTML = originalButtonText;
                        createButton.disabled = false;
                    }
                })
                .catch(error => {
                    // Handle network or other errors
                    showToast('Network error: ' + error.message, 'error');
                    const errorAlert = document.getElementById('error-alert');
                    const errorMessage = document.getElementById('error-message');
                    
                    errorMessage.textContent = "Network error: " + error.message;
                    errorAlert.style.display = 'block';
                    
                    // Restore button state
                    createButton.innerHTML = originalButtonText;
                    createButton.disabled = false;
                });
            });
        });
    </script>
</body>
</html>
