<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Webhooks - 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-success { background: var(--success); color: white; border-color: var(--success); }
        .btn-danger { background: var(--error); color: white; border-color: var(--error); }
        .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); }

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

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

        .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: 600px;
            max-height: 90vh;
            overflow-y: auto;
        }

        .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"],
        input[type="url"],
        input[type="number"],
        select {
            width: 100%;
            padding: 0.5rem 0.75rem;
            border: 1px solid var(--border);
            border-radius: 0.375rem;
            font-size: 0.875rem;
            font-family: inherit;
        }

        input:focus, select: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;
        }

        .checkbox-group {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
        }

        .checkbox-item {
            display: flex;
            align-items: center;
            gap: 0.25rem;
            padding: 0.25rem 0.5rem;
            border: 1px solid var(--border);
            border-radius: 0.25rem;
            font-size: 0.75rem;
        }

        .checkbox-item input { margin: 0; }

        .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); }

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

        .truncate {
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .events-list {
            display: flex;
            flex-wrap: wrap;
            gap: 0.25rem;
        }

        .delivery-status {
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div>
                <h1>Webhook Management</h1>
                <span class="version">{{ current_user.organization_name }}</span>
            </div>
            <div>
                <span style="margin-right: 1rem;">{{ current_user.email }}</span>
                <a href="{{ url_for('auth.logout') }}" class="btn btn-sm">Logout</a>
            </div>
        </header>

        <nav>
            <a href="{{ url_for('dashboard.index') }}">Dashboard</a>
            <a href="{{ url_for('dashboard.schedules') }}">Schedules</a>
            <a href="{{ url_for('dashboard.users') }}">Users</a>
            <a href="{{ url_for('dashboard.configs_page') }}">Configs</a>
            <a href="{{ url_for('dashboard.webhooks_page') }}" class="active">Webhooks</a>
            <a href="{{ url_for('dashboard.worksheets_page') }}">Worksheets</a>
        </nav>

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

        <div class="card">
            <div class="toolbar">
                <h2>Webhooks</h2>
                <button class="btn btn-primary" onclick="openAddModal()">Add Webhook</button>
            </div>

            {% if webhooks %}
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>URL</th>
                        <th>Events</th>
                        <th>Status</th>
                        <th>Failures</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {% for wh in webhooks %}
                    <tr data-webhook-id="{{ wh.id }}">
                        <td><strong>{{ wh.name }}</strong></td>
                        <td class="truncate">{{ wh.url }}</td>
                        <td>
                            <div class="events-list">
                                {% for event in wh.events[:3] %}
                                <span class="badge badge-info">{{ event.split('.')[1] }}</span>
                                {% endfor %}
                                {% if wh.events|length > 3 %}
                                <span class="badge badge-warning">+{{ wh.events|length - 3 }}</span>
                                {% endif %}
                            </div>
                        </td>
                        <td>
                            <span class="badge {% if wh.is_active %}badge-success{% else %}badge-error{% endif %}">
                                {{ 'Active' if wh.is_active else 'Inactive' }}
                            </span>
                        </td>
                        <td>
                            {% if wh.failure_count > 0 %}
                            <span class="badge badge-error">{{ wh.failure_count }}</span>
                            {% else %}
                            <span class="badge badge-success">0</span>
                            {% endif %}
                        </td>
                        <td>
                            <button class="btn btn-sm btn-success" onclick="testWebhook({{ wh.id }})">Test</button>
                            <button class="btn btn-sm" onclick="viewDeliveries({{ wh.id }}, '{{ wh.name }}')">Logs</button>
                            <button class="btn btn-sm" onclick="openEditModal({{ wh|tojson }})">Edit</button>
                            <button class="btn btn-sm btn-danger" onclick="deleteWebhook({{ wh.id }}, '{{ wh.name }}')">Delete</button>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
            {% else %}
            <div class="empty-state">
                <p>No webhooks configured.</p>
                <p style="margin-top: 0.5rem;">Click "Add Webhook" to receive notifications for sync events.</p>
            </div>
            {% endif %}
        </div>
    </div>

    <!-- Add/Edit Modal -->
    <div class="modal" id="webhookModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">Add Webhook</h3>
                <span class="modal-close" onclick="closeModal('webhookModal')">&times;</span>
            </div>
            <form id="webhookForm" onsubmit="saveWebhook(event)">
                <input type="hidden" id="webhookId" name="id">
                <div class="form-group">
                    <label for="webhookName">Name</label>
                    <input type="text" id="webhookName" name="name" required>
                </div>
                <div class="form-group">
                    <label for="webhookUrl">URL</label>
                    <input type="url" id="webhookUrl" name="url" placeholder="https://example.com/webhook" required>
                </div>
                <div class="form-group">
                    <label>Events</label>
                    <div class="checkbox-group">
                        <label class="checkbox-item">
                            <input type="checkbox" name="events" value="sync.started"> sync.started
                        </label>
                        <label class="checkbox-item">
                            <input type="checkbox" name="events" value="sync.completed" checked> sync.completed
                        </label>
                        <label class="checkbox-item">
                            <input type="checkbox" name="events" value="sync.failed" checked> sync.failed
                        </label>
                        <label class="checkbox-item">
                            <input type="checkbox" name="events" value="config.created"> config.created
                        </label>
                        <label class="checkbox-item">
                            <input type="checkbox" name="events" value="config.updated"> config.updated
                        </label>
                        <label class="checkbox-item">
                            <input type="checkbox" name="events" value="config.deleted"> config.deleted
                        </label>
                        <label class="checkbox-item">
                            <input type="checkbox" name="events" value="schedule.triggered"> schedule.triggered
                        </label>
                    </div>
                </div>
                <div class="form-group">
                    <label for="webhookSecret">Secret (for HMAC signature)</label>
                    <input type="text" id="webhookSecret" name="secret" placeholder="Auto-generated if empty">
                </div>
                <div class="form-group">
                    <label for="webhookRetries">Retry Count</label>
                    <input type="number" id="webhookRetries" name="retry_count" min="0" max="10" value="3">
                </div>
                <div class="form-actions">
                    <button type="button" class="btn" onclick="closeModal('webhookModal')">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Deliveries Modal -->
    <div class="modal" id="deliveriesModal">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header">
                <h3>Delivery Log: <span id="deliveriesTitle"></span></h3>
                <span class="modal-close" onclick="closeModal('deliveriesModal')">&times;</span>
            </div>
            <div id="deliveriesContent">
                <p>Loading...</p>
            </div>
        </div>
    </div>

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

        function openAddModal() {
            document.getElementById('modalTitle').textContent = 'Add Webhook';
            document.getElementById('webhookForm').reset();
            document.getElementById('webhookId').value = '';
            // Reset checkboxes
            document.querySelectorAll('#webhookForm input[name="events"]').forEach(cb => {
                cb.checked = cb.value === 'sync.completed' || cb.value === 'sync.failed';
            });
            document.getElementById('webhookModal').classList.add('active');
        }

        function openEditModal(webhook) {
            document.getElementById('modalTitle').textContent = 'Edit Webhook';
            document.getElementById('webhookId').value = webhook.id;
            document.getElementById('webhookName').value = webhook.name;
            document.getElementById('webhookUrl').value = webhook.url;
            document.getElementById('webhookRetries').value = webhook.retry_count;
            // Set event checkboxes
            document.querySelectorAll('#webhookForm input[name="events"]').forEach(cb => {
                cb.checked = webhook.events.includes(cb.value);
            });
            document.getElementById('webhookModal').classList.add('active');
        }

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

        async function saveWebhook(e) {
            e.preventDefault();
            const form = e.target;
            const id = form.querySelector('#webhookId').value;
            const isEdit = !!id;

            const events = Array.from(form.querySelectorAll('input[name="events"]:checked')).map(cb => cb.value);
            if (events.length === 0) {
                showAlert('Please select at least one event', 'error');
                return;
            }

            const data = {
                name: form.name.value,
                url: form.url.value,
                events: events,
                retry_count: parseInt(form.retry_count.value),
            };

            if (form.secret.value) {
                data.secret = form.secret.value;
            }

            try {
                const url = isEdit ? `/api/webhooks/${id}` : '/api/webhooks';
                const method = isEdit ? 'PUT' : 'POST';
                const res = await fetch(url, {
                    method,
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data),
                });
                const result = await res.json();
                if (result.success) {
                    if (!isEdit && result.webhook && result.webhook.secret) {
                        alert(`Webhook created! Save this secret - it won't be shown again:\n\n${result.webhook.secret}`);
                    }
                    showAlert(isEdit ? 'Webhook updated' : 'Webhook created');
                    closeModal('webhookModal');
                    location.reload();
                } else {
                    showAlert(result.message || 'Failed to save', 'error');
                }
            } catch (err) {
                showAlert('An error occurred', 'error');
            }
        }

        async function deleteWebhook(id, name) {
            if (!confirm(`Are you sure you want to delete "${name}"?`)) return;

            try {
                const res = await fetch(`/api/webhooks/${id}`, { method: 'DELETE' });
                const result = await res.json();
                if (result.success) {
                    showAlert('Webhook deleted');
                    location.reload();
                } else {
                    showAlert(result.message || 'Failed to delete', 'error');
                }
            } catch (err) {
                showAlert('An error occurred', 'error');
            }
        }

        async function testWebhook(id) {
            showAlert('Sending test webhook...');
            try {
                const res = await fetch(`/api/webhooks/${id}/test`, { method: 'POST' });
                const result = await res.json();
                if (result.success) {
                    showAlert('Test webhook delivered successfully');
                } else {
                    showAlert(result.message || 'Test webhook failed', 'error');
                }
            } catch (err) {
                showAlert('An error occurred', 'error');
            }
        }

        async function viewDeliveries(id, name) {
            document.getElementById('deliveriesTitle').textContent = name;
            document.getElementById('deliveriesContent').innerHTML = '<p>Loading...</p>';
            document.getElementById('deliveriesModal').classList.add('active');

            try {
                const res = await fetch(`/api/webhooks/${id}/deliveries`);
                const result = await res.json();
                if (result.success) {
                    if (result.deliveries.length === 0) {
                        document.getElementById('deliveriesContent').innerHTML = '<p>No deliveries yet.</p>';
                    } else {
                        let html = '<table><thead><tr><th>Time</th><th>Event</th><th>Status</th><th>Response</th></tr></thead><tbody>';
                        for (const d of result.deliveries) {
                            const time = d.created_at ? d.created_at.substring(0, 19).replace('T', ' ') : 'N/A';
                            const statusClass = d.status === 'success' ? 'badge-success' : d.status === 'failed' ? 'badge-error' : 'badge-warning';
                            html += `<tr>
                                <td>${time}</td>
                                <td>${d.event}</td>
                                <td><span class="badge ${statusClass}">${d.status}</span></td>
                                <td>${d.response_code || '-'} ${d.error_message ? '(' + d.error_message.substring(0, 50) + ')' : ''}</td>
                            </tr>`;
                        }
                        html += '</tbody></table>';
                        document.getElementById('deliveriesContent').innerHTML = html;
                    }
                } else {
                    document.getElementById('deliveriesContent').innerHTML = '<p>Failed to load deliveries.</p>';
                }
            } catch (err) {
                document.getElementById('deliveriesContent').innerHTML = '<p>An error occurred.</p>';
            }
        }
    </script>
</body>
</html>
