<script setup>
import { ref } from 'vue'
import { Head, Link } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    ArrowLeftIcon,
    LightBulbIcon,
    DocumentDuplicateIcon,
    CheckCircleIcon,
    ChartBarIcon,
    CommandLineIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    query:   { type: Object, default: () => ({}) },
    explain: { type: Object, default: () => ({ explain: [], suggestions: [], query: '' }) },
})

// ── EXPLAIN row coloring ─────────────────────────────────────────────────────
const typeColor = (t) => {
    const v = String(t || '').toLowerCase()
    if (v === 'all')            return 'bg-red-100 text-red-700 ring-1 ring-red-200'
    if (v === 'index')          return 'bg-orange-100 text-orange-700 ring-1 ring-orange-200'
    if (v === 'range')          return 'bg-yellow-100 text-yellow-700 ring-1 ring-yellow-200'
    if (['ref', 'eq_ref', 'const', 'system'].includes(v)) return 'bg-emerald-100 text-emerald-700 ring-1 ring-emerald-200'
    return 'bg-slate-100 text-slate-600 ring-1 ring-slate-200'
}
const extraColor = (extra) => {
    if (!extra) return ''
    const s = String(extra).toLowerCase()
    if (s.includes('using filesort') || s.includes('using temporary'))
        return 'bg-amber-50 text-amber-800'
    if (s.includes('using index') && !s.includes('using where'))
        return 'bg-emerald-50 text-emerald-800'
    return 'bg-slate-50 text-slate-700'
}

// ── Suggestion copy ──────────────────────────────────────────────────────────
const copiedIdx = ref(null)
const copy = async (text, idx) => {
    try {
        await navigator.clipboard.writeText(text)
        copiedIdx.value = idx
        setTimeout(() => { copiedIdx.value = null }, 1800)
    } catch {
        /* clipboard yok — ignore */
    }
}

const formatNum = (n) => Number(n ?? 0).toLocaleString('tr-TR')
const formatSec = (n) => `${Number(n ?? 0).toFixed(2)}s`
</script>

