<script setup>
import { ref, computed, watch } from 'vue'
import { Head, Link, router, useForm } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    ClockIcon,
    MagnifyingGlassIcon,
    BoltIcon,
    CircleStackIcon,
    ServerIcon,
    ArrowsUpDownIcon,
    ChevronUpIcon,
    ChevronDownIcon,
    EyeIcon,
    TrashIcon,
    FunnelIcon,
    Cog6ToothIcon,
    ExclamationTriangleIcon,
    PlayIcon,
    BeakerIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    queries:    { type: Array,  default: () => [] },
    filters:    { type: Object, default: () => ({}) },
    aggregates: { type: Object, default: () => ({}) },
    options:    { type: Object, default: () => ({ databases: [], users: [] }) },
    settings:   { type: Object, default: () => ({}) },
})

// ── Filter state ─────────────────────────────────────────────────────────────
const filterRange      = ref(props.filters.range || '24h')
const filterDatabase   = ref(props.filters.database || '')
const filterUser       = ref(props.filters.user || '')
const filterMinCount   = ref(Number(props.filters.min_count || 0))
const filterMinAvgTime = ref(Number(props.filters.min_avg_time || 0))
const sortKey          = ref(props.filters.sort || 'total_time')
const sortDir          = ref(props.filters.dir || 'desc')

const ranges = [
    { key: '24h', label: 'Son 24 saat' },
    { key: '7d',  label: 'Son 7 gün' },
    { key: '30d', label: 'Son 30 gün' },
]

const reload = () => {
    router.get(route('admin.mysql.slow-queries.index'), {
        range:        filterRange.value,
        database:     filterDatabase.value,
        user:         filterUser.value,
        min_count:    filterMinCount.value,
        min_avg_time: filterMinAvgTime.value,
        sort:         sortKey.value,
        dir:          sortDir.value,
    }, { preserveScroll: true, preserveState: false, replace: true })
}

const setSort = (key) => {
    if (sortKey.value === key) {
        sortDir.value = sortDir.value === 'desc' ? 'asc' : 'desc'
    } else {
        sortKey.value = key
        sortDir.value = 'desc'
    }
    reload()
}

const sortIcon = (key) => {
    if (sortKey.value !== key) return ArrowsUpDownIcon
    return sortDir.value === 'desc' ? ChevronDownIcon : ChevronUpIcon
}

// ── Formatters ───────────────────────────────────────────────────────────────
const formatNum = (n) => Number(n ?? 0).toLocaleString('tr-TR')
const formatSec = (n) => `${Number(n ?? 0).toFixed(2)}s`
const formatBytes = (b) => {
    const n = Number(b ?? 0)
    if (n >= 1024 ** 3) return (n / 1024 ** 3).toFixed(2) + ' GB'
    if (n >= 1024 ** 2) return (n / 1024 ** 2).toFixed(1) + ' MB'
    if (n >= 1024)      return (n / 1024).toFixed(1) + ' KB'
    return n + ' B'
}
const truncate = (s, n = 90) => {
    if (!s) return ''
    return s.length > n ? s.slice(0, n) + '…' : s
}
const timeBadge = (t) => {
    const v = Number(t ?? 0)
    if (v >= 10) return 'bg-red-100 text-red-700 ring-1 ring-red-200'
    if (v >= 5)  return 'bg-orange-100 text-orange-700 ring-1 ring-orange-200'
    return 'bg-amber-100 text-amber-700 ring-1 ring-amber-200'
}

