<script setup>
import { computed, ref } from 'vue'
import { Head, Link } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    ArrowLeftIcon,
    CheckCircleIcon,
    XCircleIcon,
    ExclamationTriangleIcon,
    ClipboardDocumentIcon,
    UserIcon,
    GlobeAltIcon,
    ClockIcon,
    DocumentDuplicateIcon,
    ArrowPathIcon,
    EyeIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    log: Object,
    related: Array,
})

const formatDate = (dt) => {
    if (!dt) return '—'
    return new Date(dt).toLocaleString('tr-TR', { dateStyle: 'medium', timeStyle: 'medium' })
}

const outcomeIcon = (o) => {
    if (o === 'success') return { icon: CheckCircleIcon, class: 'text-emerald-500' }
    if (o === 'failure') return { icon: XCircleIcon, class: 'text-red-500' }
    return { icon: ExclamationTriangleIcon, class: 'text-amber-500' }
}

const outcomeBadge = (o) => {
    if (o === 'success') return 'bg-emerald-50 text-emerald-700 ring-emerald-200'
    if (o === 'failure') return 'bg-red-50 text-red-700 ring-red-200'
    return 'bg-amber-50 text-amber-700 ring-amber-200'
}

const shortTarget = (t) => {
    if (!t) return ''
    return t.split('\\').pop()
}

// Pretty-print JSON helpers — collapse desteğiyle
const safePretty = (v) => {
    if (v === null || v === undefined) return ''
    try {
        return JSON.stringify(v, null, 2)
    } catch (e) {
        return String(v)
    }
}

// Diff hesaplama — before/after flat key compare (top-level)
const diff = computed(() => {
    const b = props.log?.before
    const a = props.log?.after
    if (!b || !a || typeof b !== 'object' || typeof a !== 'object') return null

    const added = []
    const removed = []
    const changed = []
    const allKeys = new Set([...Object.keys(b), ...Object.keys(a)])

    for (const k of allKeys) {
        const inB = k in b
        const inA = k in a
        if (inB && !inA) removed.push({ key: k, value: b[k] })
        else if (!inB && inA) added.push({ key: k, value: a[k] })
        else if (JSON.stringify(b[k]) !== JSON.stringify(a[k])) changed.push({ key: k, before: b[k], after: a[k] })
    }

    return { added, removed, changed }
})

const beforePretty = computed(() => safePretty(props.log?.before))
const afterPretty = computed(() => safePretty(props.log?.after))
const metaPretty = computed(() => safePretty(props.log?.metadata))

// Highlight: kayıtla aynı key olan satırlara CSS class atamak için JSON satır parsing yerine
// güvenli yol — flat key listesi gösterip yanına eski/yeni değeri tablo halinde çıkarmak.
// Mevcut "diff" hesaplaması zaten o yapıyı veriyor.

// Replay — sadece bilgi amaçlı, alert
const showReplay = ref(false)
const replayHint = computed(() => {
    const action = props.log?.action || ''
    return `Bu kayıt "${action}" aksiyonunu tekrarlar. Tekrar oynatma yalnızca tavsiye amaçlıdır — gerçek bir reverse/replay yapılmaz. Manuel olarak ilgili admin sayfasını ziyaret ederek aksiyonu yeniden tetikleyebilirsiniz.`
})

const copyToClipboard = async (text) => {
    try {
        await navigator.clipboard.writeText(text)
    } catch (e) {
        // fallback yok — sessiz
    }
}
</script>

