{% extends "base.html" %}

{% block title %}OAuth Providers - {{ app_name }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <h2><i class="fas fa-key me-2"></i>OAuth Providers</h2>
            <p class="text-muted">Configure OAuth authentication providers for user signup and login.</p>
        </div>
    </div>

    <!-- Providers List -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-list me-2"></i>Configured Providers</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover" id="providers-table">
                            <thead>
                                <tr>
                                    <th>Provider</th>
                                    <th>Status</th>
                                    <th>Client ID</th>
                                    <th>Scopes</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="providers-list">
                                <tr>
                                    <td colspan="5" class="text-center">
                                        <div class="spinner-border spinner-border-sm" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                        Loading providers...
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Provider Configuration Cards -->
    <div class="row mt-4" id="provider-configs">
        <!-- Google -->
        <div class="col-md-6 col-lg-3 mb-4">
            <div class="card h-100 provider-card" data-provider="google">
                <div class="card-header bg-danger text-white">
                    <h5 class="mb-0"><i class="fab fa-google me-2"></i>Google</h5>
                </div>
                <div class="card-body">
                    <form id="google-config-form">
                        <input type="hidden" name="provider_name" value="google">
                        <div class="mb-3">
                            <label class="form-label">Client ID</label>
                            <input type="text" class="form-control" name="client_id" 
                                   placeholder="Enter Google Client ID">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Client Secret</label>
                            <input type="password" class="form-control" name="client_secret" 
                                   placeholder="Enter Google Client Secret">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Scopes</label>
                            <input type="text" class="form-control" name="scopes" 
                                   value="openid email profile" readonly>
                        </div>
                        <div class="form-check mb-3">
                            <input type="checkbox" class="form-check-input" name="is_active" id="google-active">
                            <label class="form-check-label" for="google-active">Enabled</label>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-save me-1"></i>Save Configuration
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Facebook -->
        <div class="col-md-6 col-lg-3 mb-4">
            <div class="card h-100 provider-card" data-provider="facebook">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fab fa-facebook me-2"></i>Facebook</h5>
                </div>
                <div class="card-body">
                    <form id="facebook-config-form">
                        <input type="hidden" name="provider_name" value="facebook">
                        <div class="mb-3">
                            <label class="form-label">App ID</label>
                            <input type="text" class="form-control" name="client_id" 
                                   placeholder="Enter Facebook App ID">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">App Secret</label>
                            <input type="password" class="form-control" name="client_secret" 
                                   placeholder="Enter Facebook App Secret">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Scopes</label>
                            <input type="text" class="form-control" name="scopes" 
                                   value="email public_profile" readonly>
                        </div>
                        <div class="form-check mb-3">
                            <input type="checkbox" class="form-check-input" name="is_active" id="facebook-active">
                            <label class="form-check-label" for="facebook-active">Enabled</label>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-save me-1"></i>Save Configuration
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Discord -->
        <div class="col-md-6 col-lg-3 mb-4">
            <div class="card h-100 provider-card" data-provider="discord">
                <div class="card-header bg-indigo text-white" style="background-color: #5865F2;">
                    <h5 class="mb-0"><i class="fab fa-discord me-2"></i>Discord</h5>
                </div>
                <div class="card-body">
                    <form id="discord-config-form">
                        <input type="hidden" name="provider_name" value="discord">
                        <div class="mb-3">
                            <label class="form-label">Client ID</label>
                            <input type="text" class="form-control" name="client_id" 
                                   placeholder="Enter Discord Client ID">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Client Secret</label>
                            <input type="password" class="form-control" name="client_secret" 
                                   placeholder="Enter Discord Client Secret">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Scopes</label>
                            <input type="text" class="form-control" name="scopes" 
                                   value="identify email" readonly>
                        </div>
                        <div class="form-check mb-3">
                            <input type="checkbox" class="form-check-input" name="is_active" id="discord-active">
                            <label class="form-check-label" for="discord-active">Enabled</label>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-save me-1"></i>Save Configuration
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- GitHub -->
        <div class="col-md-6 col-lg-3 mb-4">
            <div class="card h-100 provider-card" data-provider="github">
                <div class="card-header bg-dark text-white">
                    <h5 class="mb-0"><i class="fab fa-github me-2"></i>GitHub</h5>
                </div>
                <div class="card-body">
                    <form id="github-config-form">
                        <input type="hidden" name="provider_name" value="github">
                        <div class="mb-3">
                            <label class="form-label">Client ID</label>
                            <input type="text" class="form-control" name="client_id" 
                                   placeholder="Enter GitHub Client ID">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Client Secret</label>
                            <input type="password" class="form-control" name="client_secret" 
                                   placeholder="Enter GitHub Client Secret">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Scopes</label>
                            <input type="text" class="form-control" name="scopes" 
                                   value="user:email" readonly>
                        </div>
                        <div class="form-check mb-3">
                            <input type="checkbox" class="form-check-input" name="is_active" id="github-active">
                            <label class="form-check-label" for="github-active">Enabled</label>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-save me-1"></i>Save Configuration
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Callback URLs Info -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-link me-2"></i>Callback URLs</h5>
                </div>
                <div class="card-body">
                    <p class="text-muted">Configure these callback URLs in your OAuth provider applications:</p>
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Provider</th>
                                <th>Callback URL</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><i class="fab fa-google me-1"></i>Google</td>
                                <td><code id="google-callback">{{ request.host_url }}api/oauth/callback/google</code></td>
                            </tr>
                            <tr>
                                <td><i class="fab fa-facebook me-1"></i>Facebook</td>
                                <td><code id="facebook-callback">{{ request.host_url }}api/oauth/callback/facebook</code></td>
                            </tr>
                            <tr>
                                <td><i class="fab fa-discord me-1"></i>Discord</td>
                                <td><code id="discord-callback">{{ request.host_url }}api/oauth/callback/discord</code></td>
                            </tr>
                            <tr>
                                <td><i class="fab fa-github me-1"></i>GitHub</td>
                                <td><code id="github-callback">{{ request.host_url }}api/oauth/callback/github</code></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Load provider configurations
    loadProviderConfigs();
    
    // Setup form handlers
    setupFormHandlers();
});

