<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API Keys - MySQL to Sheets Sync</title>
    <style>
        :root {
            --primary: #2563eb;
            --primary-hover: #1d4ed8;
            --success: #16a34a;
            --error: #dc2626;
            --warning: #ca8a04;
            --bg: #f8fafc;
            --card-bg: #ffffff;
            --border: #e2e8f0;
            --text: #1e293b;
            --text-muted: #64748b;
        }

        * { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--bg);
            color: var(--text);
            line-height: 1.5;
            padding: 2rem;
        }

        .container { max-width: 1200px; margin: 0 auto; }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
        }

        h1 { font-size: 1.5rem; font-weight: 600; }
        .version { color: var(--text-muted); font-size: 0.875rem; }

        nav {
            display: flex;
            gap: 1rem;
            margin-bottom: 2rem;
            border-bottom: 1px solid var(--border);
            padding-bottom: 1rem;
        }

        nav a {
            color: var(--text-muted);
            text-decoration: none;
            padding: 0.5rem 1rem;
            border-radius: 0.375rem;
        }

        nav a:hover { background: var(--border); color: var(--text); }
        nav a.active { background: var(--primary); color: white; }

        .card {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 0.5rem;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }

        .card h2 { font-size: 1.125rem; font-weight: 600; margin-bottom: 1rem; }

        .btn {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border: 1px solid var(--border);
            border-radius: 0.375rem;
            font-size: 0.875rem;
            font-weight: 500;
            cursor: pointer;
            background: var(--card-bg);
            color: var(--text);
            text-decoration: none;
        }

        .btn:hover { background: var(--bg); }
        .btn-primary { background: var(--primary); color: white; border-color: var(--primary); }
        .btn-primary:hover { background: var(--primary-hover); }
        .btn-danger { background: var(--error); color: white; border-color: var(--error); }
        .btn-danger:hover { opacity: 0.9; }
        .btn-sm { padding: 0.25rem 0.5rem; font-size: 0.75rem; }

        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 0.75rem 1rem; text-align: left; border-bottom: 1px solid var(--border); }
        th { font-weight: 500; color: var(--text-muted); font-size: 0.75rem; text-transform: uppercase; }
        tr:hover { background: var(--bg); }

        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
        }

        .empty-state {
            text-align: center;
            padding: 3rem;
            color: var(--text-muted);
        }

        .alert {
            padding: 0.75rem 1rem;
            border-radius: 0.375rem;
            margin-bottom: 1rem;
        }

        .alert-error { background: #fee2e2; border: 1px solid #fecaca; color: var(--error); }
        .alert-success { background: #dcfce7; border: 1px solid #bbf7d0; color: var(--success); }
        .alert-warning { background: #fef3c7; border: 1px solid #fde68a; color: #92400e; }

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

        .modal.active { display: flex; }

        .modal-content {
            background: var(--card-bg);
            border-radius: 0.5rem;
            padding: 1.5rem;
            width: 100%;
            max-width: 500px;
        }

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

        .modal-header h3 { font-size: 1.125rem; font-weight: 600; }
        .modal-close { cursor: pointer; font-size: 1.5rem; color: var(--text-muted); }

        .form-group { margin-bottom: 1rem; }
        label { display: block; font-size: 0.875rem; font-weight: 500; margin-bottom: 0.25rem; }

        input[type="text"],
        textarea {
            width: 100%;
            padding: 0.5rem 0.75rem;
            border: 1px solid var(--border);
            border-radius: 0.375rem;
            font-size: 0.875rem;
            font-family: inherit;
        }

        textarea {
            min-height: 80px;
            resize: vertical;
        }

        input:focus, textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }

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

        .key-display {
            background: var(--bg);
            border: 1px solid var(--border);
            border-radius: 0.375rem;
            padding: 0.75rem;
            font-family: 'Monaco', 'Menlo', monospace;
            font-size: 0.875rem;
            word-break: break-all;
            margin: 1rem 0;
        }

        .key-prefix {
            font-family: 'Monaco', 'Menlo', monospace;
            font-size: 0.875rem;
            color: var(--text-muted);
        }

        .badge {
            display: inline-flex;
            padding: 0.25rem 0.5rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
        }

        .badge-success { background: #dcfce7; color: #166534; }
        .badge-error { background: #fee2e2; color: #991b1b; }
        .badge-warning { background: #fef3c7; color: #92400e; }

        .copy-btn {
            padding: 0.375rem 0.75rem;
            font-size: 0.75rem;
            cursor: pointer;
            background: var(--primary);
            color: white;
            border: none;
            border-radius: 0.25rem;
            margin-left: 0.5rem;
        }

        .copy-btn:hover { background: var(--primary-hover); }
        .copy-btn.copied { background: var(--success); }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div>
                <h1>API Key Management</h1>
                <span class="version">v{{ version }}</span>
            </div>
            <div>
                {% if current_user %}
                <span style="margin-right: 1rem;">{{ current_user.email }}</span>
                <a href="{{ url_for('auth.logout') }}" style="color: var(--primary); text-decoration: none;">Logout</a>
                {% endif %}
            </div>
        </header>

        <nav>
            <a href="{{ url_for('dashboard.index') }}">Dashboard</a>
            <a href="{{ url_for('dashboard.users') }}">Users</a>
            <a href="{{ url_for('dashboard.webhooks_page') }}">Webhooks</a>
            <a href="{{ url_for('api_keys.api_keys_page') }}" class="active">API Keys</a>
            <a href="{{ url_for('dashboard.audit_page') }}">Audit</a>
        </nav>

        <div id="alertContainer"></div>

        <!-- Info Card -->
        <div class="card" style="background: #dbeafe; border-color: #93c5fd;">
            <div style="display: flex; gap: 1rem; align-items: flex-start;">
                <svg style="width: 24px; height: 24px; flex-shrink: 0; color: var(--primary);" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                <div>
                    <strong style="color: #1e40af;">About API Keys</strong>
                    <p style="font-size: 0.875rem; margin-top: 0.25rem; color: #1e40af;">
                        API keys are used to authenticate requests to the REST API. The full key is only shown once when created.
                        Store it securely - it cannot be retrieved later. Include the key in API requests using the
                        <code style="background: rgba(0,0,0,0.1); padding: 0.125rem 0.25rem; border-radius: 0.25rem;">X-API-Key</code> header.
                    </p>
                </div>
            </div>
        </div>

        <!-- API Keys Table -->
        <div class="card">
            <div class="toolbar">
                <h2>API Keys</h2>
                <button class="btn btn-primary" onclick="openCreateModal()">
                    <svg style="width: 16px; height: 16px;" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                    </svg>
                    Create API Key
                </button>
            </div>

            {% if api_keys %}
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Key Prefix</th>
                        <th>Created</th>
                        <th>Last Used</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="apiKeyList">
                    {% for key in api_keys %}
                    <tr data-key-id="{{ key.id }}">
                        <td>
                            <strong>{{ key.name }}</strong>
                            {% if key.description %}
                            <div style="font-size: 0.75rem; color: var(--text-muted);">{{ key.description[:50] }}{% if key.description|length > 50 %}...{% endif %}</div>
                            {% endif %}
                        </td>
                        <td>
                            <span class="key-prefix">{{ key.key_prefix }}</span>
                        </td>
                        <td>{{ key.created_at[:10] if key.created_at else 'N/A' }}</td>
                        <td>{{ key.last_used_at[:16] if key.last_used_at else 'Never' }}</td>
                        <td>
                            {% if key.is_expired %}
                            <span class="badge badge-warning">Expired</span>
                            {% elif key.revoked %}
                            <span class="badge badge-error">Revoked</span>
                            {% else %}
                            <span class="badge badge-success">Active</span>
                            {% endif %}
                        </td>
                        <td>
                            {% if not key.revoked %}
                            <button class="btn btn-sm btn-danger" onclick="revokeKey({{ key.id }}, '{{ key.name }}')">Revoke</button>
                            {% else %}
                            <span style="color: var(--text-muted); font-size: 0.75rem;">Revoked {{ key.revoked_at[:10] if key.revoked_at else '' }}</span>
                            {% endif %}
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
            {% else %}
            <div class="empty-state">
                <svg style="width: 48px; height: 48px; color: var(--text-muted); margin-bottom: 1rem;" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"/>
                </svg>
                <p>No API keys found.</p>
                <p style="margin-top: 0.5rem;">
                    <button class="btn btn-primary" onclick="openCreateModal()">Create your first API key</button>
                </p>
            </div>
            {% endif %}
        </div>
    </div>

    <!-- Create API Key Modal -->
    <div class="modal" id="createModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Create API Key</h3>
                <span class="modal-close" onclick="closeModal('createModal')">&times;</span>
            </div>
            <form id="createForm" onsubmit="createApiKey(event)">
                <div class="form-group">
                    <label for="keyName">Name *</label>
                    <input type="text" id="keyName" name="name" required maxlength="100" placeholder="e.g., Production Server">
                </div>
                <div class="form-group">
                    <label for="keyDescription">Description (optional)</label>
                    <textarea id="keyDescription" name="description" placeholder="What is this key used for?"></textarea>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn" onclick="closeModal('createModal')">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Key</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Key Created Modal -->
    <div class="modal" id="keyCreatedModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>API Key Created</h3>
                <span class="modal-close" onclick="closeKeyCreatedModal()">&times;</span>
            </div>
            <div class="alert alert-warning">
                <strong>Important:</strong> Copy your API key now. You won't be able to see it again!
            </div>
            <div class="form-group">
                <label>Your API Key</label>
                <div class="key-display" id="newKeyDisplay"></div>
                <button class="copy-btn" id="copyKeyBtn" onclick="copyKeyToClipboard()">Copy to Clipboard</button>
            </div>
            <div class="form-actions">
                <button class="btn btn-primary" onclick="closeKeyCreatedModal()">I've copied my key</button>
            </div>
        </div>
    </div>

    <script>
        let newApiKey = null;

        function showAlert(message, type = 'success') {
            const container = document.getElementById('alertContainer');
            container.innerHTML = `<div class="alert alert-${type}">${message}</div>`;
            setTimeout(() => container.innerHTML = '', 5000);
        }

        function openCreateModal() {
            document.getElementById('createForm').reset();
            document.getElementById('createModal').classList.add('active');
        }

        function closeModal(id) {
            document.getElementById(id).classList.remove('active');
        }

        function closeKeyCreatedModal() {
            closeModal('keyCreatedModal');
            newApiKey = null;
            location.reload();
        }

        async function createApiKey(e) {
            e.preventDefault();
            const form = e.target;
            const data = {
                name: form.name.value,
                description: form.description.value || null,
            };

            try {
                const res = await fetch('/api/api-keys', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data),
                });
                const result = await res.json();
                if (result.success) {
                    closeModal('createModal');
                    // Show the key in a new modal
                    newApiKey = result.raw_key;
                    document.getElementById('newKeyDisplay').textContent = newApiKey;
                    document.getElementById('keyCreatedModal').classList.add('active');
                } else {
                    showAlert(result.error || 'Failed to create API key', 'error');
                }
            } catch (err) {
                showAlert('An error occurred: ' + err.message, 'error');
            }
        }

        async function copyKeyToClipboard() {
            if (!newApiKey) return;

            try {
                await navigator.clipboard.writeText(newApiKey);
                const btn = document.getElementById('copyKeyBtn');
                btn.textContent = 'Copied!';
                btn.classList.add('copied');
                setTimeout(() => {
                    btn.textContent = 'Copy to Clipboard';
                    btn.classList.remove('copied');
                }, 2000);
            } catch (err) {
                // Fallback for older browsers
                const textarea = document.createElement('textarea');
                textarea.value = newApiKey;
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);

                const btn = document.getElementById('copyKeyBtn');
                btn.textContent = 'Copied!';
                btn.classList.add('copied');
                setTimeout(() => {
                    btn.textContent = 'Copy to Clipboard';
                    btn.classList.remove('copied');
                }, 2000);
            }
        }

        async function revokeKey(keyId, keyName) {
            if (!confirm(`Are you sure you want to revoke the API key "${keyName}"?\n\nThis action cannot be undone. Any applications using this key will no longer be able to authenticate.`)) {
                return;
            }

            try {
                const res = await fetch(`/api/api-keys/${keyId}`, { method: 'DELETE' });
                const result = await res.json();
                if (result.success) {
                    showAlert('API key revoked successfully');
                    location.reload();
                } else {
                    showAlert(result.error || 'Failed to revoke API key', 'error');
                }
            } catch (err) {
                showAlert('An error occurred: ' + err.message, 'error');
            }
        }
    </script>
</body>
</html>
