<script setup>
import { ref, computed, watch } from 'vue'
import { Head, router } from '@inertiajs/vue3'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import EmptyState from '@/Components/EmptyState.vue'
import {
    DocumentTextIcon,
    ExclamationTriangleIcon,
    ExclamationCircleIcon,
    InformationCircleIcon,
    XCircleIcon,
    FunnelIcon,
    GlobeAltIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    domain:            { type: String, default: null },
    available_domains: { type: Array,  default: () => [] },
    log_file:          { type: String, default: null },
    lines_scanned:     { type: Number, default: 0 },
    by_severity:       { type: Object, default: () => ({ critical: 0, error: 0, warn: 0, notice: 0 }) },
    grouped:           { type: Array,  default: () => [] },
    logs:              { type: Array,  default: () => [] },
    error:             { type: String, default: null },
})

const selectedDomain = ref(props.domain)
watch(selectedDomain, () => {
    router.get(route('customer.stats.errors'), { domain: selectedDomain.value }, { preserveState: false, replace: true })
})

// ─── Severity filter ─────────────────────────────────────────────────────────
const levelFilter = ref('all')
const totalCount = computed(() => (props.logs || []).length)

const filtered = computed(() => {
    if (levelFilter.value === 'all') return props.logs
    return props.logs.filter(l => l.level === levelFilter.value)
})

// ─── Visual helpers ──────────────────────────────────────────────────────────
const SEVERITY_META = {
    critical: { badge: 'bg-rose-100 text-rose-800', dot: 'bg-rose-500',   icon: XCircleIcon,             label: 'Critical' },
    error:    { badge: 'bg-red-100 text-red-700',   dot: 'bg-red-500',    icon: ExclamationCircleIcon,   label: 'Error' },
    warn:     { badge: 'bg-amber-100 text-amber-700', dot: 'bg-amber-500',icon: ExclamationTriangleIcon, label: 'Warn' },
    notice:   { badge: 'bg-sky-100 text-sky-700',   dot: 'bg-sky-400',    icon: InformationCircleIcon,   label: 'Notice' },
    info:     { badge: 'bg-slate-100 text-slate-600', dot: 'bg-slate-400',icon: InformationCircleIcon,   label: 'Info' },
}

const meta = (level) => SEVERITY_META[level] ?? SEVERITY_META.info

// HTTP 500 tooltip / debug suggestions
const debugHint = (msg) => {
    if (!msg) return null
    const m = msg.toLowerCase()
    if (m.includes('500') || m.includes('internal server error')) {
        return 'HTTP 500 → Genelde PHP fatal error. Site kök dizinindeki debug.log veya error_log dosyasını kontrol edin.'
    }
    if (m.includes('memory') || m.includes('allowed memory size')) {
        return 'PHP bellek limiti aşıldı. PHP Manager üzerinden memory_limit ayarını yükseltin.'
    }
    if (m.includes('permission denied') || m.includes('cannot access')) {
        return 'Dosya izni hatası. Public_html altındaki dosyaların 644 / 755 izniyle olduğundan emin olun.'
    }
    if (m.includes('mod_security') || m.includes('modsecurity')) {
        return 'ModSecurity tetiklendi. Firewall sayfasından detaylı log + whitelist seçeneklerine bakın.'
    }
    return null
}
</script>

