<script setup>
import { computed } from 'vue'
import { Head, Link } from '@inertiajs/vue3'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import {
    ChartBarIcon,
    EyeIcon,
    CpuChipIcon,
    ExclamationTriangleIcon,
    InformationCircleIcon,
    ArrowTrendingUpIcon,
    CircleStackIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    summary: {
        type: Object,
        default: () => ({
            bandwidth_gb_today: 0,
            bandwidth_gb_mtd: 0,
            cpu_avg_last_hour: 0,
            cpu_limit_percent: null,
            memory_max_last_hour_mb: 0,
            memory_limit_mb: null,
            processes_now: 0,
            visitors_today: null,
            errors_24h: null,
            disk_percent: 0,
            disk_used_bytes: 0,
            disk_quota_bytes: 0,
        }),
    },
    hourly: { type: Array, default: () => [] },
    primary_domain: { type: String, default: null },
    has_domains: { type: Boolean, default: false },
    package: { type: Object, default: null },
    limits: { type: Object, default: () => ({}) },
})

// ─── Formatters ─────────────────────────────────────────────────────────────
const formatBytes = (bytes) => {
    if (!bytes || bytes === 0) return '0 B'
    const units = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(1024))
    return `${(bytes / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 2)} ${units[Math.min(i, 4)]}`
}

const fmtNumber = (n) => {
    if (n === null || n === undefined) return '—'
    return new Intl.NumberFormat('tr-TR').format(n)
}

// ─── Sparkline ──────────────────────────────────────────────────────────────
const sparklinePath = computed(() => {
    const data = props.hourly
    if (!data.length) return ''
    const max = Math.max(...data.map(d => d.cpu), 1)
    const w = 240
    const h = 48
    const step = data.length > 1 ? w / (data.length - 1) : 0
    return data.map((d, i) => {
        const x = (i * step).toFixed(1)
        const y = (h - (d.cpu / max) * h).toFixed(1)
        return `${i === 0 ? 'M' : 'L'}${x},${y}`
    }).join(' ')
})

const sparklineLastValue = computed(() => {
    const last = props.hourly[props.hourly.length - 1]
    return last ? last.cpu : 0
})

// ─── CPU usage colour ───────────────────────────────────────────────────────
const cpuPctClass = computed(() => {
    const limit = props.summary.cpu_limit_percent || 100
    const used = props.summary.cpu_avg_last_hour
    const ratio = limit > 0 ? (used / limit) : 0
    if (ratio >= 0.9) return 'text-red-600'
    if (ratio >= 0.7) return 'text-amber-600'
    return 'text-emerald-600'
})

const memoryPctClass = computed(() => {
    const limit = props.summary.memory_limit_mb || 0
    const used = props.summary.memory_max_last_hour_mb
    if (!limit) return 'text-slate-700'
    const ratio = used / limit
    if (ratio >= 0.9) return 'text-red-600'
    if (ratio >= 0.7) return 'text-amber-600'
    return 'text-emerald-600'
})

const diskPctClass = computed(() => {
    const p = props.summary.disk_percent
    if (p >= 90) return 'text-red-600'
    if (p >= 75) return 'text-amber-600'
    return 'text-emerald-600'
})
</script>

