<script setup>
import { ref, computed } from 'vue'
import { Head, useForm, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    ArrowUpRightIcon,
    PlusIcon,
    TrashIcon,
    PencilIcon,
    BoltIcon,
    ListBulletIcon,
    XMarkIcon,
    CheckCircleIcon,
    ExclamationCircleIcon,
    ArrowPathIcon,
    ClipboardDocumentCheckIcon,
    KeyIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    endpoints:        Array,
    totals:           Object,
    available_events: Array,
})

// ─── Modals ───────────────────────────────────────────────────────────────────
const showCreateModal = ref(false)
const showEditModal   = ref(false)
const editTarget      = ref(null)

// ─── Test result state ────────────────────────────────────────────────────────
const testingId     = ref(null)
const testResult    = ref(null)
const testResultId  = ref(null)

// ─── Forms ────────────────────────────────────────────────────────────────────
const blankForm = () => ({
    name:            '',
    url:             '',
    secret:          '',
    is_active:       true,
    events:          [],
    retry_count:     3,
    timeout_seconds: 30,
})

const createForm = useForm(blankForm())
const editForm   = useForm(blankForm())

const openCreate = () => {
    createForm.reset()
    Object.assign(createForm, blankForm())
    showCreateModal.value = true
}

const openEdit = (ep) => {
    editTarget.value = ep
    editForm.name            = ep.name
    editForm.url             = ep.url
    editForm.secret          = ep.secret
    editForm.is_active       = !!ep.is_active
    editForm.events          = Array.isArray(ep.events) ? [...ep.events] : []
    editForm.retry_count     = ep.retry_count
    editForm.timeout_seconds = ep.timeout_seconds
    showEditModal.value      = true
}

const submitCreate = () => {
    createForm.post(route('admin.webhooks.outbound.store'), {
        preserveScroll: true,
        onSuccess: () => { showCreateModal.value = false },
    })
}

const submitEdit = () => {
    editForm.patch(route('admin.webhooks.outbound.update', editTarget.value.id), {
        preserveScroll: true,
        onSuccess: () => { showEditModal.value = false },
    })
}

const toggle = (id) => {
    router.post(route('admin.webhooks.outbound.toggle', id), {}, { preserveScroll: true })
}

const destroy = async (ep) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `"${ep.name}" endpoint silinsin mi?`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('admin.webhooks.outbound.destroy', ep.id), { preserveScroll: true })
}

const test = async (ep) => {
    testingId.value    = ep.id
    testResult.value   = null
    testResultId.value = ep.id
    try {
        const res = await fetch(route('admin.webhooks.outbound.test', ep.id), {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content,
                'Accept': 'application/json',
            },
        })
        testResult.value = await res.json()
    } catch (e) {
        testResult.value = { success: false, error: e.message }
    } finally {
        testingId.value = null
    }
}

const viewLogs = (ep) => {
    router.visit(route('admin.webhooks.outbound.logs', ep.id))
}

// ─── Secret generator ─────────────────────────────────────────────────────────
const generateSecret = (form) => {
    const arr = new Uint8Array(32)
    crypto.getRandomValues(arr)
    form.secret = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('')
}

// ─── Helpers ──────────────────────────────────────────────────────────────────
const statusBadge = (ep) => {
    if (!ep.is_active)       return 'bg-slate-100 text-slate-500'
    if (ep.failure_count > 5) return 'bg-red-100 text-red-700'
    if (ep.failure_count > 0) return 'bg-amber-100 text-amber-700'
    return 'bg-emerald-100 text-emerald-700'
}
const statusLabel = (ep) => {
    if (!ep.is_active)       return 'Pasif'
    if (ep.failure_count > 5) return 'Hatalı'
    if (ep.failure_count > 0) return 'Uyarı'
    return 'Aktif'
}
const formatDate = (d) => {
    if (!d) return '—'
    return new Date(d).toLocaleDateString('tr-TR', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })
}
const truncateUrl = (url) => url.length > 50 ? url.slice(0, 50) + '…' : url

const successRateDisplay = computed(() => {
    return props.totals.success_rate !== null ? `%${props.totals.success_rate}` : '—'
})