<template>
    <Head :title="`Audit #${log.id}`" />

    <AdminLayout>
        <template #header>
            <div class="flex items-center gap-2">
                <Link :href="route('admin.audit.index')" class="rounded p-1 hover:bg-slate-100 dark:hover:bg-slate-700">
                    <ArrowLeftIcon class="h-5 w-5 text-slate-500" />
                </Link>
                <span>Audit Kaydı #{{ log.id }}</span>
            </div>
        </template>

        <!-- Üst özet -->
        <div class="mb-4 grid grid-cols-1 gap-3 rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-4 sm:grid-cols-2 lg:grid-cols-4">
            <div>
                <div class="flex items-center gap-1 text-xs text-slate-500"><ClockIcon class="h-4 w-4" /> Zaman</div>
                <div class="mt-1 text-sm font-medium text-slate-900 dark:text-slate-100">{{ formatDate(log.created_at) }}</div>
            </div>
            <div>
                <div class="flex items-center gap-1 text-xs text-slate-500"><UserIcon class="h-4 w-4" /> Aktör</div>
                <div class="mt-1 text-sm font-medium text-slate-900 dark:text-slate-100">
                    {{ log.user_name || log.user_email || 'Sistem' }}
                </div>
                <div v-if="log.user_email && log.user_name" class="text-xs text-slate-500">{{ log.user_email }}</div>
            </div>
            <div>
                <div class="flex items-center gap-1 text-xs text-slate-500"><GlobeAltIcon class="h-4 w-4" /> IP</div>
                <div class="mt-1 text-sm font-mono text-slate-700 dark:text-slate-300">{{ log.ip_address || '—' }}</div>
            </div>
            <div>
                <div class="text-xs text-slate-500">Sonuç</div>
                <span :class="['mt-1 inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset', outcomeBadge(log.outcome)]">
                    <component :is="outcomeIcon(log.outcome).icon" class="h-3 w-3" />
                    {{ log.outcome }}
                </span>
            </div>
        </div>

        <!-- Aksiyon + Hedef -->
        <div class="mb-4 rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-4">
            <div class="grid grid-cols-1 gap-3 sm:grid-cols-3">
                <div class="sm:col-span-2">
                    <div class="text-xs uppercase text-slate-500">Aksiyon</div>
                    <div class="mt-1 inline-flex items-center gap-2">
                        <code class="rounded bg-indigo-50 dark:bg-indigo-900/30 px-2 py-1 font-mono text-sm text-indigo-700 dark:text-indigo-300">{{ log.action }}</code>
                        <button @click="copyToClipboard(log.action)" class="rounded p-1 hover:bg-slate-100 dark:hover:bg-slate-700" title="Kopyala">
                            <ClipboardDocumentIcon class="h-4 w-4 text-slate-400" />
                        </button>
                    </div>
                </div>
                <div>
                    <div class="text-xs uppercase text-slate-500">Hedef</div>
                    <div class="mt-1 text-sm font-medium text-slate-900 dark:text-slate-100">
                        <template v-if="log.target_type">
                            {{ shortTarget(log.target_type) }}<span v-if="log.target_id" class="text-slate-500">#{{ log.target_id }}</span>
                        </template>
                        <span v-else class="text-slate-400">—</span>
                    </div>
                    <div v-if="log.target_type" class="text-xs text-slate-400 break-all">{{ log.target_type }}</div>
                </div>
            </div>

            <div v-if="log.error_message" class="mt-4 rounded-lg border border-red-200 bg-red-50 p-3">
                <div class="text-xs font-semibold uppercase text-red-700">Hata mesajı</div>
                <pre class="mt-1 whitespace-pre-wrap break-words text-sm text-red-900">{{ log.error_message }}</pre>
            </div>

            <div class="mt-3 flex gap-2">
                <button
                    @click="showReplay = !showReplay"
                    class="inline-flex items-center gap-1 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 px-3 py-1.5 text-xs font-medium text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700"
                >
                    <ArrowPathIcon class="h-3.5 w-3.5" /> Replay (tavsiye)
                </button>
            </div>
            <div v-if="showReplay" class="mt-3 rounded-lg border border-amber-200 bg-amber-50 p-3 text-xs text-amber-900">
                {{ replayHint }}
            </div>
        </div>

        <!-- Metadata -->
        <div v-if="log.metadata" class="mb-4 rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-4">
            <div class="mb-2 flex items-center justify-between">
                <div class="text-xs font-semibold uppercase text-slate-500">Metadata</div>
                <button @click="copyToClipboard(metaPretty)" class="rounded p-1 hover:bg-slate-100 dark:hover:bg-slate-700">
                    <DocumentDuplicateIcon class="h-4 w-4 text-slate-400" />
                </button>
            </div>
            <pre class="overflow-auto rounded bg-slate-50 dark:bg-slate-900 p-3 text-xs text-slate-700 dark:text-slate-200">{{ metaPretty }}</pre>
        </div>

        <!-- Before / After -->
        <div v-if="log.before || log.after" class="mb-4 grid grid-cols-1 gap-3 lg:grid-cols-2">
            <div class="rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-4">
                <div class="mb-2 flex items-center justify-between">
                    <div class="text-xs font-semibold uppercase text-slate-500">Önce (before)</div>
                    <button v-if="log.before" @click="copyToClipboard(beforePretty)" class="rounded p-1 hover:bg-slate-100 dark:hover:bg-slate-700">
                        <DocumentDuplicateIcon class="h-4 w-4 text-slate-400" />
                    </button>
                </div>
                <pre v-if="log.before" class="max-h-96 overflow-auto rounded bg-slate-50 dark:bg-slate-900 p-3 text-xs text-slate-700 dark:text-slate-200">{{ beforePretty }}</pre>
                <div v-else class="text-xs text-slate-400">veri yok</div>
            </div>

            <div class="rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-4">
                <div class="mb-2 flex items-center justify-between">
                    <div class="text-xs font-semibold uppercase text-slate-500">Sonra (after)</div>
                    <button v-if="log.after" @click="copyToClipboard(afterPretty)" class="rounded p-1 hover:bg-slate-100 dark:hover:bg-slate-700">
                        <DocumentDuplicateIcon class="h-4 w-4 text-slate-400" />
                    </button>
                </div>
                <pre v-if="log.after" class="max-h-96 overflow-auto rounded bg-slate-50 dark:bg-slate-900 p-3 text-xs text-slate-700 dark:text-slate-200">{{ afterPretty }}</pre>
                <div v-else class="text-xs text-slate-400">veri yok</div>
            </div>
        </div>

        <!-- Diff özeti -->
        <div v-if="diff && (diff.added.length || diff.removed.length || diff.changed.length)" class="mb-4 rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-4">
            <div class="mb-3 text-xs font-semibold uppercase text-slate-500">Değişiklik Özeti</div>

            <div v-if="diff.changed.length" class="mb-3">
                <div class="mb-1 text-xs font-semibold text-amber-700">Değişti ({{ diff.changed.length }})</div>
                <table class="min-w-full text-xs">
                    <thead class="text-slate-500"><tr><th class="text-left py-1 pr-3">Alan</th><th class="text-left py-1 pr-3">Önce</th><th class="text-left py-1">Sonra</th></tr></thead>
                    <tbody>
                        <tr v-for="row in diff.changed" :key="row.key" class="border-t border-slate-100 dark:border-slate-700">
                            <td class="py-1 pr-3 font-mono text-slate-700 dark:text-slate-300">{{ row.key }}</td>
                            <td class="py-1 pr-3 font-mono text-red-600 break-all">{{ JSON.stringify(row.before) }}</td>
                            <td class="py-1 font-mono text-emerald-600 break-all">{{ JSON.stringify(row.after) }}</td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div v-if="diff.added.length" class="mb-3">
                <div class="mb-1 text-xs font-semibold text-emerald-700">Eklendi ({{ diff.added.length }})</div>
                <ul class="space-y-0.5 text-xs">
                    <li v-for="row in diff.added" :key="row.key" class="font-mono">
                        <span class="text-emerald-600">+ {{ row.key }}</span>: {{ JSON.stringify(row.value) }}
                    </li>
                </ul>
            </div>

            <div v-if="diff.removed.length">
                <div class="mb-1 text-xs font-semibold text-red-700">Silindi ({{ diff.removed.length }})</div>
                <ul class="space-y-0.5 text-xs">
                    <li v-for="row in diff.removed" :key="row.key" class="font-mono">
                        <span class="text-red-600">- {{ row.key }}</span>: {{ JSON.stringify(row.value) }}
                    </li>
                </ul>
            </div>
        </div>

        <!-- Related -->
        <div v-if="related && related.length" class="rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-4">
            <div class="mb-2 text-xs font-semibold uppercase text-slate-500">
                Aynı kullanıcı ±5dk içinde ({{ related.length }})
            </div>
            <table class="min-w-full text-xs">
                <thead class="text-slate-500">
                    <tr>
                        <th class="text-left py-1 pr-3">Zaman</th>
                        <th class="text-left py-1 pr-3">Aksiyon</th>
                        <th class="text-left py-1 pr-3">Hedef</th>
                        <th class="text-left py-1 pr-3">Sonuç</th>
                        <th class="py-1"></th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="r in related" :key="r.id" class="border-t border-slate-100 dark:border-slate-700">
                        <td class="py-1 pr-3 text-slate-500">{{ formatDate(r.created_at) }}</td>
                        <td class="py-1 pr-3 font-mono text-indigo-700 dark:text-indigo-300">{{ r.action }}</td>
                        <td class="py-1 pr-3 text-slate-600 dark:text-slate-300">
                            <template v-if="r.target_type">{{ shortTarget(r.target_type) }}<span v-if="r.target_id">#{{ r.target_id }}</span></template>
                            <span v-else class="text-slate-400">—</span>
                        </td>
                        <td class="py-1 pr-3">
                            <span :class="['inline-flex items-center gap-1 rounded-full px-2 py-0.5 ring-1 ring-inset', outcomeBadge(r.outcome)]">
                                <component :is="outcomeIcon(r.outcome).icon" class="h-3 w-3" />
                                {{ r.outcome }}
                            </span>
                        </td>
                        <td class="py-1">
                            <Link :href="route('admin.audit.show', r.id)" class="inline-flex items-center gap-1 text-indigo-600 hover:underline">
                                <EyeIcon class="h-3.5 w-3.5" /> aç
                            </Link>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </AdminLayout>
</template>
