{% extends "base.html" %}

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

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <h1>API Tokens</h1>
            <p>Manage API tokens for programmatic access.</p>
            
            <!-- Create Token -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>Create New Token</h5>
                </div>
                <div class="card-body">
                    <form id="create-token-form">
                        <div class="mb-3">
                            <label for="token-name" class="form-label">Token Name</label>
                            <input type="text" class="form-control" id="token-name" placeholder="e.g., Mobile App, Script" required>
                        </div>
                        <div class="mb-3">
                            <label for="token-expiry" class="form-label">Expires In</label>
                            <select class="form-select" id="token-expiry">
                                <option value="1">1 hour</option>
                                <option value="24">1 day</option>
                                <option value="168">1 week</option>
                                <option value="720">1 month</option>
                                <option value="8760" selected>1 year</option>
                                <option value="87600">10 years</option>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-primary">Create Token</button>
                    </form>
                </div>
            </div>
            
            <!-- Active Tokens -->
            <div class="card">
                <div class="card-header">
                    <h5>Active Tokens</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Created</th>
                                    <th>Expires</th>
                                    <th>Token</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="tokens-table-body">
                                <!-- Token rows will be populated by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // Load tokens on page load
    function loadTokens() {
        fetch('/api/tokens')
            .then(response => response.json())
            .then(data => {
                const tbody = document.getElementById('tokens-table-body');
                tbody.innerHTML = '';
                
                data.forEach(token => {
                    const row = document.createElement('tr');
                    const createdDate = new Date(token.created_at).toLocaleString();
                    const expiresDate = new Date(token.expires_at).toLocaleString();
                    const isExpired = new Date(token.expires_at) < new Date();
                    
                    row.innerHTML = `
                        <td>${token.name}</td>
                        <td>${createdDate}</td>
                        <td>${expiresDate} ${isExpired ? '<span class="badge bg-danger">Expired</span>' : ''}</td>
                        <td>
                            <code>${token.token_preview}</code>
                            <button class="btn btn-sm btn-outline-primary copy-token" data-token="${token.token}">
                                <i class="fas fa-copy"></i>
                            </button>
                        </td>
                        <td>
                            <button class="btn btn-sm btn-danger revoke-token" data-id="${token.id}">Revoke</button>
                        </td>
                    `;
                    tbody.appendChild(row);
                });
                
                // Add event listeners to action buttons
                document.querySelectorAll('.copy-token').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const token = this.getAttribute('data-token');
                        copyToClipboard(token);
                    });
                });
                
                document.querySelectorAll('.revoke-token').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const tokenId = this.getAttribute('data-id');
                        revokeToken(tokenId);
                    });
                });
            })
            .catch(error => {
                console.error('Error loading tokens:', error);
            });
    }
    
    // Copy token to clipboard
    function copyToClipboard(text) {
        navigator.clipboard.writeText(text).then(() => {
            alert('Token copied to clipboard');
        }).catch(err => {
            console.error('Failed to copy token: ', err);
        });
    }
    
    // Revoke token
    function revokeToken(tokenId) {
        if (confirm('Are you sure you want to revoke this token?')) {
            fetch(`/api/tokens/${tokenId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Token revoked successfully');
                    loadTokens(); // Refresh token list
                } else {
                    alert('Failed to revoke token: ' + data.error);
                }
            })
            .catch(error => {
                console.error('Error revoking token:', error);
                alert('Failed to revoke token');
            });
        }
    }
    
    // Create token
    document.getElementById('create-token-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const name = document.getElementById('token-name').value;
        const expiresHours = parseInt(document.getElementById('token-expiry').value);
        
        if (!name) {
            alert('Token name is required');
            return;
        }
        
        fetch('/api/tokens', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                name: name,
                expires_hours: expiresHours
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.token) {
                // Show the token in a modal or alert
                const tokenValue = data.token;
                const tokenInfo = data.token_info;
                
                // Create a modal to show the token
                const tokenModal = `
                    <div class="modal fade" id="newTokenModal" tabindex="-1">
                        <div class="modal-dialog modal-lg">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title">New API Token Created</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>
                                <div class="modal-body">
                                    <div class="alert alert-warning">
                                        <i class="fas fa-exclamation-triangle"></i>
                                        <strong>Important:</strong> Copy this token now. You won't be able to see it again!
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Token Name:</label>
                                        <p><strong>${tokenInfo.name}</strong></p>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Your API Token:</label>
                                        <div class="input-group">
                                            <input type="text" class="form-control font-monospace" id="new-token-value" value="${tokenValue}" readonly>
                                            <button class="btn btn-outline-primary" onclick="copyNewToken()">
                                                <i class="fas fa-copy"></i> Copy
                                            </button>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Expires:</label>
                                        <p>${new Date(tokenInfo.expires_at).toLocaleString()}</p>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">I've copied the token</button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                
                // Add modal to page
                document.body.insertAdjacentHTML('beforeend', tokenModal);
                
                // Show modal
                const modal = new bootstrap.Modal(document.getElementById('newTokenModal'));
                modal.show();
                
                // Clean up modal when closed
                document.getElementById('newTokenModal').addEventListener('hidden.bs.modal', function () {
                    this.remove();
                    loadTokens(); // Refresh token list
                });
                
                // Reset form
                document.getElementById('create-token-form').reset();
                
            } else {
                alert('Failed to create token: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error creating token:', error);
            alert('Failed to create token');
        });
    });
    
    // Copy new token function
    function copyNewToken() {
        const tokenInput = document.getElementById('new-token-value');
        tokenInput.select();
        document.execCommand('copy');
        
        // Update button text briefly
        const btn = event.target.closest('button');
        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-check"></i> Copied!';
        setTimeout(() => {
            btn.innerHTML = originalText;
        }, 2000);
    }
    
    // Load tokens when page loads
    document.addEventListener('DOMContentLoaded', function() {
        loadTokens();
    });
</script>
{% endblock %}