// ── Clear log ────────────────────────────────────────────────────────────────
const clearLog = async () => {
    const ok = await ask({
        title: 'Slow query log temizlensin mi?',
        message: 'Bu işlem slow_query.log dosyasını sıfırlar (truncate). Mevcut yavaş sorgu kayıtları silinir, geri alınamaz.',
        variant: 'danger',
        confirmText: 'Evet, temizle',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('admin.mysql.slow-queries.clear-log'), { confirm: 'clear-now' }, {
        preserveScroll: true,
    })
}

// ── Inline long_query_time ───────────────────────────────────────────────────
const settingsForm = useForm({
    long_query_time: Number(props.settings.long_query_time ?? 2),
    slow_query_log: String(props.settings.slow_query_log ?? '1'),
    log_queries_not_using_indexes: String(props.settings.log_queries_not_using_indexes ?? '0'),
})

const saveSettings = () => {
    settingsForm.patch(route('admin.mysql.slow-queries.settings.update'), {
        preserveScroll: true,
    })
}
</script>

<template>
    <Head title="MySQL Slow Query Analyzer" />
    <AdminLayout>
        <template #header>MySQL Slow Query Analyzer</template>

        <!-- Top action bar -->
        <div class="mb-6 flex flex-wrap items-center justify-between gap-3">
            <div class="flex items-center gap-3">
                <Link
                    :href="route('admin.mysql.index')"
                    class="text-sm text-slate-500 hover:text-slate-800"
                >← MySQL Yönetimi</Link>
                <Link
                    :href="route('admin.mysql.slow-queries.running')"
                    class="inline-flex items-center gap-1.5 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-1.5 text-sm font-medium text-emerald-700 hover:bg-emerald-100"
                >
                    <PlayIcon class="h-4 w-4" />
                    Canlı Sorgular
                </Link>
            </div>
            <button
                @click="clearLog"
                class="inline-flex items-center gap-1.5 rounded-lg border border-red-200 bg-red-50 px-3 py-1.5 text-sm font-medium text-red-700 hover:bg-red-100"
            >
                <TrashIcon class="h-4 w-4" />
                Slow Log Temizle
            </button>
        </div>

        <!-- Stat cards -->
        <div class="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-4">
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div class="flex items-start justify-between">
                    <div>
                        <p class="text-xs font-medium text-slate-500">24 saat içinde yavaş sorgu</p>
                        <p class="mt-1 text-2xl font-bold text-slate-900">{{ formatNum(aggregates.total_24h) }}</p>
                        <p class="mt-0.5 text-[10px] text-slate-400">{{ aggregates.distinct_queries }} farklı pattern</p>
                    </div>
                    <ClockIcon class="h-7 w-7 text-rose-400" />
                </div>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div class="flex items-start justify-between">
                    <div>
                        <p class="text-xs font-medium text-slate-500">En yavaş tek sorgu</p>
                        <p class="mt-1 text-2xl font-bold text-slate-900">{{ formatSec(aggregates.slowest_seconds) }}</p>
                    </div>
                    <BoltIcon class="h-7 w-7 text-amber-400" />
                </div>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div class="flex items-start justify-between">
                    <div>
                        <p class="text-xs font-medium text-slate-500">En yoğun veritabanı</p>
                        <p class="mt-1 truncate text-lg font-bold text-slate-900" :title="aggregates.busiest_database">
                            {{ aggregates.busiest_database || '—' }}
                        </p>
                    </div>
                    <CircleStackIcon class="h-7 w-7 text-indigo-400" />
                </div>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div class="flex items-start justify-between">
                    <div>
                        <p class="text-xs font-medium text-slate-500">Slow log dosyası</p>
                        <p class="mt-1 text-2xl font-bold text-slate-900">{{ formatBytes(aggregates.log_size_bytes) }}</p>
                        <p class="mt-0.5 truncate text-[10px] font-mono text-slate-400" :title="aggregates.log_path">
                            {{ aggregates.log_path || '—' }}
                        </p>
                    </div>
                    <ServerIcon class="h-7 w-7 text-sky-400" />
                </div>
            </div>
        </div>

        <!-- Slow log disabled warning -->
        <div v-if="!aggregates.log_enabled" class="mb-6 flex items-start gap-3 rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
            <ExclamationTriangleIcon class="mt-0.5 h-5 w-5 flex-shrink-0 text-amber-500" />
            <div>
                <strong>Slow query log devre dışı.</strong> Aşağıdan etkinleştirip
                <code class="rounded bg-amber-100 px-1 font-mono text-xs">long_query_time</code> değerini ayarlayın.
            </div>
        </div>

        <!-- Filter bar -->
        <div class="mb-4 rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
            <div class="mb-3 flex items-center gap-2">
                <FunnelIcon class="h-4 w-4 text-slate-400" />
                <span class="text-sm font-medium text-slate-700">Filtreler</span>
            </div>
            <div class="flex flex-wrap items-end gap-4">
                <!-- Range pills -->
                <div>
                    <label class="mb-1 block text-xs font-medium text-slate-500">Zaman aralığı</label>
                    <div class="flex rounded-lg border border-slate-200 p-0.5">
                        <button
                            v-for="r in ranges" :key="r.key"
                            @click="filterRange = r.key; reload()"
                            :class="['rounded-md px-3 py-1 text-xs font-medium transition',
                                filterRange === r.key
                                    ? 'bg-rose-600 text-white shadow'
                                    : 'text-slate-600 hover:bg-slate-50']"
                        >{{ r.label }}</button>
                    </div>
                </div>

                <!-- DB filter -->
                <div>
                    <label class="mb-1 block text-xs font-medium text-slate-500">Veritabanı</label>
                    <select
                        v-model="filterDatabase"
                        @change="reload"
                        class="rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-sm"
                    >
                        <option value="">Tümü</option>
                        <option v-for="db in options.databases" :key="db" :value="db">{{ db }}</option>
                    </select>
                </div>

                <!-- User filter -->
                <div>
                    <label class="mb-1 block text-xs font-medium text-slate-500">Kullanıcı</label>
                    <select
                        v-model="filterUser"
                        @change="reload"
                        class="rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-sm"
                    >
                        <option value="">Tümü</option>
                        <option v-for="u in options.users" :key="u" :value="u">{{ u }}</option>
                    </select>
                </div>

                <!-- min_count -->
                <div class="flex-1 min-w-[180px]">
                    <label class="mb-1 flex items-center justify-between text-xs font-medium text-slate-500">
                        <span>Min. tekrar sayısı</span>
                        <span class="font-mono text-slate-700">{{ filterMinCount }}</span>
                    </label>
                    <input
                        v-model.number="filterMinCount"
                        @change="reload"
                        type="range" min="0" max="2000" step="10"
                        class="w-full accent-rose-600"
                    />
                </div>

                <!-- min_avg_time -->
                <div class="flex-1 min-w-[180px]">
                    <label class="mb-1 flex items-center justify-between text-xs font-medium text-slate-500">
                        <span>Min. ortalama süre (s)</span>
                        <span class="font-mono text-slate-700">{{ filterMinAvgTime.toFixed(1) }}s</span>
                    </label>
                    <input
                        v-model.number="filterMinAvgTime"
                        @change="reload"
                        type="range" min="0" max="20" step="0.5"
                        class="w-full accent-rose-600"
                    />
                </div>
            </div>
        </div>

        <!-- Settings inline panel -->
        <div class="mb-6 rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
            <div class="mb-3 flex items-center gap-2">
                <Cog6ToothIcon class="h-4 w-4 text-slate-400" />
                <span class="text-sm font-medium text-slate-700">Slow Query Ayarları</span>
            </div>
            <form @submit.prevent="saveSettings" class="flex flex-wrap items-end gap-4">
                <div>
                    <label class="mb-1 block text-xs font-medium text-slate-600">long_query_time (saniye)</label>
                    <input
                        v-model.number="settingsForm.long_query_time"
                        type="number" step="0.1" min="0" max="3600"
                        class="w-32 rounded-lg border border-slate-300 px-3 py-1.5 font-mono text-sm"
                    />
                </div>
                <div>
                    <label class="mb-1 block text-xs font-medium text-slate-600">slow_query_log</label>
                    <select
                        v-model="settingsForm.slow_query_log"
                        class="rounded-lg border border-slate-300 px-3 py-1.5 text-sm"
                    >
                        <option value="1">Açık</option>
                        <option value="0">Kapalı</option>
                    </select>
                </div>
                <div>
                    <label class="mb-1 block text-xs font-medium text-slate-600">Index'siz sorguları da kaydet</label>
                    <select
                        v-model="settingsForm.log_queries_not_using_indexes"
                        class="rounded-lg border border-slate-300 px-3 py-1.5 text-sm"
                    >
                        <option value="0">Hayır</option>
                        <option value="1">Evet</option>
                    </select>
                </div>
                <button
                    type="submit"
                    :disabled="settingsForm.processing"
                    class="inline-flex items-center gap-2 rounded-lg bg-rose-600 px-4 py-1.5 text-sm font-semibold text-white hover:bg-rose-700 disabled:opacity-50"
                >
                    Kaydet
                </button>
                <p class="text-xs text-slate-500">Değişiklikler MySQL restart sonrası geçerli olur.</p>
            </form>
        </div>

        <!-- Queries table -->
        <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 flex items-center justify-between">
                <h3 class="text-base font-semibold flex items-center gap-2">
                    <MagnifyingGlassIcon class="h-5 w-5 text-slate-500" />
                    Yavaş Sorgular Sıralaması
                </h3>
                <span class="text-xs text-slate-500">{{ queries.length }} sorgu</span>
            </div>

            <div v-if="queries.length === 0" class="px-5 py-16 text-center text-sm text-slate-500">
                Filtrelere uyan yavaş sorgu yok.
            </div>

            <div v-else class="overflow-x-auto">
                <table class="min-w-full divide-y divide-slate-200 text-sm">
                    <thead class="bg-slate-50 text-xs uppercase text-slate-500">
                        <tr>
                            <th class="w-12 px-4 py-2 text-left">#</th>
                            <th class="px-4 py-2 text-left">Normalized Sorgu</th>
                            <th class="px-4 py-2 text-right">
                                <button @click="setSort('count')" class="inline-flex items-center gap-1 hover:text-slate-800">
                                    Tekrar <component :is="sortIcon('count')" class="h-3 w-3" />
                                </button>
                            </th>
                            <th class="px-4 py-2 text-right">
                                <button @click="setSort('avg_time')" class="inline-flex items-center gap-1 hover:text-slate-800">
                                    Ort. Süre <component :is="sortIcon('avg_time')" class="h-3 w-3" />
                                </button>
                            </th>
                            <th class="px-4 py-2 text-right">
                                <button @click="setSort('max_time')" class="inline-flex items-center gap-1 hover:text-slate-800">
                                    Maks. <component :is="sortIcon('max_time')" class="h-3 w-3" />
                                </button>
                            </th>
                            <th class="px-4 py-2 text-right">
                                <button @click="setSort('total_time')" class="inline-flex items-center gap-1 hover:text-slate-800">
                                    Toplam <component :is="sortIcon('total_time')" class="h-3 w-3" />
                                </button>
                            </th>
                            <th class="px-4 py-2 text-left">DB / Kullanıcı</th>
                            <th class="px-4 py-2 text-left">İşlem</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                        <tr v-for="(q, i) in queries" :key="q.hash" class="hover:bg-slate-50 align-top">
                            <td class="px-4 py-3 text-xs font-bold text-slate-400">{{ i + 1 }}</td>
                            <td class="px-4 py-3 max-w-xl">
                                <div :title="q.normalized" class="font-mono text-xs text-slate-700">
                                    {{ truncate(q.normalized, 110) }}
                                </div>
                                <div class="mt-1 flex items-center gap-2 text-[10px] text-slate-400">
                                    <span class="font-mono">#{{ q.hash }}</span>
                                    <span>·</span>
                                    <span>{{ formatNum(q.rows_examined_avg) }} satır taranıyor</span>
                                </div>
                            </td>
                            <td class="px-4 py-3 text-right font-mono text-xs">{{ formatNum(q.count) }}</td>
                            <td class="px-4 py-3 text-right">
                                <span :class="['inline-flex rounded px-2 py-0.5 text-xs font-semibold font-mono', timeBadge(q.avg_time)]">
                                    {{ formatSec(q.avg_time) }}
                                </span>
                            </td>
                            <td class="px-4 py-3 text-right">
                                <span :class="['inline-flex rounded px-2 py-0.5 text-xs font-semibold font-mono', timeBadge(q.max_time)]">
                                    {{ formatSec(q.max_time) }}
                                </span>
                            </td>
                            <td class="px-4 py-3 text-right font-mono text-xs text-slate-700">{{ formatSec(q.total_time) }}</td>
                            <td class="px-4 py-3">
                                <div class="flex flex-col gap-0.5 text-[11px]">
                                    <span class="font-mono text-slate-700">{{ (q.databases || []).join(', ') }}</span>
                                    <span class="font-mono text-slate-400">{{ (q.users || []).join(', ') }}</span>
                                </div>
                            </td>
                            <td class="px-4 py-3">
                                <Link
                                    :href="route('admin.mysql.slow-queries.show', q.hash)"
                                    class="inline-flex items-center gap-1 rounded-lg border border-blue-200 bg-blue-50 px-2 py-1 text-xs text-blue-700 hover:bg-blue-100"
                                >
                                    <EyeIcon class="h-3.5 w-3.5" />
                                    Detay
                                </Link>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </AdminLayout>
</template>
