{% extends "base.html" %}

{% block title %}API Tokens - Fixture Manager{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="h3 mb-0">🔑 API Tokens</h1>
                    <p class="text-muted">Manage your API tokens for external application access</p>
                </div>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createTokenModal">
                    <i class="fas fa-plus"></i> Create New Token
                </button>
            </div>
        </div>
    </div>

    <!-- API Documentation Card -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-info">
                <div class="card-header bg-info text-white">
                    <h5 class="mb-0"><i class="fas fa-info-circle"></i> API Usage</h5>
                </div>
                <div class="card-body">
                    <p class="mb-2"><strong>Base URL:</strong> <code>{{ request.url_root }}api/</code></p>
                    <p class="mb-2"><strong>Authentication:</strong> Include your token in the Authorization header:</p>
                    <pre class="bg-light p-2 rounded"><code>Authorization: Bearer YOUR_TOKEN_HERE</code></pre>
                    <p class="mb-2"><strong>Available Endpoints:</strong></p>
                    <ul class="mb-0">
                        <li><code>GET /api/fixtures</code> - List all fixtures</li>
                        <li><code>GET /api/matches</code> - List all matches</li>
                        <li><code>GET /api/match/&lt;id&gt;</code> - Get match details</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- Tokens List -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Your API Tokens</h5>
                </div>
                <div class="card-body">
                    {% if tokens %}
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Status</th>
                                        <th>Created</th>
                                        <th>Expires</th>
                                        <th>Last Used</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="tokensTableBody">
                                    {% for token in tokens %}
                                    <tr data-token-id="{{ token.id }}">
                                        <td>
                                            <strong>{{ token.name }}</strong>
                                        </td>
                                        <td>
                                            {% if token.is_valid() %}
                                                <span class="badge bg-success">Active</span>
                                            {% elif token.is_expired() %}
                                                <span class="badge bg-danger">Expired</span>
                                            {% else %}
                                                <span class="badge bg-secondary">Revoked</span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            <small class="text-muted">
                                                {{ token.created_at.strftime('%Y-%m-%d %H:%M') }}
                                            </small>
                                        </td>
                                        <td>
                                            <small class="text-muted">
                                                {{ token.expires_at.strftime('%Y-%m-%d %H:%M') }}
                                            </small>
                                        </td>
                                        <td>
                                            <small class="text-muted">
                                                {% if token.last_used_at %}
                                                    {{ token.last_used_at.strftime('%Y-%m-%d %H:%M') }}
                                                    {% if token.last_used_ip %}
                                                        <br>from {{ token.last_used_ip }}
                                                    {% endif %}
                                                {% else %}
                                                    Never used
                                                {% endif %}
                                            </small>
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm" role="group">
                                                {% if token.is_active and not token.is_expired() %}
                                                    <button type="button" class="btn btn-outline-warning" 
                                                            onclick="revokeToken({{ token.id }}, '{{ token.name }}')"
                                                            title="Revoke Token">
                                                        <i class="fas fa-ban"></i>
                                                    </button>
                                                    <button type="button" class="btn btn-outline-info" 
                                                            onclick="extendToken({{ token.id }}, '{{ token.name }}')"
                                                            title="Extend Expiration">
                                                        <i class="fas fa-clock"></i>
                                                    </button>
                                                {% endif %}
                                                <button type="button" class="btn btn-outline-danger" 
                                                        onclick="deleteToken({{ token.id }}, '{{ token.name }}')"
                                                        title="Delete Token">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <div class="text-center py-5">
                            <i class="fas fa-key fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">No API tokens yet</h5>
                            <p class="text-muted">Create your first API token to start accessing the API</p>
                            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createTokenModal">
                                <i class="fas fa-plus"></i> Create Your First Token
                            </button>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Create Token Modal -->
<div class="modal fade" id="createTokenModal" tabindex="-1" aria-labelledby="createTokenModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createTokenModalLabel">Create New API Token</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="createTokenForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="tokenName" class="form-label">Token Name</label>
                        <input type="text" class="form-control" id="tokenName" name="name" required
                               placeholder="e.g., Mobile App, Dashboard Integration">
                        <div class="form-text">Choose a descriptive name to identify this token</div>
                    </div>
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle"></i>
                        <strong>Important:</strong> The token will only be shown once after creation. Make sure to copy and store it securely.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Create Token
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Token Created Modal -->
<div class="modal fade" id="tokenCreatedModal" tabindex="-1" aria-labelledby="tokenCreatedModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title" id="tokenCreatedModalLabel">
                    <i class="fas fa-check-circle"></i> Token Created Successfully
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-success">
                    <strong>Your new API token has been created!</strong>
                </div>
                <div class="mb-3">
                    <label for="newTokenValue" class="form-label"><strong>Token Value:</strong></label>
                    <div class="input-group">
                        <input type="text" class="form-control font-monospace" id="newTokenValue" readonly>
                        <button class="btn btn-outline-secondary" type="button" onclick="copyToken()">
                            <i class="fas fa-copy"></i> Copy
                        </button>
                    </div>
                </div>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    <strong>Warning:</strong> This token will not be shown again. Make sure to copy and store it in a secure location.
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">I've Saved the Token</button>
            </div>
        </div>
    </div>
</div>

<!-- Extend Token Modal -->
<div class="modal fade" id="extendTokenModal" tabindex="-1" aria-labelledby="extendTokenModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="extendTokenModalLabel">Extend Token Expiration</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="extendTokenForm">
                <div class="modal-body">
                    <p>Extend the expiration date for token: <strong id="extendTokenName"></strong></p>
                    <div class="mb-3">
                        <label for="extensionDays" class="form-label">Extend by (days)</label>
                        <select class="form-select" id="extensionDays" name="days">
                            <option value="30">30 days</option>
                            <option value="90">90 days</option>
                            <option value="180">180 days</option>
                            <option value="365" selected>365 days (1 year)</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-info">
                        <i class="fas fa-clock"></i> Extend Token
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Global variables for token management
let currentTokenId = null;

// Create token form submission
document.getElementById('createTokenForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const tokenName = formData.get('name');
    
    if (!tokenName.trim()) {
        showAlert('Token name is required', 'danger');
        return;
    }
    
    try {
        const response = await fetch('{{ url_for("main.create_api_token") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token() }}'
            },
            body: JSON.stringify({ name: tokenName })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            // Hide create modal
            const createModal = bootstrap.Modal.getInstance(document.getElementById('createTokenModal'));
            createModal.hide();
            
            // Show token value in success modal
            document.getElementById('newTokenValue').value = data.token.token;
            const tokenCreatedModal = new bootstrap.Modal(document.getElementById('tokenCreatedModal'));
            tokenCreatedModal.show();
            
            // Reset form
            this.reset();
            
            // Reload page after modal is closed
            document.getElementById('tokenCreatedModal').addEventListener('hidden.bs.modal', function() {
                location.reload();
            }, { once: true });
            
        } else {
            showAlert(data.error || 'Failed to create token', 'danger');
        }
    } catch (error) {
        console.error('Error creating token:', error);
        showAlert('Network error occurred', 'danger');
    }
});

