{% extends "dashboard/base.html" %}

{% block title %}{{ t.oauth_clients }}{% endblock %}
{% block page_title %}{{ t.oauth_clients }}{% endblock %}

{% block content %}
<div class="space-y-6">
    <!-- Header with Create Button -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
            <p class="text-gray-500 dark:text-gray-400">
                {% if lang == 'fa' %}
                مدیریت کلاینت‌های OAuth برای دسترسی امن به API
                {% else %}
                Manage OAuth clients for secure API access
                {% endif %}
            </p>
        </div>
        <button
            onclick="openCreateModal()"
            class="px-4 py-2 bg-primary-600 hover:bg-primary-700 rounded-lg text-white text-sm transition-colors inline-flex items-center gap-2"
        >
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
            </svg>
            {% if lang == 'fa' %}ایجاد کلاینت{% else %}Create Client{% endif %}
        </button>
    </div>

    <!-- Stats -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 dark:text-gray-400">{% if lang == 'fa' %}کل کلاینت‌ها{% else %}Total Clients{% endif %}</p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-white">{{ total_count }}</p>
                </div>
                <div class="w-10 h-10 bg-blue-500/20 rounded-lg flex items-center justify-center">
                    <svg class="w-5 h-5 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"/>
                    </svg>
                </div>
            </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 dark:text-gray-400">{% if lang == 'fa' %}کلاینت‌های فعال{% else %}Active Clients{% endif %}</p>
                    <p class="text-2xl font-bold text-green-400">{{ total_count }}</p>
                </div>
                <div class="w-10 h-10 bg-green-500/20 rounded-lg flex items-center justify-center">
                    <svg class="w-5 h-5 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                </div>
            </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 dark:text-gray-400">{% if lang == 'fa' %}پروتکل{% else %}Protocol{% endif %}</p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-white">OAuth 2.1</p>
                </div>
                <div class="w-10 h-10 bg-purple-500/20 rounded-lg flex items-center justify-center">
                    <svg class="w-5 h-5 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
                    </svg>
                </div>
            </div>
        </div>
    </div>

    <!-- Clients Table -->
    <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 dark:bg-gray-700/50">
                    <tr>
                        <th class="px-6 py-4 text-{% if lang == 'fa' %}right{% else %}left{% endif %} text-sm font-medium text-gray-700 dark:text-gray-300">
                            {% if lang == 'fa' %}نام کلاینت{% else %}Client Name{% endif %}
                        </th>
                        <th class="px-6 py-4 text-{% if lang == 'fa' %}right{% else %}left{% endif %} text-sm font-medium text-gray-700 dark:text-gray-300">
                            {% if lang == 'fa' %}شناسه کلاینت{% else %}Client ID{% endif %}
                        </th>
                        <th class="px-6 py-4 text-{% if lang == 'fa' %}right{% else %}left{% endif %} text-sm font-medium text-gray-700 dark:text-gray-300">
                            {% if lang == 'fa' %}دامنه‌ها{% else %}Scopes{% endif %}
                        </th>
                        <th class="px-6 py-4 text-{% if lang == 'fa' %}right{% else %}left{% endif %} text-sm font-medium text-gray-700 dark:text-gray-300">
                            {% if lang == 'fa' %}تاریخ ایجاد{% else %}Created{% endif %}
                        </th>
                        <th class="px-6 py-4 text-{% if lang == 'fa' %}right{% else %}left{% endif %} text-sm font-medium text-gray-700 dark:text-gray-300">
                            {% if lang == 'fa' %}عملیات{% else %}Actions{% endif %}
                        </th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                    {% if clients %}
                        {% for client in clients %}
                        <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors">
                            <td class="px-6 py-4">
                                <span class="text-gray-900 dark:text-white font-medium">{{ client.client_name }}</span>
                            </td>
                            <td class="px-6 py-4">
                                <code class="text-sm text-gray-500 dark:text-gray-400 bg-gray-900 px-2 py-1 rounded">{{ client.client_id[:30] }}...</code>
                            </td>
                            <td class="px-6 py-4">
                                <div class="flex flex-wrap gap-1">
                                    {% for scope in client.allowed_scopes %}
                                    <span class="px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded">{{ scope }}</span>
                                    {% endfor %}
                                </div>
                            </td>
                            <td class="px-6 py-4">
                                <span class="text-sm text-gray-500 dark:text-gray-400">{{ client.created_at[:10] if client.created_at else '-' }}</span>
                            </td>
                            <td class="px-6 py-4">
                                <div class="flex items-center gap-2">
                                    <button
                                        onclick="showClientDetails({{ loop.index }})"
                                        class="p-2 text-gray-400 hover:text-white transition-colors"
                                        title="{% if lang == 'fa' %}جزئیات{% else %}Details{% endif %}"
                                    >
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                                        </svg>
                                    </button>
                                    <button
                                        onclick="confirmDeleteClient('{{ client.client_id }}', '{{ client.client_name }}')"
                                        class="p-2 text-red-400 hover:text-red-300 transition-colors"
                                        title="{{ t.delete }}"
                                    >
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                                        </svg>
                                    </button>
                                </div>
                            </td>
                        </tr>

                        <!-- Details Row (hidden by default) -->
                        <tr id="details-{{ loop.index }}" class="hidden bg-gray-900/50">
                            <td colspan="5" class="px-6 py-4">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <p class="text-sm text-gray-500 dark:text-gray-400 mb-1">{% if lang == 'fa' %}آدرس‌های Redirect{% else %}Redirect URIs{% endif %}</p>
                                        <div class="space-y-1">
                                            {% for uri in client.redirect_uris %}
                                            <code class="block text-xs text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-800 px-2 py-1 rounded">{{ uri }}</code>
                                            {% endfor %}
                                        </div>
                                    </div>
                                    <div>
                                        <p class="text-sm text-gray-500 dark:text-gray-400 mb-1">{% if lang == 'fa' %}انواع Grant{% else %}Grant Types{% endif %}</p>
                                        <div class="flex flex-wrap gap-1">
                                            {% for grant in client.grant_types %}
                                            <span class="px-2 py-0.5 bg-purple-500/20 text-purple-400 text-xs rounded">{{ grant }}</span>
                                            {% endfor %}
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    {% else %}
                        <tr>
                            <td colspan="5" class="px-6 py-12 text-center">
                                <svg class="w-12 h-12 mx-auto mb-4 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"/>
                                </svg>
                                <p class="text-gray-500 dark:text-gray-400 mb-4">
                                    {% if lang == 'fa' %}هیچ کلاینت OAuth ثبت نشده{% else %}No OAuth clients registered{% endif %}
                                </p>
                                <button
                                    onclick="openCreateModal()"
                                    class="px-4 py-2 bg-primary-600 hover:bg-primary-700 rounded-lg text-white text-sm transition-colors"
                                >
                                    {% if lang == 'fa' %}ایجاد اولین کلاینت{% else %}Create First Client{% endif %}
                                </button>
                            </td>
                        </tr>
                    {% endif %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Create Client Modal -->
<div id="createModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 w-full max-w-lg mx-4">
        <h3 class="text-xl font-semibold text-white mb-4">
            {% if lang == 'fa' %}ایجاد کلاینت OAuth{% else %}Create OAuth Client{% endif %}
        </h3>

        <form id="createForm" class="space-y-4">
            <div>
                <label class="block text-sm text-gray-500 dark:text-gray-400 mb-1">{% if lang == 'fa' %}نام کلاینت{% else %}Client Name{% endif %}</label>
                <input
                    type="text"
                    name="client_name"
                    required
                    class="w-full bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg px-4 py-2 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                    placeholder="{% if lang == 'fa' %}مثال: My MCP Client{% else %}e.g., My MCP Client{% endif %}"
                >
            </div>

            <div>
                <label class="block text-sm text-gray-500 dark:text-gray-400 mb-1">{% if lang == 'fa' %}آدرس‌های Redirect{% else %}Redirect URIs{% endif %}</label>
                <textarea
                    name="redirect_uris"
                    required
                    rows="3"
                    class="w-full bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg px-4 py-2 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                >https://claude.ai/api/mcp/auth_callback
https://claude.com/api/mcp/auth_callback</textarea>
                <p class="text-xs text-gray-500 mt-1">
                    {% if lang == 'fa' %}هر آدرس را در یک خط جداگانه وارد کنید{% else %}Enter one URI per line{% endif %}
                </p>
            </div>

            <div>
                <div class="flex items-center gap-3">
                    <span class="px-3 py-1 bg-green-100 dark:bg-green-500/20 text-green-700 dark:text-green-400 text-sm font-medium rounded-lg">
                        {% if lang == 'fa' %}دسترسی کامل{% else %}Full Access{% endif %}
                    </span>
                    <p class="text-xs text-gray-500 dark:text-gray-400">
                        {% if lang == 'fa' %}دسترسی ابزار در تنظیمات هر سایت کنترل می‌شود.{% else %}Tool access is controlled per-site in Site Settings.{% endif %}
                    </p>
                </div>
            </div>

            <div class="flex justify-end gap-3 pt-4">
                <button
                    type="button"
                    onclick="closeCreateModal()"
                    class="px-4 py-2 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 rounded-lg text-white text-sm transition-colors"
                >
                    {{ t.cancel }}
                </button>
                <button
                    type="submit"
                    class="px-4 py-2 bg-primary-600 hover:bg-primary-700 rounded-lg text-white text-sm transition-colors"
                >
                    {{ t.create }}
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Success Modal (shows client secret) -->
<div id="successModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 w-full max-w-lg mx-4">
        <div class="text-center">
            <div class="w-16 h-16 bg-green-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
                <svg class="w-8 h-8 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                </svg>
            </div>
            <h3 class="text-xl font-semibold text-white mb-2">
                {% if lang == 'fa' %}کلاینت ایجاد شد{% else %}Client Created{% endif %}
            </h3>
            <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">
                {% if lang == 'fa' %}این رمز فقط یکبار نمایش داده می‌شود. آن را در جای امنی ذخیره کنید.{% else %}This secret is only shown once. Save it in a secure place.{% endif %}
            </p>
        </div>

        <div class="space-y-3 mb-6">
            <div>
                <label class="block text-sm text-gray-500 dark:text-gray-400 mb-1">Client ID</label>
                <div class="flex items-center gap-2">
                    <code id="newClientId" class="flex-1 bg-gray-900 px-3 py-2 rounded text-sm text-gray-700 dark:text-gray-300 overflow-x-auto"></code>
                    <button onclick="copyToClipboard('newClientId')" class="p-2 text-gray-400 hover:text-white">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                        </svg>
                    </button>
                </div>
            </div>
            <div>
                <label class="block text-sm text-gray-500 dark:text-gray-400 mb-1">Client Secret</label>
                <div class="flex items-center gap-2">
                    <code id="newClientSecret" class="flex-1 bg-gray-900 px-3 py-2 rounded text-sm text-green-400 overflow-x-auto"></code>
                    <button onclick="copyToClipboard('newClientSecret')" class="p-2 text-gray-400 hover:text-white">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                        </svg>
                    </button>
                </div>
            </div>
        </div>

        <button
            onclick="closeSuccessModal()"
            class="w-full px-4 py-2 bg-primary-600 hover:bg-primary-700 rounded-lg text-white text-sm transition-colors"
        >
            {% if lang == 'fa' %}متوجه شدم{% else %}I understand{% endif %}
        </button>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div id="deleteModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 w-full max-w-md mx-4">
        <div class="text-center">
            <div class="w-16 h-16 bg-red-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
                <svg class="w-8 h-8 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                </svg>
            </div>
            <h3 class="text-xl font-semibold text-white mb-2">
                {% if lang == 'fa' %}حذف کلاینت{% else %}Delete Client{% endif %}
            </h3>
            <p class="text-gray-500 dark:text-gray-400 mb-1">
                {% if lang == 'fa' %}آیا مطمئن هستید که می‌خواهید این کلاینت را حذف کنید؟{% else %}Are you sure you want to delete this client?{% endif %}
            </p>
            <p id="deleteClientName" class="text-white font-medium mb-4"></p>
        </div>

        <div class="flex gap-3">
            <button
                onclick="closeDeleteModal()"
                class="flex-1 px-4 py-2 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 rounded-lg text-white text-sm transition-colors"
            >
                {{ t.cancel }}
            </button>
            <button
                onclick="deleteClient()"
                class="flex-1 px-4 py-2 bg-red-600 hover:bg-red-700 rounded-lg text-white text-sm transition-colors"
            >
                {{ t.delete }}
            </button>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
(function() {
    if (window.oauthClientsPageInitialized) return;
    window.oauthClientsPageInitialized = true;

    var currentDeleteClientId = null;

    function openCreateModal() {
        document.getElementById('createModal').classList.remove('hidden');
        document.getElementById('createModal').classList.add('flex');
    }

    function closeCreateModal() {
        document.getElementById('createModal').classList.add('hidden');
        document.getElementById('createModal').classList.remove('flex');
        document.getElementById('createForm').reset();
    }

    function closeSuccessModal() {
        document.getElementById('successModal').classList.add('hidden');
        document.getElementById('successModal').classList.remove('flex');
        window.location.reload();
    }

    function showClientDetails(index) {
        var row = document.getElementById('details-' + index);
        if (row) {
            row.classList.toggle('hidden');
        }
    }

    function confirmDeleteClient(clientId, clientName) {
        currentDeleteClientId = clientId;
        document.getElementById('deleteClientName').textContent = clientName;
        document.getElementById('deleteModal').classList.remove('hidden');
        document.getElementById('deleteModal').classList.add('flex');
    }

    function closeDeleteModal() {
        document.getElementById('deleteModal').classList.add('hidden');
        document.getElementById('deleteModal').classList.remove('flex');
        currentDeleteClientId = null;
    }

    function deleteClient() {
        if (!currentDeleteClientId) return;

        fetch('/api/dashboard/oauth-clients/' + currentDeleteClientId, {
            method: 'DELETE',
            credentials: 'same-origin'
        })
        .then(function(response) { return response.json(); })
        .then(function(data) {
            if (data.success) {
                window.location.reload();
            } else {
                alert(data.error || 'Failed to delete client');
            }
        })
        .catch(function(error) {
            console.error('Error:', error);
            alert('Failed to delete client');
        });

        closeDeleteModal();
    }

    function copyToClipboard(elementId) {
        var text = document.getElementById(elementId).textContent;
        navigator.clipboard.writeText(text).then(function() {
            alert('{% if lang == "fa" %}کپی شد{% else %}Copied{% endif %}');
        });
    }

    // Form submission
    document.getElementById('createForm').addEventListener('submit', function(e) {
        e.preventDefault();

        var formData = new FormData(this);
        // F.7c: All clients get full scope — tool access controlled per-site
        var scopes = ['read', 'write', 'admin'];

        // Parse redirect URIs (one per line)
        var redirectUrisText = formData.get('redirect_uris') || '';
        var redirectUris = redirectUrisText.split('\n')
            .map(function(uri) { return uri.trim(); })
            .filter(function(uri) { return uri.length > 0; });

        var data = {
            client_name: formData.get('client_name'),
            redirect_uris: redirectUris,
            scopes: scopes
        };

        fetch('/api/dashboard/oauth-clients/create', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            credentials: 'same-origin',
            body: JSON.stringify(data)
        })
        .then(function(response) { return response.json(); })
        .then(function(data) {
            if (data.success) {
                closeCreateModal();
                document.getElementById('newClientId').textContent = data.client_id;
                document.getElementById('newClientSecret').textContent = data.client_secret;
                document.getElementById('successModal').classList.remove('hidden');
                document.getElementById('successModal').classList.add('flex');
            } else {
                alert(data.error || 'Failed to create client');
            }
        })
        .catch(function(error) {
            console.error('Error:', error);
            alert('Failed to create client');
        });
    });

    // Expose functions to window
    window.openCreateModal = openCreateModal;
    window.closeCreateModal = closeCreateModal;
    window.closeSuccessModal = closeSuccessModal;
    window.showClientDetails = showClientDetails;
    window.confirmDeleteClient = confirmDeleteClient;
    window.closeDeleteModal = closeDeleteModal;
    window.deleteClient = deleteClient;
    window.copyToClipboard = copyToClipboard;
})();
</script>
{% endblock %}