<template>
    <Head :title="`Slow Query #${query.hash}`" />
    <AdminLayout>
        <template #header>Slow Query Detayı</template>

        <div class="mb-4">
            <Link
                :href="route('admin.mysql.slow-queries.index')"
                class="inline-flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-800"
            >
                <ArrowLeftIcon class="h-4 w-4" />
                Slow Queries listesi
            </Link>
        </div>

        <!-- Top stat cards -->
        <div class="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-5">
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <p class="text-xs text-slate-500">Tekrar sayısı</p>
                <p class="mt-1 text-xl font-bold">{{ formatNum(query.count) }}</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <p class="text-xs text-slate-500">Ortalama süre</p>
                <p class="mt-1 text-xl font-bold text-amber-600">{{ formatSec(query.avg_time) }}</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <p class="text-xs text-slate-500">Maksimum</p>
                <p class="mt-1 text-xl font-bold text-red-600">{{ formatSec(query.max_time) }}</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <p class="text-xs text-slate-500">Toplam süre</p>
                <p class="mt-1 text-xl font-bold">{{ formatSec(query.total_time) }}</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <p class="text-xs text-slate-500">Satır tarama (avg)</p>
                <p class="mt-1 text-xl font-bold">{{ formatNum(query.rows_examined_avg) }}</p>
            </div>
        </div>

        <div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
            <!-- LEFT 2/3 — query body + explain -->
            <div class="space-y-6 lg:col-span-2">
                <!-- Normalized -->
                <div class="rounded-xl border border-slate-200 bg-white shadow-sm overflow-hidden">
                    <div class="flex items-center gap-2 border-b border-slate-200 px-5 py-3">
                        <CommandLineIcon class="h-5 w-5 text-slate-500" />
                        <h3 class="text-base font-semibold">Normalized Query</h3>
                        <span class="ml-auto font-mono text-xs text-slate-400">#{{ query.hash }}</span>
                    </div>
                    <pre class="overflow-x-auto bg-slate-900 px-5 py-4 font-mono text-xs leading-6 text-slate-100">{{ query.normalized }}</pre>
                </div>

                <!-- Sample -->
                <div class="rounded-xl border border-slate-200 bg-white shadow-sm overflow-hidden">
                    <div class="border-b border-slate-200 px-5 py-3">
                        <h3 class="text-base font-semibold">Örnek Çalıştırma</h3>
                    </div>
                    <pre class="overflow-x-auto px-5 py-4 font-mono text-xs leading-6 text-slate-700">{{ query.sample }}</pre>
                    <div class="border-t border-slate-100 bg-slate-50 px-5 py-2 text-xs text-slate-500">
                        İlk görülme: <span class="font-mono">{{ query.first_seen }}</span> ·
                        Son görülme: <span class="font-mono">{{ query.last_seen }}</span>
                    </div>
                </div>

                <!-- EXPLAIN -->
                <div class="rounded-xl border border-slate-200 bg-white shadow-sm overflow-hidden">
                    <div class="flex items-center gap-2 border-b border-slate-200 px-5 py-3">
                        <ChartBarIcon class="h-5 w-5 text-slate-500" />
                        <h3 class="text-base font-semibold">EXPLAIN Planı</h3>
                    </div>

                    <div v-if="!explain.explain || explain.explain.length === 0" class="px-5 py-8 text-center text-sm text-slate-500">
                        EXPLAIN sonucu yok.
                    </div>

                    <div v-else class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-slate-200 text-xs">
                            <thead class="bg-slate-50 uppercase text-slate-500">
                                <tr>
                                    <th class="px-3 py-2 text-left">id</th>
                                    <th class="px-3 py-2 text-left">select_type</th>
                                    <th class="px-3 py-2 text-left">table</th>
                                    <th class="px-3 py-2 text-left">type</th>
                                    <th class="px-3 py-2 text-left">possible_keys</th>
                                    <th class="px-3 py-2 text-left">key</th>
                                    <th class="px-3 py-2 text-left">ref</th>
                                    <th class="px-3 py-2 text-right">rows</th>
                                    <th class="px-3 py-2 text-left">Extra</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <tr v-for="(row, i) in explain.explain" :key="i" class="hover:bg-slate-50">
                                    <td class="px-3 py-2 font-mono">{{ row.id }}</td>
                                    <td class="px-3 py-2 font-mono text-slate-600">{{ row.select_type }}</td>
                                    <td class="px-3 py-2 font-mono font-semibold text-slate-800">{{ row.table }}</td>
                                    <td class="px-3 py-2">
                                        <span :class="['inline-flex rounded px-2 py-0.5 font-mono text-[10px] font-semibold uppercase', typeColor(row.type)]">
                                            {{ row.type || '—' }}
                                        </span>
                                    </td>
                                    <td class="px-3 py-2 font-mono text-slate-600">{{ row.possible_keys || '—' }}</td>
                                    <td class="px-3 py-2 font-mono">
                                        <span v-if="row.key" class="text-emerald-700">{{ row.key }}</span>
                                        <span v-else class="text-red-600">— yok</span>
                                    </td>
                                    <td class="px-3 py-2 font-mono text-slate-500">{{ row.ref || '—' }}</td>
                                    <td class="px-3 py-2 text-right font-mono">{{ formatNum(row.rows) }}</td>
                                    <td class="px-3 py-2">
                                        <span v-if="row.Extra" :class="['inline-flex rounded px-1.5 py-0.5 text-[10px]', extraColor(row.Extra)]">
                                            {{ row.Extra }}
                                        </span>
                                        <span v-else class="text-slate-400">—</span>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- RIGHT 1/3 — suggestions + meta -->
            <div class="space-y-6">
                <!-- Suggestions -->
                <div class="rounded-xl border border-yellow-200 bg-yellow-50 shadow-sm">
                    <div class="flex items-center gap-2 border-b border-yellow-200 px-5 py-3">
                        <LightBulbIcon class="h-5 w-5 text-yellow-600" />
                        <h3 class="text-base font-semibold text-yellow-900">Öneriler</h3>
                    </div>
                    <ul class="divide-y divide-yellow-100">
                        <li
                            v-for="(s, i) in (explain.suggestions || [])"
                            :key="i"
                            class="flex items-start gap-2 px-5 py-3 text-sm text-yellow-900"
                        >
                            <span class="mt-0.5 flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full bg-yellow-200 text-[10px] font-bold text-yellow-800">{{ i + 1 }}</span>
                            <div class="flex-1">
                                <p class="font-mono text-xs leading-5">{{ s }}</p>
                                <button
                                    @click="copy(s, i)"
                                    class="mt-1 inline-flex items-center gap-1 text-[10px] font-medium text-yellow-700 hover:text-yellow-900"
                                >
                                    <CheckCircleIcon v-if="copiedIdx === i" class="h-3 w-3 text-emerald-600" />
                                    <DocumentDuplicateIcon v-else class="h-3 w-3" />
                                    {{ copiedIdx === i ? 'Kopyalandı' : 'Kopyala' }}
                                </button>
                            </div>
                        </li>
                        <li v-if="!(explain.suggestions && explain.suggestions.length)" class="px-5 py-6 text-center text-sm text-yellow-700">
                            Öneri üretilemedi.
                        </li>
                    </ul>
                </div>

                <!-- Meta -->
                <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                    <h3 class="mb-3 text-base font-semibold">Veri Kapsamı</h3>
                    <dl class="space-y-2 text-sm">
                        <div class="flex justify-between">
                            <dt class="text-slate-500">Veritabanları</dt>
                            <dd class="font-mono text-slate-800">{{ (query.databases || []).join(', ') || '—' }}</dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-slate-500">Kullanıcılar</dt>
                            <dd class="font-mono text-slate-800">{{ (query.users || []).join(', ') || '—' }}</dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-slate-500">Ort. satır gönderilen</dt>
                            <dd class="font-mono text-slate-800">{{ formatNum(query.rows_sent_avg) }}</dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-slate-500">Ort. satır taranan</dt>
                            <dd class="font-mono text-slate-800">{{ formatNum(query.rows_examined_avg) }}</dd>
                        </div>
                    </dl>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