// Extend token form submission
document.getElementById('extendTokenForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    if (!currentTokenId) return;
    
    const formData = new FormData(this);
    const days = parseInt(formData.get('days'));
    
    try {
        const response = await fetch(`{{ url_for("main.extend_api_token", token_id=0) }}`.replace('0', currentTokenId), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token() }}'
            },
            body: JSON.stringify({ days: days })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            showAlert(data.message, 'success');
            const modal = bootstrap.Modal.getInstance(document.getElementById('extendTokenModal'));
            modal.hide();
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert(data.error || 'Failed to extend token', 'danger');
        }
    } catch (error) {
        console.error('Error extending token:', error);
        showAlert('Network error occurred', 'danger');
    }
});

// Token management functions
async function revokeToken(tokenId, tokenName) {
    if (!confirm(`Are you sure you want to revoke the token "${tokenName}"? This action cannot be undone.`)) {
        return;
    }
    
    try {
        const response = await fetch(`{{ url_for("main.revoke_api_token", token_id=0) }}`.replace('0', tokenId), {
            method: 'POST',
            headers: {
                'X-CSRFToken': '{{ csrf_token() }}'
            }
        });
        
        const data = await response.json();
        
        if (response.ok) {
            showAlert(data.message, 'success');
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert(data.error || 'Failed to revoke token', 'danger');
        }
    } catch (error) {
        console.error('Error revoking token:', error);
        showAlert('Network error occurred', 'danger');
    }
}

async function deleteToken(tokenId, tokenName) {
    if (!confirm(`Are you sure you want to permanently delete the token "${tokenName}"? This action cannot be undone.`)) {
        return;
    }
    
    try {
        const response = await fetch(`{{ url_for("main.delete_api_token", token_id=0) }}`.replace('0', tokenId), {
            method: 'DELETE',
            headers: {
                'X-CSRFToken': '{{ csrf_token() }}'
            }
        });
        
        const data = await response.json();
        
        if (response.ok) {
            showAlert(data.message, 'success');
            // Remove the row from table
            const row = document.querySelector(`tr[data-token-id="${tokenId}"]`);
            if (row) {
                row.remove();
            }
        } else {
            showAlert(data.error || 'Failed to delete token', 'danger');
        }
    } catch (error) {
        console.error('Error deleting token:', error);
        showAlert('Network error occurred', 'danger');
    }
}

function extendToken(tokenId, tokenName) {
    currentTokenId = tokenId;
    document.getElementById('extendTokenName').textContent = tokenName;
    const modal = new bootstrap.Modal(document.getElementById('extendTokenModal'));
    modal.show();
}

function copyToken() {
    const tokenInput = document.getElementById('newTokenValue');
    tokenInput.select();
    tokenInput.setSelectionRange(0, 99999); // For mobile devices
    
    try {
        document.execCommand('copy');
        showAlert('Token copied to clipboard!', 'success');
    } catch (err) {
        console.error('Failed to copy token:', err);
        showAlert('Failed to copy token. Please copy manually.', 'warning');
    }
}

function showAlert(message, type) {
    // Create alert element
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    
    // Insert at top of container
    const container = document.querySelector('.container-fluid');
    container.insertBefore(alertDiv, container.firstChild);
    
    // Auto-dismiss after 5 seconds
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 5000);
}
</script>
{% endblock %}