function loadProviderConfigs() {
    fetch('/api/oauth/providers')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.providers) {
                updateProviderConfigs(data.providers);
                updateProvidersTable(data.providers);
            }
        })
        .catch(error => {
            console.error('Error loading provider configs:', error);
            // Show error in table
            const tbody = document.getElementById('providers-list');
            if (tbody) {
                tbody.innerHTML = '<tr><td colspan="5" class="text-center text-danger">Failed to load providers</td></tr>';
            }
        });
}

function updateProvidersTable(providers) {
    const tbody = document.getElementById('providers-list');
    if (!tbody) return;
    
    if (providers.length === 0) {
        tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">No providers configured</td></tr>';
        return;
    }
    
    const providerIcons = {
        'google': '<i class="fab fa-google me-1"></i>Google',
        'facebook': '<i class="fab fa-facebook me-1"></i>Facebook',
        'discord': '<i class="fab fa-discord me-1"></i>Discord',
        'github': '<i class="fab fa-github me-1"></i>GitHub'
    };
    
    const providerScopes = {
        'google': 'openid email profile',
        'facebook': 'email public_profile',
        'discord': 'identify email',
        'github': 'user:email'
    };
    
    let html = '';
    providers.forEach(provider => {
        const statusBadge = provider.enabled
            ? '<span class="badge bg-success">Enabled</span>'
            : '<span class="badge bg-secondary">Disabled</span>';
        
        const configBadge = provider.is_configured
            ? '<span class="badge bg-info">Configured</span>'
            : '<span class="badge bg-warning text-dark">Not Configured</span>';
        
        html += `
            <tr>
                <td>${providerIcons[provider.name] || provider.name}</td>
                <td>${statusBadge} ${configBadge}</td>
                <td><code>${provider.client_id || '-'}</code></td>
                <td><small>${providerScopes[provider.name] || '-'}</small></td>
                <td>
                    <button class="btn btn-sm btn-outline-primary" onclick="document.querySelector('.provider-card[data-provider=\\'${provider.name}\\'').scrollIntoView({behavior: 'smooth'})">
                        <i class="fas fa-edit"></i> Edit
                    </button>
                </td>
            </tr>
        `;
    });
    
    tbody.innerHTML = html;
}

function updateProviderConfigs(providers) {
    providers.forEach(provider => {
        const card = document.querySelector(`.provider-card[data-provider="${provider.name}"]`);
        if (card) {
            const form = card.querySelector('form');
            form.querySelector('[name="client_id"]').value = provider.client_id || '';
            form.querySelector('[name="is_active"]').checked = provider.enabled;
            
            // Show asterisks for client_secret if it exists
            const secretInput = form.querySelector('[name="client_secret"]');
            if (provider.has_client_secret && secretInput) {
                secretInput.placeholder = '••••••••••••••••••••••••';
                secretInput.dataset.hasSecret = 'true';
            }
            
            // Remove existing status badge before adding new one
            const cardHeader = card.querySelector('.card-header');
            const existingBadge = cardHeader.querySelector('.badge');
            if (existingBadge) {
                existingBadge.remove();
            }
            
            // Update status indicator
            const statusBadge = document.createElement('span');
            statusBadge.className = `badge ${provider.is_configured ? 'bg-success' : 'bg-secondary'} ms-2`;
            statusBadge.textContent = provider.is_configured ? 'Configured' : 'Not Configured';
            cardHeader.appendChild(statusBadge);
        }
    });
}

function setupFormHandlers() {
    document.querySelectorAll('.provider-card form').forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const data = {
                provider_name: formData.get('provider_name'),
                client_id: formData.get('client_id'),
                client_secret: formData.get('client_secret'),
                is_active: formData.get('is_active') === 'on'
            };
            
            // Show loading state
            const btn = this.querySelector('button[type="submit"]');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving...';
            btn.disabled = true;
            
            fetch(`/api/admin/oauth/providers/${data.provider_name}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    showToast('success', `${data.provider_name.charAt(0).toUpperCase() + data.provider_name.slice(1)} configuration saved`);
                    loadProviderConfigs();
                } else {
                    showToast('error', result.error || 'Failed to save configuration');
                }
            })
            .catch(error => {
                console.error('Error saving configuration:', error);
                showToast('error', 'Failed to save configuration');
            })
            .finally(() => {
                btn.innerHTML = originalText;
                btn.disabled = false;
            });
        });
    });
}

function showToast(type, message) {
    const toast = document.createElement('div');
    toast.className = `alert alert-${type === 'error' ? 'danger' : 'success'} alert-dismissible fade show position-fixed`;
    toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    toast.innerHTML = `
        <i class="fas fa-${type === 'error' ? 'exclamation-triangle' : 'check-circle'} me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, 5000);
}
</script>
{% endblock %}