{% extends "base.html" %}

{% block title %}My API Tokens - AISBF{% endblock %}

{% block content %}
<div class="container">
    <h1>My API Tokens</h1>
    <p>Manage your personal API tokens for accessing the AISBF API</p>

    {% if success %}
    <div class="alert alert-success">{{ success }}</div>
    {% endif %}

    {% if error %}
    <div class="alert alert-error">{{ error }}</div>
    {% endif %}

    <!-- API Documentation -->
    <div class="card">
        <h2>🔌 How to Use Your Token</h2>
        <p>Include your API token in the <code>Authorization</code> header when making requests:</p>
        <pre style="background: #1a1a2e; padding: 1rem; border-radius: 4px; overflow-x: auto;"><code>Authorization: Bearer YOUR_API_TOKEN</code></pre>
        
        <h3>Available Endpoints:</h3>
        <table class="endpoints-table">
            <thead>
                <tr>
                    <th>Method</th>
                    <th>Endpoint</th>
                    <th>Description</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><code class="method GET">GET</code></td>
                    <td><code>/api/user/models</code></td>
                    <td>List your models</td>
                </tr>
                <tr>
                    <td><code class="method GET">GET</code></td>
                    <td><code>/api/user/providers</code></td>
                    <td>List your providers</td>
                </tr>
                <tr>
                    <td><code class="method GET">GET</code></td>
                    <td><code>/api/user/rotations</code></td>
                    <td>List your rotations</td>
                </tr>
                <tr>
                    <td><code class="method GET">GET</code></td>
                    <td><code>/api/user/autoselects</code></td>
                    <td>List your autoselects</td>
                </tr>
                <tr>
                    <td><code class="method POST">POST</code></td>
                    <td><code>/api/user/chat/completions</code></td>
                    <td>Chat using your configs</td>
                </tr>
                <tr>
                    <td><code class="method GET">GET</code></td>
                    <td><code>/mcp/tools</code></td>
                    <td>List MCP tools</td>
                </tr>
                <tr>
                    <td><code class="method POST">POST</code></td>
                    <td><code>/mcp/tools/call</code></td>
                    <td>Call MCP tools</td>
                </tr>
            </tbody>
        </table>
        
        <h3>Example curl commands:</h3>
        <pre style="background: #1a1a2e; padding: 1rem; border-radius: 4px; overflow-x: auto;"><code># List your models
curl -H "Authorization: Bearer YOUR_TOKEN" http://localhost:17765/api/user/models

# List your providers  
curl -H "Authorization: Bearer YOUR_TOKEN" http://localhost:17765/api/user/providers

# Send a chat request
curl -X POST -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"model": "user-rotation/myrotation", "messages": [{"role": "user", "content": "Hello"}]}' \
  http://localhost:17765/api/user/chat/completions</code></pre>
    </div>

    <div class="card">
        <h2>API Tokens</h2>
        <div id="tokens-list">
            <!-- Tokens will be loaded here -->
        </div>
        <button class="btn btn-primary" onclick="createToken()">Create New Token</button>
    </div>

    <!-- Modal for creating tokens -->
    <div id="token-modal" class="modal" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Create New API Token</h3>
                <button class="close-btn" onclick="closeModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div id="token-creation-form">
                    <form id="create-token-form">
                        <div class="form-group">
                            <label for="token-description">Description (optional):</label>
                            <input type="text" id="token-description" placeholder="e.g., My application token">
                        </div>
                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary">Create Token</button>
                            <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button>
                        </div>
                    </form>
                </div>
                <div id="token-result" style="display: none;">
                    <div class="alert alert-success">
                        <h4>Token Created Successfully!</h4>
                        <p><strong>Token:</strong> <code id="created-token"></code></p>
                        <p class="warning-text">⚠️ <strong>Important:</strong> Copy this token now. You won't be able to see it again!</p>
                        <div class="form-actions">
                            <button type="button" class="btn btn-primary" onclick="copyToken()">Copy Token</button>
                            <button type="button" class="btn btn-secondary" onclick="closeModal()">Close</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let tokens = {{ user_tokens | tojson }};

function renderTokens() {
    const container = document.getElementById('tokens-list');
    container.innerHTML = '';

    if (tokens.length === 0) {
        container.innerHTML = '<p class="empty-state">No API tokens created yet. Click "Create New Token" to get started.</p>';
        return;
    }

    tokens.forEach((token) => {
        const div = document.createElement('div');
        div.className = 'token-item';
        div.innerHTML = `
            <div class="token-header">
                <div class="token-info">
                    <h4>${token.description || 'No description'}</h4>
                    <p class="token-meta">
                        Created: ${new Date(token.created_at).toLocaleString()}
                        ${token.last_used ? `| Last used: ${new Date(token.last_used).toLocaleString()}` : ''}
                    </p>
                </div>
                <div class="token-actions">
                    <span class="token-status ${token.is_active ? 'active' : 'inactive'}">
                        ${token.is_active ? 'Active' : 'Inactive'}
                    </span>
                    <button class="btn btn-danger btn-sm" onclick="deleteToken(${token.id})">Delete</button>
                </div>
            </div>
            <div class="token-details">
                <p><strong>Token ID:</strong> ${token.id}</p>
                <p><strong>Token:</strong> ${token.token.substring(0, 20)}...</p>
            </div>
        `;
        container.appendChild(div);
    });
}

