<script setup>
import { ref, computed } from 'vue'
import { Head, Link, router } from '@inertiajs/vue3'
import axios from 'axios'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { useConfirm } from '@/composables/useConfirm'
import {
    BeakerIcon,
    PlusIcon,
    TrashIcon,
    ClipboardDocumentIcon,
    CheckIcon,
    ArrowPathIcon,
    XMarkIcon,
    InboxArrowDownIcon,
    PaperAirplaneIcon,
    EyeIcon,
} from '@heroicons/vue/24/outline'

const { ask } = useConfirm()

const props = defineProps({
    inboxes:  { type: Array, default: () => [] },
    inbound:  { type: Array, default: () => [] },
    outbound: { type: Array, default: () => [] },
})

// ─── Tabs ────────────────────────────────────────────────────────────────────
const activeTab = ref('inbound')
const tabs = [
    { id: 'inbound',  label: 'Gelen (Inbound)', icon: InboxArrowDownIcon },
    { id: 'outbound', label: 'Giden (Outbound)', icon: PaperAirplaneIcon },
    { id: 'inboxes',  label: 'Inbox Yönetimi', icon: BeakerIcon },
]

// ─── Copy helper ─────────────────────────────────────────────────────────────
const copied = ref(null)
async function copyText(text, key) {
    await navigator.clipboard.writeText(text)
    copied.value = key
    setTimeout(() => { copied.value = null }, 1500)
}

function statusClass(code) {
    if (code === null || code === undefined) return 'bg-slate-200 text-slate-700 dark:bg-slate-700 dark:text-slate-300'
    if (code < 300) return 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300'
    if (code < 400) return 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300'
    return 'bg-rose-100 text-rose-800 dark:bg-rose-900/40 dark:text-rose-300'
}

function formatDate(d) {
    if (!d) return '—'
    return new Date(d).toLocaleString('tr-TR')
}

// ─── Inbox form (Inboxes tab) ────────────────────────────────────────────────
const newInbox = ref({ label: '', hmac_secret: '' })
const creatingInbox = ref(false)

function createInbox() {
    creatingInbox.value = true
    router.post(route('admin.webhook-playground.inbox.create'), newInbox.value, {
        preserveScroll: true,
        onSuccess: () => {
            newInbox.value = { label: '', hmac_secret: '' }
        },
        onFinish: () => { creatingInbox.value = false },
    })
}

