{% extends "base.html" %}

{% block title %}{{ page_title }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <h1>API Configuration</h1>
            <p>Configure and test connection to MbetterD daemon.</p>
            
            <!-- API Status -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>API Connection Status</h5>
                </div>
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="status-indicator me-3" id="api-status-indicator"></div>
                        <div>
                            <span id="api-status-text">Checking connection...</span>
                            <button class="btn btn-sm btn-outline-primary ms-3" id="refresh-status">Refresh</button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- API Configuration -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>API Configuration</h5>
                </div>
                <div class="card-body">
                    <form id="api-config-form">
                        <div class="mb-3">
                            <label for="api-host" class="form-label">Host</label>
                            <input type="text" class="form-control" id="api-host" placeholder="localhost" value="{{ config.api_host or 'localhost' }}">
                        </div>
                        <div class="mb-3">
                            <label for="api-port" class="form-label">Port</label>
                            <input type="number" class="form-control" id="api-port" placeholder="8080" value="{{ config.api_port or 8080 }}">
                        </div>
                        <div class="mb-3">
                            <label for="api-token" class="form-label">API Token</label>
                            <input type="password" class="form-control" id="api-token" placeholder="Enter API token">
                        </div>
                        <div class="mb-3">
                            <label for="api-interval" class="form-label">Request Interval (seconds)</label>
                            <input type="number" class="form-control" id="api-interval" placeholder="1800" value="{{ config.api_interval or 1800 }}" min="30" max="86400">
                            <div class="form-text">How often to request updates from the MbetterD daemon (30 seconds to 24 hours)</div>
                        </div>
                        <button type="submit" class="btn btn-primary">Save Configuration</button>
                    </form>
                </div>
            </div>
            
            <!-- API Test -->
            <div class="card">
                <div class="card-header">
                    <h5>API Test</h5>
                </div>
                <div class="card-body">
                    <button class="btn btn-success" id="test-api-btn">Test API Connection</button>
                    <div class="mt-3" id="api-test-result" style="display: none;">
                        <h6>Test Result:</h6>
                        <pre id="api-test-response"></pre>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // Update API status indicator
    function updateApiStatus(isConnected) {
        const indicator = document.getElementById('api-status-indicator');
        const statusText = document.getElementById('api-status-text');
        
        if (isConnected) {
            indicator.className = 'status-indicator status-connected';
            statusText.textContent = 'Connected to MbetterD daemon';
        } else {
            indicator.className = 'status-indicator status-disconnected';
            statusText.textContent = 'Disconnected from MbetterD daemon';
        }
    }
    
    // Check API status on page load
    fetch('/api/status')
        .then(response => response.json())
        .then(data => {
            updateApiStatus(data.connected);
        })
        .catch(error => {
            console.error('Error checking API status:', error);
            updateApiStatus(false);
        });
    
    // Refresh status button
    document.getElementById('refresh-status').addEventListener('click', function() {
        fetch('/api/status')
            .then(response => response.json())
            .then(data => {
                updateApiStatus(data.connected);
            })
            .catch(error => {
                console.error('Error checking API status:', error);
                updateApiStatus(false);
            });
    });
    
    // Save API configuration
    document.getElementById('api-config-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const config = {
            api_host: document.getElementById('api-host').value,
            api_port: parseInt(document.getElementById('api-port').value),
            api_token: document.getElementById('api-token').value,
            api_interval: parseInt(document.getElementById('api-interval').value)
        };
        
        fetch('/api/config', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(config)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Configuration saved successfully');
            } else {
                alert('Failed to save configuration: ' + data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Failed to save configuration');
        });
    });
    
    // Test API connection
    document.getElementById('test-api-btn').addEventListener('click', function() {
        const resultDiv = document.getElementById('api-test-result');
        const responsePre = document.getElementById('api-test-response');
        
        resultDiv.style.display = 'block';
        responsePre.textContent = 'Testing...';
        
        fetch('/api/test')
            .then(response => response.json())
            .then(data => {
                responsePre.textContent = JSON.stringify(data, null, 2);
            })
            .catch(error => {
                responsePre.textContent = 'Error: ' + error.message;
            });
    });
</script>
{% endblock %}