// ─── Event checkbox helpers ───────────────────────────────────────────────────
const eventLabel = (e) => ({
    'account.provisioned':  'Hesap Oluşturuldu',
    'account.suspended':    'Hesap Askıya Alındı',
    'account.unsuspended':  'Askı Kaldırıldı',
    'account.terminated':   'Hesap Silindi',
    'account.quota_exceeded': 'Kota Aşıldı',
    'ssl.issued':           'SSL Sertifikası Verildi',
    'ssl.renewed':          'SSL Sertifikası Yenilendi',
    'ssl.expiring':         'SSL Sona Eriyor',
}[e] || e)

const toggleEvent = (form, ev) => {
    const idx = form.events.indexOf(ev)
    if (idx === -1) form.events.push(ev)
    else form.events.splice(idx, 1)
}
const selectAllEvents = (form) => { form.events = [...props.available_events] }
const clearAllEvents  = (form) => { form.events = [] }
</script>

<template>
    <Head title="Outbound Webhooks" />
    <AdminLayout>
        <template #header>Outbound Webhook Yönetimi</template>

        <!-- ─── Stat Cards ───────────────────────────────────────────────────── -->
        <div class="mb-5 grid grid-cols-2 gap-3 sm:grid-cols-4">
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <ArrowUpRightIcon class="h-5 w-5 text-slate-400" />
                <div class="mt-2 text-2xl font-bold text-slate-800">{{ totals.total }}</div>
                <p class="text-xs text-slate-500">Toplam Endpoint</p>
            </div>
            <div class="rounded-xl border border-emerald-200 bg-emerald-50 p-4">
                <CheckCircleIcon class="h-5 w-5 text-emerald-500" />
                <div class="mt-2 text-2xl font-bold text-emerald-700">{{ totals.active }}</div>
                <p class="text-xs text-emerald-700">Aktif</p>
            </div>
            <div class="rounded-xl border border-blue-200 bg-blue-50 p-4">
                <BoltIcon class="h-5 w-5 text-blue-500" />
                <div class="mt-2 text-2xl font-bold text-blue-700">{{ totals.calls_24h }}</div>
                <p class="text-xs text-blue-700">Son 24s Çağrı</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <ClipboardDocumentCheckIcon class="h-5 w-5 text-slate-400" />
                <div class="mt-2 text-2xl font-bold text-slate-800">{{ successRateDisplay }}</div>
                <p class="text-xs text-slate-500">Başarı Oranı</p>
            </div>
        </div>

        <!-- ─── Table header ────────────────────────────────────────────────── -->
        <div class="mb-4 flex items-center justify-between">
            <h2 class="text-sm font-semibold text-slate-700">Endpoint Listesi</h2>
            <button @click="openCreate"
                class="inline-flex items-center gap-2 rounded-lg bg-rose-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-rose-700">
                <PlusIcon class="h-4 w-4" />
                Yeni Endpoint
            </button>
        </div>

        <!-- ─── Endpoint Table ───────────────────────────────────────────────── -->
        <div class="rounded-xl border border-slate-200 bg-white shadow-sm overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="border-b border-slate-100 bg-slate-50 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
                            <th class="px-4 py-3">Ad / URL</th>
                            <th class="px-4 py-3 text-center">Event</th>
                            <th class="px-4 py-3">Son Çağrı</th>
                            <th class="px-4 py-3 text-center">Hata</th>
                            <th class="px-4 py-3 text-center">Durum</th>
                            <th class="px-4 py-3 text-center">Aktif</th>
                            <th class="px-4 py-3 text-right">İşlemler</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-50">
                        <tr v-if="endpoints.length === 0">
                            <td colspan="7" class="px-4 py-8 text-center text-sm text-slate-400">
                                Henüz endpoint yok. Yeni endpoint ekleyin.
                            </td>
                        </tr>
                        <tr v-for="ep in endpoints" :key="ep.id" class="hover:bg-slate-50 transition-colors">
                            <td class="px-4 py-3 max-w-xs">
                                <div class="font-medium text-slate-800">{{ ep.name }}</div>
                                <div class="text-xs text-slate-400 truncate" :title="ep.url">{{ truncateUrl(ep.url) }}</div>
                            </td>
                            <td class="px-4 py-3 text-center">
                                <span class="inline-block rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-600">
                                    {{ ep.events?.length ?? 0 }} event
                                </span>
                            </td>
                            <td class="px-4 py-3 text-xs text-slate-500">{{ formatDate(ep.last_call_at) }}</td>
                            <td class="px-4 py-3 text-center">
                                <span v-if="ep.failure_count > 0"
                                    class="inline-block rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-700">
                                    {{ ep.failure_count }}
                                </span>
                                <span v-else class="text-slate-300">—</span>
                            </td>
                            <td class="px-4 py-3 text-center">
                                <span :class="['inline-block rounded-full px-2 py-0.5 text-xs font-semibold', statusBadge(ep)]">
                                    {{ statusLabel(ep) }}
                                </span>
                            </td>
                            <td class="px-4 py-3 text-center">
                                <button @click="toggle(ep.id)"
                                    :class="['relative inline-flex h-5 w-10 flex-shrink-0 rounded-full border-2 border-transparent transition-colors',
                                        ep.is_active ? 'bg-emerald-500' : 'bg-slate-200']">
                                    <span :class="['inline-block h-4 w-4 rounded-full bg-white shadow transition-transform',
                                        ep.is_active ? 'translate-x-5' : 'translate-x-0']" />
                                </button>
                            </td>
                            <td class="px-4 py-3">
                                <div class="flex items-center justify-end gap-1">
                                    <button @click="test(ep)"
                                        :disabled="testingId === ep.id"
                                        class="rounded p-1.5 text-slate-400 hover:bg-blue-50 hover:text-blue-600 transition-colors disabled:opacity-50"
                                        title="Test Et">
                                        <ArrowPathIcon v-if="testingId === ep.id" class="h-4 w-4 animate-spin" />
                                        <BoltIcon v-else class="h-4 w-4" />
                                    </button>
                                    <button @click="viewLogs(ep)"
                                        class="rounded p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-700 transition-colors"
                                        title="Loglar">
                                        <ListBulletIcon class="h-4 w-4" />
                                    </button>
                                    <button @click="openEdit(ep)"
                                        class="rounded p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-700 transition-colors"
                                        title="Düzenle">
                                        <PencilIcon class="h-4 w-4" />
                                    </button>
                                    <button @click="destroy(ep)"
                                        class="rounded p-1.5 text-slate-400 hover:bg-red-50 hover:text-red-600 transition-colors"
                                        title="Sil">
                                        <TrashIcon class="h-4 w-4" />
                                    </button>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- ─── Inline Test Result ───────────────────────────────────────────── -->
        <Transition enter-active-class="transition duration-200" enter-from-class="opacity-0 translate-y-1" leave-active-class="transition duration-150" leave-to-class="opacity-0">
            <div v-if="testResult && testResultId"
                class="mt-4 rounded-xl border p-4 text-sm"
                :class="testResult.success ? 'border-emerald-200 bg-emerald-50' : 'border-red-200 bg-red-50'">
                <div class="flex items-center justify-between mb-2">
                    <span class="font-semibold" :class="testResult.success ? 'text-emerald-700' : 'text-red-700'">
                        {{ testResult.success ? 'Test Başarılı' : 'Test Başarısız' }}
                        <span v-if="testResult.status_code" class="ml-2 font-normal text-slate-500">HTTP {{ testResult.status_code }}</span>
                        <span v-if="testResult.duration_ms" class="ml-2 font-normal text-slate-500">{{ testResult.duration_ms }}ms</span>
                    </span>
                    <button @click="testResult = null; testResultId = null" class="text-slate-400 hover:text-slate-600">
                        <XMarkIcon class="h-4 w-4" />
                    </button>
                </div>
                <pre v-if="testResult.response_body" class="overflow-auto rounded bg-white/70 p-2 text-xs text-slate-700 max-h-40">{{ testResult.response_body }}</pre>
                <p v-if="testResult.error" class="text-xs text-red-600">{{ testResult.error }}</p>
            </div>
        </Transition>

        <!-- ─── Create Modal ─────────────────────────────────────────────────── -->
        <Teleport to="body">
            <div v-if="showCreateModal"
                class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4"
                @click.self="showCreateModal = false">
                <div class="w-full max-w-2xl rounded-2xl bg-white shadow-2xl max-h-[90vh] overflow-y-auto">
                    <div class="flex items-center justify-between border-b border-slate-200 px-6 py-4 sticky top-0 bg-white">
                        <div class="flex items-center gap-2">
                            <PlusIcon class="h-5 w-5 text-rose-500" />
                            <h3 class="font-semibold text-slate-900">Yeni Webhook Endpoint</h3>
                        </div>
                        <button @click="showCreateModal = false" class="rounded p-1 text-slate-400 hover:text-slate-700">
                            <XMarkIcon class="h-5 w-5" />
                        </button>
                    </div>
                    <form @submit.prevent="submitCreate" class="space-y-4 p-6">
                        <EndpointFormFields :form="createForm" :available_events="available_events" :on-generate-secret="() => generateSecret(createForm)" />
                        <div class="flex justify-end gap-3 pt-2">
                            <button type="button" @click="showCreateModal = false"
                                class="rounded-lg border border-slate-300 px-4 py-2 text-sm text-slate-700 hover:bg-slate-50">
                                İptal
                            </button>
                            <button type="submit" :disabled="createForm.processing"
                                class="rounded-lg bg-rose-600 px-5 py-2 text-sm font-semibold text-white hover:bg-rose-700 disabled:opacity-50">
                                {{ createForm.processing ? 'Oluşturuluyor...' : 'Oluştur' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </Teleport>

        <!-- ─── Edit Modal ───────────────────────────────────────────────────── -->
        <Teleport to="body">
            <div v-if="showEditModal"
                class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4"
                @click.self="showEditModal = false">
                <div class="w-full max-w-2xl rounded-2xl bg-white shadow-2xl max-h-[90vh] overflow-y-auto">
                    <div class="flex items-center justify-between border-b border-slate-200 px-6 py-4 sticky top-0 bg-white">
                        <div class="flex items-center gap-2">
                            <PencilIcon class="h-5 w-5 text-slate-500" />
                            <h3 class="font-semibold text-slate-900">Endpoint Düzenle</h3>
                        </div>
                        <button @click="showEditModal = false" class="rounded p-1 text-slate-400 hover:text-slate-700">
                            <XMarkIcon class="h-5 w-5" />
                        </button>
                    </div>
                    <form @submit.prevent="submitEdit" class="space-y-4 p-6">
                        <EndpointFormFields :form="editForm" :available_events="available_events" :on-generate-secret="() => generateSecret(editForm)" />
                        <div class="flex justify-end gap-3 pt-2">
                            <button type="button" @click="showEditModal = false"
                                class="rounded-lg border border-slate-300 px-4 py-2 text-sm text-slate-700 hover:bg-slate-50">
                                İptal
                            </button>
                            <button type="submit" :disabled="editForm.processing"
                                class="rounded-lg bg-rose-600 px-5 py-2 text-sm font-semibold text-white hover:bg-rose-700 disabled:opacity-50">
                                {{ editForm.processing ? 'Kaydediliyor...' : 'Kaydet' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </Teleport>
    </AdminLayout>
</template>

<script>
import { defineComponent } from 'vue'
import { KeyIcon } from '@heroicons/vue/24/outline'

const eventLabel = (e) => ({
    'account.provisioned':    'Hesap Oluşturuldu',
    'account.suspended':      'Hesap Askıya Alındı',
    'account.unsuspended':    'Askı Kaldırıldı',
    'account.terminated':     'Hesap Silindi',
    'account.quota_exceeded': 'Kota Aşıldı',
    'ssl.issued':             'SSL Sertifikası Verildi',
    'ssl.renewed':            'SSL Sertifikası Yenilendi',
    'ssl.expiring':           'SSL Sona Eriyor',
}[e] || e)

export default defineComponent({
    components: {
        EndpointFormFields: {
            props: { form: Object, available_events: Array, onGenerateSecret: Function },
            setup(props) {
                const toggleEvent = (ev) => {
                    const idx = props.form.events.indexOf(ev)
                    if (idx === -1) props.form.events.push(ev)
                    else props.form.events.splice(idx, 1)
                }
                const selectAll = () => { props.form.events = [...props.available_events] }
                const clearAll  = () => { props.form.events = [] }
                return { toggleEvent, selectAll, clearAll, eventLabel }
            },
            template: `
                <div class="space-y-4">
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-medium text-slate-700 mb-1">Ad <span class="text-red-500">*</span></label>
                            <input v-model="form.name" type="text" maxlength="100" required
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-rose-500"
                                :class="form.errors.name ? 'border-red-400' : ''" placeholder="Production WHMCS" />
                            <p v-if="form.errors.name" class="mt-1 text-xs text-red-600">{{ form.errors.name }}</p>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-slate-700 mb-1">Durum</label>
                            <label class="inline-flex items-center gap-2 cursor-pointer select-none text-sm text-slate-700 mt-2">
                                <input v-model="form.is_active" type="checkbox"
                                    class="h-4 w-4 rounded border-slate-300 text-rose-600 focus:ring-rose-500" />
                                Aktif
                            </label>
                        </div>
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-slate-700 mb-1">Endpoint URL <span class="text-red-500">*</span></label>
                        <input v-model="form.url" type="url" maxlength="500" required
                            class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-rose-500"
                            :class="form.errors.url ? 'border-red-400' : ''" placeholder="https://whmcs.example.com/api/onox-event" />
                        <p v-if="form.errors.url" class="mt-1 text-xs text-red-600">{{ form.errors.url }}</p>
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-slate-700 mb-1">HMAC Secret <span class="text-red-500">*</span></label>
                        <div class="flex gap-2">
                            <input v-model="form.secret" type="text" maxlength="64" required
                                class="flex-1 rounded-lg border border-slate-300 px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-rose-500"
                                :class="form.errors.secret ? 'border-red-400' : ''" placeholder="min. 16 karakter" />
                            <button type="button" @click="onGenerateSecret"
                                class="inline-flex items-center gap-1 rounded-lg border border-slate-300 px-3 py-2 text-xs text-slate-600 hover:bg-slate-50">
                                Üret
                            </button>
                        </div>
                        <p class="mt-1 text-xs text-slate-400">SHA-256 HMAC ile imzalanır. WHMCS tarafı bu key ile doğrulama yapar.</p>
                        <p v-if="form.errors.secret" class="mt-1 text-xs text-red-600">{{ form.errors.secret }}</p>
                    </div>
                    <div>
                        <div class="flex items-center justify-between mb-2">
                            <label class="block text-xs font-medium text-slate-700">Tetiklenecek Eventler <span class="text-red-500">*</span></label>
                            <div class="flex gap-2">
                                <button type="button" @click="selectAll" class="text-xs text-rose-600 hover:underline">Tümünü Seç</button>
                                <button type="button" @click="clearAll" class="text-xs text-slate-400 hover:underline">Temizle</button>
                            </div>
                        </div>
                        <div class="grid grid-cols-2 gap-1.5">
                            <label v-for="ev in available_events" :key="ev"
                                class="flex items-center gap-2 cursor-pointer rounded-lg border px-3 py-2 text-sm transition-colors select-none"
                                :class="form.events.includes(ev) ? 'border-rose-300 bg-rose-50 text-rose-700' : 'border-slate-200 text-slate-600 hover:bg-slate-50'">
                                <input type="checkbox" class="sr-only" :checked="form.events.includes(ev)" @change="toggleEvent(ev)" />
                                <span class="h-3.5 w-3.5 flex-shrink-0 rounded border"
                                    :class="form.events.includes(ev) ? 'bg-rose-500 border-rose-500' : 'border-slate-300'">
                                    <svg v-if="form.events.includes(ev)" viewBox="0 0 12 12" fill="none" class="text-white">
                                        <path d="M2 6l3 3 5-5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                                    </svg>
                                </span>
                                {{ eventLabel(ev) }}
                            </label>
                        </div>
                        <p v-if="form.errors.events" class="mt-1 text-xs text-red-600">{{ form.errors.events }}</p>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-medium text-slate-700 mb-1">Yeniden Deneme Sayısı</label>
                            <input v-model.number="form.retry_count" type="number" min="0" max="10" required
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-rose-500" />
                            <p class="mt-1 text-xs text-slate-400">Backoff: 1dk → 5dk → 15dk</p>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-slate-700 mb-1">Timeout (saniye)</label>
                            <input v-model.number="form.timeout_seconds" type="number" min="5" max="120" required
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-rose-500" />
                        </div>
                    </div>
                </div>
            `,
        },
    },
})
</script>