async function deleteInbox(slug) {
    const ok = await ask({
        title: 'Inbox silinsin mi?',
        message: 'Bu inbox\'a ait tüm istek kayıtları da silinecek. Geri alınamaz.',
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('admin.webhook-playground.inbox.delete', slug), { preserveScroll: true })
}

// ─── Outbound form ───────────────────────────────────────────────────────────
const form = ref({
    url: '',
    method: 'POST',
    headers: [{ key: 'Content-Type', value: 'application/json' }],
    body: '{\n  "event": "test"\n}',
    hmac_secret: '',
})

const sending = ref(false)
const lastResult = ref(null)
const methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']

function addHeader()    { form.value.headers.push({ key: '', value: '' }) }
function removeHeader(i) { form.value.headers.splice(i, 1) }

function headersAsObject() {
    const obj = {}
    for (const h of form.value.headers) {
        if (h.key.trim()) obj[h.key.trim()] = h.value
    }
    return obj
}

async function sendOutbound() {
    sending.value = true
    lastResult.value = null
    try {
        const { data } = await axios.post(route('admin.webhook-playground.outbound'), {
            url: form.value.url,
            method: form.value.method,
            headers: headersAsObject(),
            body: form.value.body || '',
            hmac_secret: form.value.hmac_secret || null,
        })
        lastResult.value = data
        router.reload({ only: ['outbound'] })
    } catch (err) {
        lastResult.value = { error: err.response?.data?.message ?? err.message }
    } finally {
        sending.value = false
    }
}

async function replay(id) {
    const ok = await ask({
        title: 'Tekrar gönderilsin mi?',
        message: 'Bu istek aynı parametrelerle yeniden gönderilecek.',
        confirmText: 'Tekrar Gönder',
        cancelText: 'İptal',
    })
    if (!ok) return
    try {
        await axios.post(route('admin.webhook-playground.replay', id))
        router.reload({ only: ['inbound', 'outbound'] })
    } catch (err) {
        alert('Replay başarısız: ' + (err.response?.data?.message ?? err.message))
    }
}

const hasInboxes = computed(() => props.inboxes.length > 0)
</script>

<template>
    <Head title="Webhook Playground" />
    <AdminLayout>
        <div class="space-y-6">
            <!-- Header -->
            <div class="flex items-center gap-3">
                <BeakerIcon class="h-7 w-7 text-violet-500" />
                <div>
                    <h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100">Webhook Playground</h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400">
                        Gelen ve giden webhook trafiğini izleyin, test edin, yeniden gönderin.
                    </p>
                </div>
            </div>

            <!-- Tabs -->
            <div class="border-b border-slate-200 dark:border-slate-700">
                <nav class="-mb-px flex gap-6">
                    <button
                        v-for="t in tabs" :key="t.id"
                        @click="activeTab = t.id"
                        :class="[
                            'pb-3 text-sm font-medium border-b-2 transition-colors inline-flex items-center gap-2',
                            activeTab === t.id
                                ? 'border-violet-500 text-violet-600 dark:text-violet-400'
                                : 'border-transparent text-slate-500 hover:text-slate-700 dark:hover:text-slate-300',
                        ]"
                    >
                        <component :is="t.icon" class="h-4 w-4" />
                        {{ t.label }}
                    </button>
                </nav>
            </div>

            <!-- ═══════════════════════════════════════════════════ INBOUND ═══ -->
            <div v-if="activeTab === 'inbound'" class="space-y-4">
                <div v-if="!hasInboxes" class="rounded-xl border border-amber-200 bg-amber-50 dark:bg-amber-950/30 dark:border-amber-800 p-4 text-sm text-amber-800 dark:text-amber-300">
                    Henüz inbox yok. Önce "Inbox Yönetimi" sekmesinden bir inbox oluşturun.
                </div>

                <div class="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-700 overflow-hidden">
                    <div class="px-5 py-3 border-b border-slate-200 dark:border-slate-700 flex items-center justify-between">
                        <h2 class="font-semibold text-slate-800 dark:text-slate-200">Son Gelen İstekler (50)</h2>
                        <button @click="router.reload({ only: ['inbound'] })"
                                class="text-xs text-slate-500 hover:text-violet-600 inline-flex items-center gap-1">
                            <ArrowPathIcon class="h-3.5 w-3.5" /> Yenile
                        </button>
                    </div>

                    <div v-if="!inbound.length" class="p-8 text-center text-sm text-slate-400">
                        Henüz bir webhook gelmedi. Aşağıdaki inbox URL'lerinden birine POST atın.
                    </div>

                    <table v-else class="w-full text-sm">
                        <thead class="bg-slate-50 dark:bg-slate-800/50 text-xs text-slate-500 uppercase">
                            <tr>
                                <th class="px-4 py-2 text-left">Method</th>
                                <th class="px-4 py-2 text-left">Inbox</th>
                                <th class="px-4 py-2 text-left">Durum</th>
                                <th class="px-4 py-2 text-left">HMAC</th>
                                <th class="px-4 py-2 text-left">IP</th>
                                <th class="px-4 py-2 text-left">Süre</th>
                                <th class="px-4 py-2 text-left">Zaman</th>
                                <th class="px-4 py-2"></th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                            <tr v-for="r in inbound" :key="r.id" class="hover:bg-slate-50 dark:hover:bg-slate-800/40">
                                <td class="px-4 py-2 font-mono text-xs">
                                    <span class="inline-block px-2 py-0.5 rounded bg-violet-100 text-violet-700 dark:bg-violet-900/40 dark:text-violet-300 font-semibold">{{ r.method }}</span>
                                </td>
                                <td class="px-4 py-2 font-mono text-xs text-slate-500">{{ r.slug }}</td>
                                <td class="px-4 py-2">
                                    <span :class="['inline-block px-2 py-0.5 rounded text-xs font-semibold', statusClass(r.response_status)]">
                                        {{ r.response_status ?? 'OK' }}
                                    </span>
                                </td>
                                <td class="px-4 py-2 text-xs">
                                    <span v-if="r.hmac_valid === true" class="text-emerald-600">Geçerli</span>
                                    <span v-else-if="r.hmac_valid === false" class="text-rose-600">Geçersiz</span>
                                    <span v-else class="text-slate-400">—</span>
                                </td>
                                <td class="px-4 py-2 text-xs font-mono text-slate-500">{{ r.client_ip ?? '—' }}</td>
                                <td class="px-4 py-2 text-xs text-slate-500">{{ r.duration_ms }} ms</td>
                                <td class="px-4 py-2 text-xs text-slate-500">{{ formatDate(r.created_at) }}</td>
                                <td class="px-4 py-2 text-right">
                                    <Link :href="route('admin.webhook-playground.request.show', r.id)"
                                          class="inline-flex items-center gap-1 text-xs text-violet-600 hover:underline">
                                        <EyeIcon class="h-4 w-4" /> Detay
                                    </Link>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- ════════════════════════════════════════════════════ OUTBOUND ═══ -->
            <div v-if="activeTab === 'outbound'" class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Builder -->
                <div class="lg:col-span-2 space-y-4">
                    <div class="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-700 p-5 space-y-4">
                        <h2 class="font-semibold text-slate-800 dark:text-slate-200">İstek Gönder</h2>

                        <div class="flex gap-2">
                            <select v-model="form.method"
                                    class="rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-violet-400">
                                <option v-for="m in methods" :key="m">{{ m }}</option>
                            </select>
                            <input v-model="form.url" type="url" placeholder="https://hedef.example.com/webhook"
                                   class="flex-1 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-violet-400" />
                        </div>

                        <!-- Headers -->
                        <div>
                            <div class="flex items-center justify-between mb-2">
                                <label class="text-xs font-medium text-slate-600 dark:text-slate-400">Headers</label>
                                <button @click="addHeader" class="text-xs text-violet-600 hover:underline inline-flex items-center gap-1">
                                    <PlusIcon class="h-3 w-3" /> Header Ekle
                                </button>
                            </div>
                            <div v-for="(h, i) in form.headers" :key="i" class="flex gap-2 mb-1">
                                <input v-model="h.key" placeholder="Header adı"
                                       class="flex-1 rounded border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-violet-400" />
                                <input v-model="h.value" placeholder="Değer"
                                       class="flex-1 rounded border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-violet-400" />
                                <button @click="removeHeader(i)" class="text-slate-400 hover:text-rose-500">
                                    <XMarkIcon class="h-4 w-4" />
                                </button>
                            </div>
                        </div>

                        <div>
                            <label class="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">Body</label>
                            <textarea v-model="form.body" rows="8" spellcheck="false"
                                      class="w-full rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 px-3 py-2 text-xs font-mono focus:outline-none focus:ring-2 focus:ring-violet-400"></textarea>
                            <p class="text-xs text-slate-400 mt-1">Maks. 64 KB. Üzerindeki kısım kaydedilirken kırpılır.</p>
                        </div>

                        <div>
                            <label class="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">
                                HMAC Secret (opsiyonel — <code class="font-mono">X-Onoxsoft-Signature</code> header'ı imzalanır)
                            </label>
                            <input v-model="form.hmac_secret" type="password" placeholder="Gizli anahtar"
                                   class="w-full rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-violet-400" />
                        </div>

                        <button @click="sendOutbound" :disabled="sending || !form.url"
                                class="inline-flex items-center gap-2 rounded-lg bg-violet-600 hover:bg-violet-700 disabled:opacity-60 text-white px-5 py-2.5 text-sm font-semibold transition-colors">
                            <ArrowPathIcon v-if="sending" class="h-4 w-4 animate-spin" />
                            <PaperAirplaneIcon v-else class="h-4 w-4" />
                            {{ sending ? 'Gönderiliyor…' : 'Gönder' }}
                        </button>

                        <!-- Last result inline -->
                        <div v-if="lastResult" class="rounded-lg border border-slate-200 dark:border-slate-700 p-3 text-xs space-y-1">
                            <div v-if="lastResult.error" class="text-rose-600 font-mono">{{ lastResult.error }}</div>
                            <div v-else>
                                <span :class="['inline-block px-2 py-0.5 rounded font-semibold', statusClass(lastResult.status)]">
                                    {{ lastResult.status ?? 'ERR' }}
                                </span>
                                <span class="text-slate-400 ml-2">{{ lastResult.duration_ms }} ms</span>
                                <Link v-if="lastResult.id" :href="route('admin.webhook-playground.request.show', lastResult.id)"
                                      class="ml-2 text-violet-600 hover:underline">
                                    Detay görüntüle →
                                </Link>
                            </div>
                            <div v-if="lastResult.signature" class="font-mono text-slate-500 truncate">
                                İmza: {{ lastResult.signature }}
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Recent outbound table -->
                <div class="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-700 overflow-hidden">
                    <div class="px-4 py-3 border-b border-slate-200 dark:border-slate-700">
                        <h3 class="font-semibold text-sm text-slate-800 dark:text-slate-200">Son Gönderilenler</h3>
                    </div>
                    <div v-if="!outbound.length" class="p-6 text-center text-xs text-slate-400">
                        Henüz gönderim yok.
                    </div>
                    <ul v-else class="divide-y divide-slate-100 dark:divide-slate-800 max-h-[600px] overflow-y-auto">
                        <li v-for="r in outbound" :key="r.id" class="p-3 hover:bg-slate-50 dark:hover:bg-slate-800/40">
                            <div class="flex items-start gap-2">
                                <span class="inline-block px-2 py-0.5 rounded bg-violet-100 text-violet-700 dark:bg-violet-900/40 dark:text-violet-300 font-mono text-xs shrink-0">{{ r.method }}</span>
                                <span :class="['inline-block px-2 py-0.5 rounded text-xs font-semibold shrink-0', statusClass(r.response_status)]">
                                    {{ r.response_status ?? 'ERR' }}
                                </span>
                                <span class="text-xs text-slate-400 ml-auto">{{ r.duration_ms }} ms</span>
                            </div>
                            <p class="text-xs font-mono text-slate-500 truncate mt-1">{{ r.url }}</p>
                            <div class="flex items-center justify-between mt-1">
                                <span class="text-xs text-slate-400">{{ formatDate(r.created_at) }}</span>
                                <div class="flex gap-2">
                                    <Link :href="route('admin.webhook-playground.request.show', r.id)"
                                          class="text-xs text-violet-600 hover:underline">Detay</Link>
                                    <button @click="replay(r.id)" class="text-xs text-slate-500 hover:text-violet-600">Tekrar</button>
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>

            <!-- ════════════════════════════════════════════════════ INBOXES ═══ -->
            <div v-if="activeTab === 'inboxes'" class="space-y-5">
                <!-- New inbox form -->
                <div class="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-700 p-5 space-y-3">
                    <h2 class="font-semibold text-slate-800 dark:text-slate-200">Yeni Inbox Oluştur</h2>
                    <p class="text-xs text-slate-500">
                        Inbox URL'leri kimlik doğrulaması olmadan POST kabul eder. İsteğe bağlı HMAC secret tanımlarsanız
                        <code class="font-mono">X-Onoxsoft-Signature</code> header'ı sha256 ile doğrulanır.
                    </p>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <input v-model="newInbox.label" type="text" placeholder="Etiket (Örn: WHMCS Test)"
                               class="rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-violet-400" />
                        <input v-model="newInbox.hmac_secret" type="password" placeholder="HMAC Secret (opsiyonel)"
                               class="rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-violet-400" />
                    </div>
                    <button @click="createInbox" :disabled="creatingInbox"
                            class="inline-flex items-center gap-2 rounded-lg bg-violet-600 hover:bg-violet-700 disabled:opacity-60 text-white px-5 py-2 text-sm font-semibold">
                        <PlusIcon class="h-4 w-4" /> Oluştur
                    </button>
                </div>

                <!-- Inbox list -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div v-if="!inboxes.length" class="col-span-full text-sm text-slate-400 italic text-center py-8">
                        Henüz inbox tanımlı değil.
                    </div>
                    <div v-for="ib in inboxes" :key="ib.id"
                         class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-xl p-4 space-y-2">
                        <div class="flex items-start justify-between gap-2">
                            <div class="min-w-0">
                                <p class="font-semibold text-slate-800 dark:text-slate-200 truncate">
                                    {{ ib.label || ib.slug }}
                                </p>
                                <p class="text-xs text-slate-400 font-mono">{{ ib.slug }}</p>
                            </div>
                            <button @click="deleteInbox(ib.slug)" class="text-slate-400 hover:text-rose-500">
                                <TrashIcon class="h-4 w-4" />
                            </button>
                        </div>

                        <div class="flex items-center gap-2 text-xs text-slate-500">
                            <span>{{ ib.received_count }} istek</span>
                            <span>•</span>
                            <span>Son: {{ formatDate(ib.last_received_at) }}</span>
                            <span v-if="ib.has_secret" class="ml-auto inline-block px-2 py-0.5 rounded bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300 font-semibold">HMAC</span>
                        </div>

                        <div class="flex items-center gap-2 bg-slate-50 dark:bg-slate-800 rounded p-2">
                            <code class="text-xs font-mono text-slate-600 dark:text-slate-300 truncate flex-1">{{ ib.url }}</code>
                            <button @click="copyText(ib.url, 'ib-' + ib.id)" class="shrink-0 text-slate-400 hover:text-violet-600">
                                <CheckIcon v-if="copied === 'ib-' + ib.id" class="h-4 w-4 text-emerald-500" />
                                <ClipboardDocumentIcon v-else class="h-4 w-4" />
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