<template>
    <Head title="Hata Logları" />
    <CustomerLayout>
        <template #header>Hata Logları</template>

        <!-- Filter bar -->
        <div class="mb-5 flex flex-wrap items-center gap-2">
            <FunnelIcon class="h-4 w-4 text-slate-400" />
            <select
                v-model="selectedDomain"
                :disabled="!available_domains.length"
                class="rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 disabled:bg-slate-100 disabled:text-slate-400"
            >
                <option v-if="!available_domains.length" value="">Domain yok</option>
                <option v-for="d in available_domains" :key="d.value" :value="d.value">{{ d.label }}</option>
            </select>
            <div class="flex gap-1">
                <button
                    @click="levelFilter = 'all'"
                    :class="[
                        'rounded px-3 py-1.5 text-xs font-medium transition-colors',
                        levelFilter === 'all' ? 'bg-slate-800 text-white' : 'bg-white border border-slate-200 text-slate-600',
                    ]"
                >Hepsi ({{ totalCount }})</button>
                <button
                    v-for="lvl in ['critical', 'error', 'warn', 'notice']"
                    :key="lvl"
                    @click="levelFilter = lvl"
                    :class="[
                        'rounded px-3 py-1.5 text-xs font-medium transition-colors capitalize',
                        levelFilter === lvl ? meta(lvl).badge + ' ring-1 ring-current' : 'bg-white border border-slate-200 text-slate-600',
                    ]"
                >
                    {{ meta(lvl).label }} ({{ by_severity[lvl] ?? 0 }})
                </button>
            </div>

            <span v-if="log_file" class="ml-auto truncate font-mono text-[10px] text-slate-400" :title="log_file">
                {{ log_file }}
            </span>
        </div>

        <!-- No domain -->
        <EmptyState
            v-if="!available_domains.length"
            :icon="GlobeAltIcon"
            title="Henüz domain yok"
            description="Error log için önce bir alan adı ekleyin."
            action-label="Alan Adı Ekle"
            :action-href="route('customer.domains.index')"
        />

        <!-- Error -->
        <div
            v-else-if="error"
            class="mb-4 flex items-start gap-3 rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900"
        >
            <InformationCircleIcon class="h-5 w-5 flex-shrink-0 text-amber-600" />
            <div>
                <p class="font-medium">Error log şu an okunamadı</p>
                <p class="mt-1 text-xs">{{ error }}</p>
            </div>
        </div>

        <!-- Log file missing -->
        <EmptyState
            v-else-if="!log_file && lines_scanned === 0"
            :icon="DocumentTextIcon"
            title="Bu domain için henüz hata yok"
            description="Apache/Nginx error log dosyası bulunamadı. Bu iyi haber — sitenizde yakın zamanda hata oluşmamış demektir."
        />

        <template v-else>
            <!-- Severity summary cards -->
            <div class="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
                <div
                    v-for="lvl in ['critical', 'error', 'warn', 'notice']"
                    :key="lvl"
                    class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm"
                >
                    <div class="flex items-center justify-between mb-1">
                        <component :is="meta(lvl).icon" class="h-5 w-5" :class="meta(lvl).dot.replace('bg-', 'text-')" />
                        <span class="text-[10px] uppercase tracking-wide text-slate-400 capitalize">
                            {{ meta(lvl).label }}
                        </span>
                    </div>
                    <div class="text-2xl font-bold text-slate-900">{{ (by_severity[lvl] ?? 0).toLocaleString('tr-TR') }}</div>
                    <div class="text-xs text-slate-500">{{ lines_scanned.toLocaleString('tr-TR') }} satırda</div>
                </div>
            </div>

            <!-- Grouped (signature) errors -->
            <div v-if="grouped.length" class="mb-6 rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <h3 class="mb-3 text-sm font-semibold text-slate-700">En Çok Tekrar Eden Hatalar</h3>
                <div class="space-y-2">
                    <div
                        v-for="(g, i) in grouped.slice(0, 10)"
                        :key="i"
                        class="rounded-lg border border-slate-100 p-3 hover:bg-slate-50"
                    >
                        <div class="flex items-start justify-between gap-3">
                            <div class="flex items-start gap-2 min-w-0 flex-1">
                                <span :class="['mt-1 inline-block h-2 w-2 flex-shrink-0 rounded-full', meta(g.severity).dot]"></span>
                                <div class="min-w-0 flex-1">
                                    <p class="break-words font-mono text-xs text-slate-800">{{ g.signature }}</p>
                                    <p class="mt-0.5 text-[10px] text-slate-500">
                                        İlk: <span class="font-mono">{{ g.first_seen }}</span>
                                        <span v-if="g.last_seen && g.last_seen !== g.first_seen"> · Son: <span class="font-mono">{{ g.last_seen }}</span></span>
                                        <span v-if="g.sample_ip"> · IP: <span class="font-mono">{{ g.sample_ip }}</span></span>
                                    </p>
                                    <p v-if="debugHint(g.signature)" class="mt-1 text-[10px] text-indigo-600">
                                        ↳ {{ debugHint(g.signature) }}
                                    </p>
                                </div>
                            </div>
                            <span class="flex-shrink-0 rounded-full bg-slate-100 px-2 py-0.5 text-xs font-semibold text-slate-700">
                                ×{{ g.count }}
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Recent stream -->
            <div v-if="!filtered.length" class="rounded-xl border border-dashed border-slate-300 bg-white p-12 text-center">
                <DocumentTextIcon class="mx-auto h-14 w-14 text-slate-300" />
                <h3 class="mt-3 text-lg font-semibold">Bu seviyede log yok</h3>
                <p class="mt-1 text-xs text-slate-500">Farklı bir filtre veya tüm logları seçmeyi deneyin.</p>
            </div>

            <div v-else class="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm">
                <table class="min-w-full divide-y divide-slate-200">
                    <thead class="bg-slate-50">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-slate-500">Zaman</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-slate-500">Seviye</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-slate-500">İstemci IP</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-slate-500">Mesaj</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                        <tr v-for="(l, idx) in filtered" :key="idx" class="hover:bg-slate-50">
                            <td class="whitespace-nowrap px-4 py-2 font-mono text-xs text-slate-500">{{ l.timestamp }}</td>
                            <td class="px-4 py-2">
                                <span :class="['inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs font-semibold uppercase', meta(l.level).badge]">
                                    <component :is="meta(l.level).icon" class="h-3 w-3" />
                                    {{ meta(l.level).label }}
                                </span>
                            </td>
                            <td class="px-4 py-2 font-mono text-xs text-slate-600">{{ l.client || l.client_ip || '—' }}</td>
                            <td class="px-4 py-2">
                                <p class="font-mono text-xs text-slate-800">{{ l.message }}</p>
                                <p v-if="debugHint(l.message)" class="mt-0.5 text-[10px] text-indigo-600">↳ {{ debugHint(l.message) }}</p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </template>
    </CustomerLayout>
</template>
