<script setup>
import { computed } from 'vue'
import { Head, router } from '@inertiajs/vue3'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import {
    ChartBarIcon,
    ArrowDownTrayIcon,
    ArrowUpTrayIcon,
    GlobeAltIcon,
    ExclamationTriangleIcon,
    InformationCircleIcon,
    FunnelIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    daily:        { type: Array,  default: () => [] },
    perDomain:    { type: Array,  default: () => [] },
    monthly:      { type: Number, default: 0 },
    monthlyLimit: { type: Number, default: 100000 },
    usagePct:     { type: Number, default: 0 },
    period:       { type: String, default: '30d' },
    totals:       { type: Object, default: () => ({ bytes_in: 0, bytes_out: 0, requests: 0 }) },
})

// ─── Period selector ─────────────────────────────────────────────────────────
const periods = [
    { value: '24h',        label: '24 Saat' },
    { value: '30d',        label: '30 Gün' },
    { value: 'this_month', label: 'Bu Ay' },
    { value: 'last_month', label: 'Geçen Ay' },
]

const setPeriod = (p) => {
    router.get(route('customer.stats.bandwidth'), { period: p }, { preserveState: false, replace: true })
}

// ─── Byte formatter ──────────────────────────────────────────────────────────
const formatBytes = (bytes) => {
    if (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)]}`
}

// ─── Bar chart ───────────────────────────────────────────────────────────────
const maxBarValue = computed(() => {
    if (!props.daily.length) return 1
    return Math.max(...props.daily.map((d) => d.bytes_in + d.bytes_out)) || 1
})

const inHeight  = (d) => `${(d.bytes_in  / maxBarValue.value) * 100}%`
const outHeight = (d) => `${(d.bytes_out / maxBarValue.value) * 100}%`

// ─── Monthly usage bar colour ────────────────────────────────────────────────
const usageBarClass = computed(() => {
    if (props.usagePct >= 90) return 'bg-red-500'
    if (props.usagePct >= 75) return 'bg-amber-500'
    return 'bg-emerald-500'
})

// ─── Per-domain table total ───────────────────────────────────────────────────
const domainAccountTotal = computed(() =>
    props.perDomain.reduce((s, d) => s + d.bytes_in + d.bytes_out, 0)
)
</script>

<template>
    <Head title="Bant Genişliği İstatistikleri" />
    <CustomerLayout>
        <template #header>Bant Genişliği</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>
                    Bant genişliği, sitenizin sunucudan dışarı/içeri gönderdiği toplam veridir.
                    Veriler her gece Apache access log analiziyle <code class="rounded bg-white/60 px-1">bandwidth_usage</code>
                    tablosuna işlenir; günlük rakamlar bir sonraki gün sabahı yenilenir.
                </span>
            </div>
        </div>

        <!-- Period selector -->
        <div class="mb-5 flex items-center gap-2">
            <FunnelIcon class="h-4 w-4 text-slate-400" />
            <div class="flex gap-1">
                <button
                    v-for="p in periods"
                    :key="p.value"
                    @click="setPeriod(p.value)"
                    :class="[
                        'rounded px-3 py-1.5 text-xs font-medium transition-colors',
                        period === p.value
                            ? 'bg-indigo-600 text-white'
                            : 'bg-white border border-slate-200 text-slate-600 hover:bg-slate-50',
                    ]"
                >{{ p.label }}</button>
            </div>
        </div>

        <!-- Stat cards -->
        <div class="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
            <!-- Total In -->
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="flex items-center justify-between mb-2">
                    <ArrowDownTrayIcon class="h-5 w-5 text-emerald-500" />
                    <span class="text-xs text-slate-500">Gelen Trafik</span>
                </div>
                <div class="text-xl font-bold text-slate-900">{{ formatBytes(totals.bytes_in) }}</div>
                <div class="mt-1 text-xs text-slate-400">Ziyaretçi → Sunucu</div>
            </div>

            <!-- Total Out -->
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="flex items-center justify-between mb-2">
                    <ArrowUpTrayIcon class="h-5 w-5 text-blue-500" />
                    <span class="text-xs text-slate-500">Giden Trafik</span>
                </div>
                <div class="text-xl font-bold text-slate-900">{{ formatBytes(totals.bytes_out) }}</div>
                <div class="mt-1 text-xs text-slate-400">Sunucu → Ziyaretçi</div>
            </div>

            <!-- Requests -->
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="flex items-center justify-between mb-2">
                    <ChartBarIcon class="h-5 w-5 text-purple-500" />
                    <span class="text-xs text-slate-500">İstek Sayısı</span>
                </div>
                <div class="text-xl font-bold text-slate-900">{{ totals.requests.toLocaleString('tr-TR') }}</div>
                <div class="mt-1 text-xs text-slate-400">HTTP isteği</div>
            </div>

            <!-- Monthly usage % -->
            <div
                :class="[
                    'rounded-xl border p-4',
                    usagePct >= 80
                        ? 'border-amber-200 bg-amber-50'
                        : 'border-slate-200 bg-white shadow-sm',
                ]"
            >
                <div class="flex items-center justify-between mb-2">
                    <ExclamationTriangleIcon
                        v-if="usagePct >= 80"
                        class="h-5 w-5 text-amber-500"
                    />
                    <ChartBarIcon v-else class="h-5 w-5 text-slate-400" />
                    <span class="text-xs text-slate-500">Bu Ay Limiti</span>
                </div>
                <div class="text-xl font-bold text-slate-900">{{ usagePct }}%</div>
                <div class="mt-2 h-1.5 overflow-hidden rounded-full bg-slate-200">
                    <div
                        :class="['h-full transition-all', usageBarClass]"
                        :style="{ width: Math.min(usagePct, 100) + '%' }"
                    ></div>
                </div>
                <div class="mt-1 text-xs text-slate-400">
                    {{ formatBytes(monthly) }} / {{ monthlyLimit.toLocaleString('tr-TR') }} MB
                </div>
            </div>
        </div>

        <!-- Daily bar chart -->
        <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
            <h3 class="mb-4 flex items-center gap-2 text-sm font-semibold text-slate-700">
                <ChartBarIcon class="h-4 w-4 text-indigo-500" />
                Günlük Bant Genişliği
            </h3>

            <div v-if="daily.length" class="flex items-end gap-[2px] h-56 border-b border-l border-slate-200 pb-1 pl-1">
                <div
                    v-for="(d, i) in daily"
                    :key="i"
                    class="group relative flex flex-1 min-w-0 flex-col items-stretch justify-end"
                >
                    <!-- Out bar (top, blue) -->
                    <div :style="{ height: outHeight(d) }" class="bg-blue-400 hover:bg-blue-500 transition-colors"></div>
                    <!-- In bar (bottom, green) -->
                    <div :style="{ height: inHeight(d) }"  class="bg-emerald-400 hover:bg-emerald-500 transition-colors"></div>

                    <!-- Tooltip -->
                    <div class="pointer-events-none absolute bottom-full left-1/2 z-10 mb-1 hidden -translate-x-1/2 whitespace-nowrap rounded bg-slate-900 px-2 py-1 text-xs text-white group-hover:block">
                        <div class="font-semibold">{{ d.date }}</div>
                        <div>↓ {{ formatBytes(d.bytes_in) }}</div>
                        <div>↑ {{ formatBytes(d.bytes_out) }}</div>
                        <div class="mt-0.5 border-t border-slate-700 pt-0.5 font-bold">
                            {{ formatBytes(d.bytes_in + d.bytes_out) }}
                        </div>
                        <div class="text-slate-400">{{ d.requests.toLocaleString('tr-TR') }} istek</div>
                    </div>
                </div>
            </div>
            <div v-else class="flex h-56 items-center justify-center text-sm text-slate-400">
                Bu dönem için veri bulunamadı.
            </div>

            <div v-if="daily.length" class="mt-1 flex justify-between text-[10px] text-slate-400">
                <span>{{ daily[0]?.date }}</span>
                <span>{{ daily[daily.length - 1]?.date }}</span>
            </div>

            <div class="mt-4 flex items-center gap-4 text-xs text-slate-600">
                <div class="flex items-center gap-1.5">
                    <div class="h-3 w-3 rounded bg-emerald-400"></div>
                    <span>Gelen (İndirme)</span>
                </div>
                <div class="flex items-center gap-1.5">
                    <div class="h-3 w-3 rounded bg-blue-400"></div>
                    <span>Giden (Yükleme)</span>
                </div>
            </div>
        </div>

        <!-- Per-domain table -->
        <div v-if="perDomain.length" class="mt-6 rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
            <h3 class="mb-4 flex items-center gap-2 text-sm font-semibold text-slate-700">
                <GlobeAltIcon class="h-4 w-4 text-purple-500" />
                Domain Bazlı Kırılım
            </h3>

            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="border-b border-slate-100 text-xs text-slate-500">
                            <th class="pb-2 text-left font-medium">Domain</th>
                            <th class="pb-2 text-right font-medium">Gelen</th>
                            <th class="pb-2 text-right font-medium">Giden</th>
                            <th class="pb-2 text-right font-medium">Toplam</th>
                            <th class="pb-2 text-right font-medium">İstekler</th>
                            <th class="pb-2 text-right font-medium">%</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr
                            v-for="d in perDomain"
                            :key="d.domain_name"
                            class="border-b border-slate-50 hover:bg-slate-50"
                        >
                            <td class="py-2.5 font-mono text-xs text-slate-800">{{ d.domain_name }}</td>
                            <td class="py-2.5 text-right text-slate-600">{{ formatBytes(d.bytes_in) }}</td>
                            <td class="py-2.5 text-right text-slate-600">{{ formatBytes(d.bytes_out) }}</td>
                            <td class="py-2.5 text-right font-semibold text-slate-800">{{ formatBytes(d.bytes_in + d.bytes_out) }}</td>
                            <td class="py-2.5 text-right text-slate-500">{{ d.requests.toLocaleString('tr-TR') }}</td>
                            <td class="py-2.5 text-right">
                                <span class="inline-block min-w-[2.5rem] rounded bg-indigo-50 px-1.5 py-0.5 text-xs font-medium text-indigo-700">
                                    {{ d.pct }}%
                                </span>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

    </CustomerLayout>
</template>