<template>
    <Head title="İstatistikler" />
    <CustomerLayout>
        <template #header>İstatistikler</template>

        <!-- Info banner -->
        <div class="mb-4 rounded-xl border border-indigo-200 bg-indigo-50 p-4 text-sm text-indigo-900">
            <div class="flex gap-3">
                <InformationCircleIcon class="h-5 w-5 flex-shrink-0 text-indigo-600" />
                <span>
                    Bu sayfa son 24 saatin özetini gösterir. Detay için kartlara tıklayın — her sekme ilgili veriyi
                    o anda hesaplar (Apache log parse, cgroup snapshot vb.).
                </span>
            </div>
        </div>

        <!-- 4-card summary grid -->
        <div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            <!-- Bant Genişliği -->
            <Link :href="route('customer.stats.bandwidth')"
                  class="group rounded-xl border border-slate-200 bg-white p-5 shadow-sm transition hover:border-indigo-300 hover:shadow">
                <div class="flex items-center justify-between">
                    <ArrowTrendingUpIcon class="h-6 w-6 text-indigo-500" />
                    <span class="text-[10px] uppercase tracking-wider text-slate-400 group-hover:text-indigo-500">Detay →</span>
                </div>
                <h3 class="mt-3 text-sm font-medium text-slate-500">Bant Genişliği</h3>
                <p class="mt-1 text-2xl font-semibold text-slate-900">{{ summary.bandwidth_gb_today }} GB</p>
                <p class="mt-1 text-xs text-slate-500">
                    Bugün ·
                    <span class="font-medium text-slate-700">{{ summary.bandwidth_gb_mtd }} GB</span> bu ay
                </p>
            </Link>

            <!-- Kaynak Kullanımı -->
            <Link :href="route('customer.stats.resources')"
                  class="group rounded-xl border border-slate-200 bg-white p-5 shadow-sm transition hover:border-indigo-300 hover:shadow">
                <div class="flex items-center justify-between">
                    <CpuChipIcon class="h-6 w-6 text-indigo-500" />
                    <span class="text-[10px] uppercase tracking-wider text-slate-400 group-hover:text-indigo-500">Detay →</span>
                </div>
                <h3 class="mt-3 text-sm font-medium text-slate-500">CPU / RAM</h3>
                <p class="mt-1 text-2xl font-semibold" :class="cpuPctClass">{{ summary.cpu_avg_last_hour }}%</p>
                <p class="mt-1 text-xs text-slate-500">
                    Son 1 saat CPU ort. ·
                    <span class="font-medium" :class="memoryPctClass">{{ summary.memory_max_last_hour_mb }} MB</span>
                    RAM peak
                </p>
            </Link>

            <!-- Ziyaretçi -->
            <Link :href="route('customer.stats.visitors')"
                  class="group rounded-xl border border-slate-200 bg-white p-5 shadow-sm transition hover:border-indigo-300 hover:shadow">
                <div class="flex items-center justify-between">
                    <EyeIcon class="h-6 w-6 text-indigo-500" />
                    <span class="text-[10px] uppercase tracking-wider text-slate-400 group-hover:text-indigo-500">Detay →</span>
                </div>
                <h3 class="mt-3 text-sm font-medium text-slate-500">Ziyaretçiler</h3>
                <p class="mt-1 text-2xl font-semibold text-slate-900">
                    {{ summary.visitors_today === null ? '—' : fmtNumber(summary.visitors_today) }}
                </p>
                <p class="mt-1 text-xs text-slate-500">
                    {{ summary.visitors_today === null
                        ? 'Detay sayfasında hesaplanır'
                        : 'Bugün tekil ziyaretçi' }}
                </p>
            </Link>

            <!-- Hata Logları -->
            <Link :href="route('customer.stats.errors')"
                  class="group rounded-xl border border-slate-200 bg-white p-5 shadow-sm transition hover:border-indigo-300 hover:shadow">
                <div class="flex items-center justify-between">
                    <ExclamationTriangleIcon class="h-6 w-6 text-rose-500" />
                    <span class="text-[10px] uppercase tracking-wider text-slate-400 group-hover:text-indigo-500">Detay →</span>
                </div>
                <h3 class="mt-3 text-sm font-medium text-slate-500">Hatalar</h3>
                <p class="mt-1 text-2xl font-semibold text-slate-900">
                    {{ summary.errors_24h === null ? '—' : fmtNumber(summary.errors_24h) }}
                </p>
                <p class="mt-1 text-xs text-slate-500">
                    {{ summary.errors_24h === null
                        ? 'Detay sayfasında hesaplanır'
                        : 'Son 24 saatte error.log' }}
                </p>
            </Link>
        </div>

        <!-- 24h CPU sparkline -->
        <div class="mt-6 rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-sm font-semibold text-slate-800">Son 24 saat CPU kullanımı</h3>
                    <p class="text-xs text-slate-500">5 dakika örnekleme · ortalama yüzde</p>
                </div>
                <div v-if="hourly.length > 0" class="text-right">
                    <div class="text-2xl font-semibold" :class="cpuPctClass">{{ sparklineLastValue.toFixed(1) }}%</div>
                    <div class="text-xs text-slate-500">son okuma</div>
                </div>
            </div>

            <div v-if="hourly.length > 0" class="mt-4 overflow-x-auto">
                <svg :viewBox="`0 0 240 48`" preserveAspectRatio="none" class="h-12 w-full">
                    <path :d="sparklinePath" fill="none" stroke="currentColor" stroke-width="1.5"
                          class="text-indigo-500" />
                </svg>
            </div>
            <div v-else class="mt-4 rounded-md border border-dashed border-slate-200 px-4 py-8 text-center text-xs text-slate-500">
                Henüz örnekleme yok — <code class="rounded bg-slate-100 px-1">onoxsoft:resources:snapshot</code>
                cron'u 5 dakikada bir veri toplamaya başlayacak.
            </div>
        </div>

        <!-- Disk row -->
        <div class="mt-6 grid gap-4 sm:grid-cols-2">
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div class="flex items-center gap-3">
                    <CircleStackIcon class="h-5 w-5 text-slate-400" />
                    <h3 class="text-sm font-semibold text-slate-800">Disk Kullanımı</h3>
                </div>
                <div class="mt-3 flex items-end justify-between">
                    <div>
                        <div class="text-2xl font-semibold" :class="diskPctClass">{{ summary.disk_percent }}%</div>
                        <div class="mt-0.5 text-xs text-slate-500">
                            {{ formatBytes(summary.disk_used_bytes) }} / {{ formatBytes(summary.disk_quota_bytes) }}
                        </div>
                    </div>
                    <Link :href="route('customer.disk-usage.index')"
                          class="text-xs font-medium text-indigo-600 hover:text-indigo-700">
                        Detaylı analiz →
                    </Link>
                </div>
                <div class="mt-3 h-2 w-full overflow-hidden rounded bg-slate-100">
                    <div :style="{ width: Math.min(summary.disk_percent || 0, 100) + '%' }"
                         :class="['h-full transition-all',
                                  summary.disk_percent >= 90 ? 'bg-red-500' :
                                  summary.disk_percent >= 75 ? 'bg-amber-500' : 'bg-emerald-500']"></div>
                </div>
            </div>

            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div class="flex items-center gap-3">
                    <ChartBarIcon class="h-5 w-5 text-slate-400" />
                    <h3 class="text-sm font-semibold text-slate-800">Paket Limitleri</h3>
                </div>
                <dl class="mt-3 grid grid-cols-2 gap-3 text-xs">
                    <div>
                        <dt class="text-slate-500">Paket</dt>
                        <dd class="font-medium text-slate-800">{{ package?.name || '—' }}</dd>
                    </div>
                    <div>
                        <dt class="text-slate-500">CPU Limit</dt>
                        <dd class="font-medium text-slate-800">
                            {{ summary.cpu_limit_percent ? summary.cpu_limit_percent + '%' : 'sınırsız' }}
                        </dd>
                    </div>
                    <div>
                        <dt class="text-slate-500">RAM Limit</dt>
                        <dd class="font-medium text-slate-800">
                            {{ summary.memory_limit_mb ? summary.memory_limit_mb + ' MB' : 'sınırsız' }}
                        </dd>
                    </div>
                    <div>
                        <dt class="text-slate-500">Aktif İşlem</dt>
                        <dd class="font-medium text-slate-800">{{ summary.processes_now }}</dd>
                    </div>
                </dl>
            </div>
        </div>

        <!-- No domains warning -->
        <div v-if="!has_domains" class="mt-6 rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
            <div class="flex gap-3">
                <ExclamationTriangleIcon class="h-5 w-5 flex-shrink-0 text-amber-600" />
                <span>
                    Henüz hiç domain'iniz yok. İstatistik üretebilmek için
                    <Link :href="route('customer.domains.index')" class="font-medium underline">
                        domain ekleyin
                    </Link>.
                </span>
            </div>
        </div>
    </CustomerLayout>
</template>