function createToken() {
    document.getElementById('token-creation-form').style.display = 'block';
    document.getElementById('token-result').style.display = 'none';
    document.getElementById('create-token-form').reset();
    document.getElementById('token-modal').style.display = 'block';
}

function closeModal() {
    document.getElementById('token-modal').style.display = 'none';
}

function deleteToken(tokenId) {
    if (!confirm('Are you sure you want to delete this API token? This action cannot be undone and will immediately revoke access.')) return;

    fetch('{{ url_for(request, "/dashboard/user/tokens") }}/' + tokenId, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json'
        }
    }).then(response => {
        if (response.ok) {
            location.reload();
        } else {
            return response.json().then(data => {
                throw new Error(data.error || 'Failed to delete token');
            });
        }
    }).catch(error => {
        alert('Error: ' + error.message);
    });
}

function copyToken() {
    const tokenElement = document.getElementById('created-token');
    const token = tokenElement.textContent;

    navigator.clipboard.writeText(token).then(() => {
        alert('Token copied to clipboard!');
    }).catch(() => {
        // Fallback for older browsers
        const textArea = document.createElement('textarea');
        textArea.value = token;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        alert('Token copied to clipboard!');
    });
}

// Handle form submission
document.getElementById('create-token-form').addEventListener('submit', function(e) {
    e.preventDefault();

    const description = document.getElementById('token-description').value.trim();

    const formData = new FormData();
    if (description) {
        formData.append('description', description);
    }

    fetch('{{ url_for(request, "/dashboard/user/tokens") }}', {
        method: 'POST',
        body: formData
    }).then(response => {
        if (response.ok) {
            return response.json();
        } else {
            return response.json().then(data => {
                throw new Error(data.error || 'Failed to create token');
            });
        }
    }).then(data => {
        // Show the created token
        document.getElementById('created-token').textContent = data.token;
        document.getElementById('token-creation-form').style.display = 'none';
        document.getElementById('token-result').style.display = 'block';

        // Refresh the token list
        tokens.push({
            id: data.token_id,
            token: data.token,
            description: description || null,
            created_at: new Date().toISOString(),
            last_used: null,
            is_active: true
        });
        renderTokens();
    }).catch(error => {
        alert('Error: ' + error.message);
    });
});

renderTokens();
</script>

<style>
.token-item {
    background: #1a1a2e;
    padding: 1rem;
    margin: 1rem 0;
    border-radius: 8px;
    border: 1px solid #0f3460;
}

.token-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 1rem;
}

.token-info h4 {
    margin: 0 0 0.5rem 0;
    color: #e0e0e0;
}

.token-meta {
    color: #a0a0a0;
    font-size: 0.9rem;
    margin: 0;
}

.token-actions {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.token-status {
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.8rem;
    font-weight: 500;
}

.token-status.active {
    background: #28a745;
    color: white;
}

.token-status.inactive {
    background: #dc3545;
    color: white;
}

.token-details {
    background: #16213e;
    padding: 1rem;
    border-radius: 4px;
    font-family: monospace;
    font-size: 0.9rem;
}

.token-details p {
    margin: 0.5rem 0;
    word-break: break-all;
}

.empty-state {
    text-align: center;
    color: #a0a0a0;
    padding: 2rem;
}

.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.modal-content {
    background: #1a1a2e;
    border-radius: 8px;
    width: 90%;
    max-width: 500px;
    max-height: 80vh;
    overflow-y: auto;
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem;
    border-bottom: 1px solid #0f3460;
}

.modal-header h3 {
    margin: 0;
}

.close-btn {
    background: none;
    border: none;
    color: #e0e0e0;
    font-size: 1.5rem;
    cursor: pointer;
    padding: 0;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.modal-body {
    padding: 1rem;
}

.form-group {
    margin-bottom: 1rem;
}

.form-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 500;
    color: #e0e0e0;
}

.form-group input[type="text"] {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid #0f3460;
    border-radius: 4px;
    background: #16213e;
    color: #e0e0e0;
    font-size: 14px;
}

.form-actions {
    display: flex;
    gap: 0.5rem;
    justify-content: flex-end;
    margin-top: 1rem;
}

.warning-text {
    color: #ffc107;
    font-weight: 500;
}

#created-token {
    background: #0f3460;
    padding: 0.5rem;
    border-radius: 4px;
    font-family: monospace;
    word-break: break-all;
}

/* API Endpoints Table */
.endpoints-table {
    width: 100%;
    margin: 1rem 0;
    border-collapse: collapse;
}

.endpoints-table th,
.endpoints-table td {
    padding: 0.75rem;
    text-align: left;
    border-bottom: 1px solid #333;
}

.endpoints-table th {
    background: #1a1a2e;
    font-weight: bold;
}

.endpoints-table .method {
    display: inline-block;
    padding: 0.2rem 0.5rem;
    border-radius: 3px;
    font-weight: bold;
    font-size: 0.75rem;
}

.endpoints-table .method.GET {
    background: #28a745;
    color: white;
}

.endpoints-table .method.POST {
    background: #007bff;
    color: white;
}
</style>
{% endblock %}