<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { Head, router, useForm, Link } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    ServerStackIcon,
    PlusIcon,
    TrashIcon,
    PowerIcon,
    CheckCircleIcon,
    XCircleIcon,
    ExclamationTriangleIcon,
    XMarkIcon,
    SignalIcon,
    ArrowRightIcon,
    BriefcaseIcon,
    ArrowsRightLeftIcon,
    BoltIcon,
    CpuChipIcon,
    CircleStackIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({ nodes: Array, stats: Object })

const showForm = ref(false)

// ── Real-time health (10sn polling) ───────────────────────────────────────────
const health = ref(null)
const lastUpdated = ref(null)
let pollTimer = null

async function fetchHealth() {
    try {
        const res = await fetch(route('admin.cluster.health'), {
            headers: { 'Accept': 'application/json' },
        })
        if (!res.ok) return
        health.value = await res.json()
        lastUpdated.value = new Date()
    } catch (e) {
        // sessizce başarısız ol — bir sonraki tick'te tekrar dener
    }
}

onMounted(() => {
    fetchHealth()
    pollTimer = setInterval(fetchHealth, 10_000)
})

onBeforeUnmount(() => {
    if (pollTimer) clearInterval(pollTimer)
})

// Health-aware node listesi (canlı veri varsa onu kullan, yoksa props)
const liveNodes = computed(() => {
    if (!health.value?.nodes) return props.nodes
    // health endpoint sadece subset döner — props nodes ile merge et
    const liveById = new Map(health.value.nodes.map(n => [n.id, n]))
    return props.nodes.map(n => {
        const live = liveById.get(n.id)
        if (!live) return n
        return {
            ...n,
            health_bucket: live.health,
            last_heartbeat_seconds: live.last_heartbeat_seconds,
            current_load: {
                ...(n.current_load || {}),
                cpu_pct: live.cpu_pct ?? n.current_load?.cpu_pct,
                mem_pct: live.mem_pct ?? n.current_load?.mem_pct,
                disk_pct: live.disk_pct ?? n.current_load?.disk_pct,
            },
            pending_jobs: live.pending_jobs ?? n.pending_jobs,
        }
    })
})

const healthDot = (bucket) => ({
    online:   { cls: 'bg-emerald-500',  label: 'online' },
    degraded: { cls: 'bg-amber-500 animate-pulse', label: 'degraded' },
    offline:  { cls: 'bg-red-500', label: 'offline' },
}[bucket] || { cls: 'bg-slate-400', label: 'unknown' })

const formatLastSeen = (sec) => {
    if (sec == null) return 'no heartbeat'
    if (sec < 60) return `${sec}sn önce`
    if (sec < 3600) return `${Math.round(sec / 60)}dk önce`
    return `${Math.round(sec / 3600)}sa önce`
}

// Yük bar rengi
const loadColor = (pct) => {
    if (pct == null) return 'bg-slate-200'
    if (pct > 85) return 'bg-red-500'
    if (pct > 65) return 'bg-amber-500'
    return 'bg-emerald-500'
}

const form = useForm({
    name: '',
    hostname: '',
    ip_address: '',
    role: 'web',
    environment: 'production',
    cpu_cores: 4,
    ram_mb: 8192,
    disk_gb: 100,
    region: 'eu-central-1',
    provider: 'Hetzner',
    max_account_count: 100,
    agent_url: '',
    agent_token: '',
    ssh_user: 'root',
    ssh_port: 22,
    notes: '',
})

const submit = () => form.post(route('admin.cluster.store'), {
    preserveScroll: true,
    onSuccess: () => { showForm.value = false; form.reset() },
})

const remove = async (n) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `Node '${n.name}' kaldırılacak?`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('admin.cluster.destroy', n.id), { preserveScroll: true })
}

const toggle = (n) => router.post(route('admin.cluster.toggle', n.id), {}, { preserveScroll: true })

const statusBadge = (s) => ({
    active: 'bg-emerald-100 text-emerald-700',
    provisioning: 'bg-amber-100 text-amber-700',
    maintenance: 'bg-blue-100 text-blue-700',
    down: 'bg-red-100 text-red-700',
    decommissioned: 'bg-slate-100 text-slate-500',
}[s] || 'bg-slate-100 text-slate-700')

const roleIcon = (r) => ({
    control_plane: '👑',
    web: '🌐',
    database: '🗄️',
    dns: '📡',
    mail: '📧',
    cache: '⚡',
    storage: '💾',
}[r] || '🖥️')
</script>

<template>
    <Head title="Cluster Yönetimi" />
    <AdminLayout>
        <template #header>Cluster Yönetimi (Multi-Server)</template>

        <!-- Multi-Server Cluster -->
        <div class="mb-4 rounded-xl border border-indigo-200 bg-indigo-50 p-4 text-sm text-indigo-900">
            <div class="flex items-center justify-between gap-2 flex-wrap">
                <div>
                    <strong>Multi-Server Cluster:</strong> Master ↔ Slave HMAC komünikasyonu aktif.
                    Her slave dakikada bir heartbeat atar; UI 10 saniyede bir health endpoint'i polling yapar.
                </div>
                <div class="flex items-center gap-2">
                    <Link :href="route('admin.cluster.sync.wizard')"
                        class="inline-flex items-center gap-1.5 rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-700">
                        <ArrowsRightLeftIcon class="h-3.5 w-3.5" /> Cluster Sync Wizard
                    </Link>
                </div>
            </div>
        </div>

        <!-- ── Real-time Health Widget (Phase N) ──────────────────────────── -->
        <div class="mb-4 rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
            <div class="flex items-center justify-between mb-3">
                <h3 class="text-sm font-semibold text-slate-700 inline-flex items-center gap-2">
                    <BoltIcon class="h-4 w-4 text-amber-500" /> Real-time Cluster Health
                </h3>
                <span class="text-xs text-slate-400">
                    <span v-if="lastUpdated">Son güncelleme: {{ lastUpdated.toLocaleTimeString() }}</span>
                    <span v-else>İlk veri bekleniyor…</span>
                </span>
            </div>
            <div v-if="health" class="grid grid-cols-2 gap-3 sm:grid-cols-6">
                <!-- Buckets -->
                <div class="rounded-lg bg-emerald-50 border border-emerald-100 px-3 py-2">
                    <div class="flex items-center gap-1.5 text-xs text-emerald-700"><span class="h-2 w-2 rounded-full bg-emerald-500"></span> Online</div>
                    <div class="mt-1 text-xl font-bold text-emerald-800">{{ health.buckets.online }}</div>
                </div>
                <div class="rounded-lg bg-amber-50 border border-amber-100 px-3 py-2">
                    <div class="flex items-center gap-1.5 text-xs text-amber-700"><span class="h-2 w-2 rounded-full bg-amber-500 animate-pulse"></span> Degraded</div>
                    <div class="mt-1 text-xl font-bold text-amber-800">{{ health.buckets.degraded }}</div>
                </div>
                <div class="rounded-lg bg-red-50 border border-red-100 px-3 py-2">
                    <div class="flex items-center gap-1.5 text-xs text-red-700"><span class="h-2 w-2 rounded-full bg-red-500"></span> Offline</div>
                    <div class="mt-1 text-xl font-bold text-red-800">{{ health.buckets.offline }}</div>
                </div>
                <div class="rounded-lg bg-slate-50 border border-slate-100 px-3 py-2">
                    <div class="flex items-center gap-1.5 text-xs text-slate-600"><CpuChipIcon class="h-3.5 w-3.5" /> CPU avg</div>
                    <div class="mt-1 text-xl font-bold text-slate-800">{{ health.avg_cpu_pct }}%</div>
                </div>
                <div class="rounded-lg bg-slate-50 border border-slate-100 px-3 py-2">
                    <div class="flex items-center gap-1.5 text-xs text-slate-600"><CircleStackIcon class="h-3.5 w-3.5" /> RAM avg</div>
                    <div class="mt-1 text-xl font-bold text-slate-800">{{ health.avg_mem_pct }}%</div>
                </div>
                <div class="rounded-lg bg-slate-50 border border-slate-100 px-3 py-2">
                    <div class="flex items-center gap-1.5 text-xs text-slate-600"><BriefcaseIcon class="h-3.5 w-3.5" /> Active jobs</div>
                    <div class="mt-1 text-xl font-bold text-slate-800">{{ health.active_jobs }}</div>
                </div>
            </div>
            <div v-else class="py-2 text-center text-xs text-slate-400">
                Health verisi yükleniyor…
            </div>
        </div>

        <!-- Stats -->
        <div class="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-5">
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <ServerStackIcon class="h-5 w-5 text-indigo-500" />
                <div class="mt-2 text-2xl font-bold">{{ stats.total }}</div>
                <p class="text-xs text-slate-500">Toplam Node</p>
            </div>
            <div class="rounded-xl border border-emerald-200 bg-emerald-50 p-4">
                <CheckCircleIcon class="h-5 w-5 text-emerald-600" />
                <div class="mt-2 text-2xl font-bold text-emerald-700">{{ stats.active }}</div>
                <p class="text-xs text-emerald-700">Aktif</p>
            </div>
            <div :class="['rounded-xl border p-4', stats.down > 0 ? 'border-red-200 bg-red-50' : 'border-slate-200 bg-white shadow-sm']">
                <XCircleIcon :class="['h-5 w-5', stats.down > 0 ? 'text-red-600' : 'text-slate-400']" />
                <div :class="['mt-2 text-2xl font-bold', stats.down > 0 ? 'text-red-700' : 'text-slate-500']">{{ stats.down }}</div>
                <p class="text-xs text-slate-500">Down</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="text-xs text-slate-500">Toplam Kapasite</div>
                <div class="mt-1 text-2xl font-bold">{{ stats.total_capacity }}</div>
                <p class="text-xs text-slate-500">hesap</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="text-xs text-slate-500">Kullanılan</div>
                <div class="mt-1 text-2xl font-bold">{{ stats.total_used }}</div>
                <p class="text-xs text-slate-500">{{ stats.total_capacity ? Math.round(stats.total_used / stats.total_capacity * 100) + '%' : '—' }}</p>
            </div>
        </div>

        <div class="mb-4 flex justify-end">
            <button @click="showForm = true" class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">
                <PlusIcon class="h-4 w-4" /> Node Ekle
            </button>
        </div>

        <div v-if="nodes.length === 0" class="rounded-xl border border-dashed border-slate-300 bg-white p-12 text-center">
            <ServerStackIcon class="mx-auto h-14 w-14 text-slate-300" />
            <h3 class="mt-3 text-lg font-semibold">Henüz cluster node yok</h3>
            <p class="mt-1 text-sm text-slate-500">Single-server modunda çalışıyorsun. 2+ node ile cluster kurulabilir.</p>
        </div>

        <div v-else class="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
            <div v-for="n in liveNodes" :key="n.id" class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div class="flex items-start justify-between gap-3">
                    <div class="flex items-start gap-3">
                        <div class="text-4xl">{{ roleIcon(n.role) }}</div>
                        <div>
                            <div class="flex items-center gap-2 flex-wrap">
                                <h3 class="font-semibold">{{ n.name }}</h3>
                                <span :class="['rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase', statusBadge(n.status)]">{{ n.status }}</span>
                                <span v-if="!n.accept_new_accounts" class="rounded bg-amber-100 px-1.5 py-0.5 text-[10px] font-semibold text-amber-700">YENİ KABUL ETMİYOR</span>
                            </div>
                            <p class="font-mono text-xs text-slate-500">{{ n.hostname }}</p>
                            <p class="font-mono text-xs text-slate-400">{{ n.ip_address }}</p>
                        </div>
                    </div>
                    <!-- Real-time health badge -->
                    <div v-if="n.health_bucket" class="flex flex-col items-end gap-0.5">
                        <span class="inline-flex items-center gap-1.5 text-xs font-medium"
                            :class="{
                                'text-emerald-700': n.health_bucket === 'online',
                                'text-amber-700': n.health_bucket === 'degraded',
                                'text-red-700': n.health_bucket === 'offline',
                            }">
                            <span class="h-2 w-2 rounded-full" :class="healthDot(n.health_bucket).cls"></span>
                            {{ healthDot(n.health_bucket).label }}
                        </span>
                        <span class="text-[10px] text-slate-400 font-mono">
                            {{ formatLastSeen(n.last_heartbeat_seconds) }}
                        </span>
                    </div>
                    <span v-else-if="n.is_healthy" class="inline-flex items-center gap-1 text-xs text-emerald-600">
                        <SignalIcon class="h-4 w-4" /> sağlıklı
                    </span>
                    <span v-else class="inline-flex items-center gap-1 text-xs text-amber-600">
                        <ExclamationTriangleIcon class="h-4 w-4" /> {{ n.last_heartbeat_at || 'no heartbeat' }}
                    </span>
                </div>

                <dl class="mt-3 grid grid-cols-2 gap-2 border-t border-slate-100 pt-3 text-xs">
                    <div><dt class="text-slate-500">Rol</dt><dd class="font-medium capitalize">{{ n.role }}</dd></div>
                    <div><dt class="text-slate-500">Ortam</dt><dd class="font-medium">{{ n.environment }}</dd></div>
                    <div><dt class="text-slate-500">CPU</dt><dd class="font-mono">{{ n.cpu_cores || '—' }} core</dd></div>
                    <div><dt class="text-slate-500">RAM</dt><dd class="font-mono">{{ n.ram_mb ? (n.ram_mb/1024).toFixed(1)+' GB' : '—' }}</dd></div>
                    <div><dt class="text-slate-500">Disk</dt><dd class="font-mono">{{ n.disk_gb || '—' }} GB</dd></div>
                    <div><dt class="text-slate-500">Provider</dt><dd>{{ n.provider || '—' }} · {{ n.region || '—' }}</dd></div>
                </dl>

                <!-- Kapasite çubuğu -->
                <div v-if="n.max_account_count" class="mt-3">
                    <div class="flex justify-between text-xs mb-1">
                        <span class="text-slate-500">Kapasite</span>
                        <span class="font-medium">{{ n.current_account_count }} / {{ n.max_account_count }}</span>
                    </div>
                    <div class="h-1.5 overflow-hidden rounded-full bg-slate-200">
                        <div class="h-full bg-indigo-500" :style="{ width: (n.current_account_count / n.max_account_count * 100) + '%' }"></div>
                    </div>
                </div>

                <!-- Canlı yük çubukları -->
                <div v-if="n.current_load" class="mt-3 space-y-1">
                    <div v-for="[label, key] in [['CPU', 'cpu_pct'], ['RAM', 'mem_pct'], ['Disk', 'disk_pct']]" :key="key"
                        class="flex items-center gap-2 text-xs">
                        <span class="w-8 shrink-0 text-slate-500">{{ label }}</span>
                        <div class="flex-1 h-1.5 overflow-hidden rounded-full bg-slate-100">
                            <div :class="['h-full rounded-full', loadColor(n.current_load[key])]"
                                :style="{ width: (n.current_load[key] ?? 0) + '%' }"></div>
                        </div>
                        <span class="w-8 text-right font-mono text-slate-500">{{ n.current_load[key] ?? '?' }}%</span>
                    </div>
                </div>

                <!-- Bekleyen job sayısı -->
                <div v-if="n.pending_jobs > 0" class="mt-2 flex items-center gap-1.5 text-xs text-amber-700">
                    <BriefcaseIcon class="h-3.5 w-3.5" />
                    {{ n.pending_jobs }} bekleyen job
                </div>

                <div class="mt-3 flex gap-2">
                    <Link :href="route('admin.cluster.show', n.id)"
                        class="flex-1 inline-flex items-center justify-center gap-1 rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-700">
                        Detay <ArrowRightIcon class="h-3 w-3" />
                    </Link>
                    <button @click="toggle(n)" class="inline-flex items-center gap-1 rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50">
                        <PowerIcon class="h-3.5 w-3.5" />
                    </button>
                    <button @click="remove(n)" class="rounded-lg border border-red-300 bg-white px-3 py-1.5 text-red-700 hover:bg-red-50">
                        <TrashIcon class="h-3.5 w-3.5" />
                    </button>
                </div>
            </div>
        </div>

        <!-- Add node modal -->
        <div v-if="showForm" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-2xl rounded-xl bg-white p-6 shadow-xl max-h-[90vh] overflow-y-auto">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="text-lg font-semibold">Yeni Cluster Node</h3>
                    <button @click="showForm = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>
                <form @submit.prevent="submit" class="space-y-4">
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-sm font-medium">Node Adı</label>
                            <input v-model="form.name" type="text" placeholder="web1-eu" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                        </div>
                        <div>
                            <label class="block text-sm font-medium">Hostname (FQDN)</label>
                            <input v-model="form.hostname" type="text" placeholder="web1.example.com" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                        </div>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-sm font-medium">IP</label>
                            <input v-model="form.ip_address" type="text" placeholder="192.0.2.10" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                        </div>
                        <div>
                            <label class="block text-sm font-medium">Rol</label>
                            <select v-model="form.role" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                                <option value="web">🌐 Web (Apache+PHP)</option>
                                <option value="database">🗄️ Database (MariaDB)</option>
                                <option value="dns">📡 DNS (PowerDNS)</option>
                                <option value="mail">📧 Mail</option>
                                <option value="cache">⚡ Cache (Redis)</option>
                                <option value="storage">💾 Storage</option>
                                <option value="control_plane">👑 Control Plane</option>
                            </select>
                        </div>
                    </div>
                    <div class="grid grid-cols-3 gap-3">
                        <div>
                            <label class="block text-sm font-medium">CPU</label>
                            <input v-model.number="form.cpu_cores" type="number" min="1" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                        </div>
                        <div>
                            <label class="block text-sm font-medium">RAM (MB)</label>
                            <input v-model.number="form.ram_mb" type="number" min="512" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                        </div>
                        <div>
                            <label class="block text-sm font-medium">Disk (GB)</label>
                            <input v-model.number="form.disk_gb" type="number" min="10" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                        </div>
                    </div>
                    <div class="grid grid-cols-3 gap-3">
                        <div>
                            <label class="block text-sm font-medium">Provider</label>
                            <input v-model="form.provider" type="text" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                        </div>
                        <div>
                            <label class="block text-sm font-medium">Region</label>
                            <input v-model="form.region" type="text" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                        </div>
                        <div>
                            <label class="block text-sm font-medium">Maks. Hesap</label>
                            <input v-model.number="form.max_account_count" type="number" min="0" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                        </div>
                    </div>
                    <details class="rounded-lg border border-slate-200 p-3">
                        <summary class="text-sm font-medium cursor-pointer">Agent + SSH Config (opsiyonel)</summary>
                        <div class="mt-3 space-y-3">
                            <input v-model="form.agent_url" type="text" placeholder="https://node1.example.com:8443" class="w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-xs" />
                            <input v-model="form.agent_token" type="password" placeholder="Shared secret" class="w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-xs" />
                            <div class="grid grid-cols-2 gap-3">
                                <input v-model="form.ssh_user" type="text" placeholder="root" class="rounded-lg border border-slate-300 px-3 py-2 font-mono text-xs" />
                                <input v-model.number="form.ssh_port" type="number" placeholder="22" class="rounded-lg border border-slate-300 px-3 py-2 font-mono text-xs" />
                            </div>
                        </div>
                    </details>
                    <div class="flex justify-end gap-2 border-t pt-3">
                        <button type="button" @click="showForm = false" class="rounded-lg border border-slate-300 px-4 py-2 text-sm">İptal</button>
                        <button type="submit" :disabled="form.processing" class="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">Node Ekle</button>
                    </div>
                </form>
            </div>
        </div>
    </AdminLayout>
</template>
