<script setup>
import { ref, computed } from 'vue'
import { Head, Link, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()
import {
    Cog6ToothIcon,
    PlayIcon,
    StopIcon,
    ArrowPathIcon,
    CheckCircleIcon,
    XCircleIcon,
    DocumentTextIcon,
    ExclamationTriangleIcon,
    MagnifyingGlassIcon,
    ClockIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    services: Array,
    grouped: Object,
    summary: Object,
    failed_units: { type: Array, default: () => [] },
})

const search = ref('')
const filterStatus = ref('all')

const filtered = computed(() => {
    return props.services.filter((s) => {
        if (filterStatus.value === 'running' && s.status !== 'running') return false
        if (filterStatus.value === 'stopped' && s.status !== 'stopped') return false
        if (filterStatus.value === 'failed' && s.status !== 'failed') return false
        if (search.value && !s.name.toLowerCase().includes(search.value.toLowerCase()) && !s.unit.includes(search.value.toLowerCase())) return false
        return true
    })
})

const formatRelative = (iso) => {
    if (!iso) return '—'
    const diff = (Date.now() - new Date(iso).getTime()) / 1000
    if (diff < 60) return Math.floor(diff) + 'sn önce'
    if (diff < 3600) return Math.floor(diff / 60) + 'dk önce'
    if (diff < 86400) return Math.floor(diff / 3600) + 'sa önce'
    return Math.floor(diff / 86400) + 'g önce'
}

const restart = async (s) => {
    const ok = await ask({
        title: 'Servisi yeniden başlat',
        message: `${s.name} yeniden başlatılacak. Birkaç saniyelik kısa bir kesinti olabilir.`,
        variant: 'warning',
        confirmText: 'Restart',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('admin.services.restart', s.unit), {}, { preserveScroll: true })
}

const reload = async (s) => {
    const ok = await ask({
        title: 'Servisi yeniden yükle',
        message: `${s.name} graceful reload edilecek. Aktif bağlantılar kesilmez.`,
        variant: 'info',
        confirmText: 'Reload',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('admin.services.reload', s.unit), {}, { preserveScroll: true })
}

const stop = async (s) => {
    if (s.critical) {
        const okCritical = await ask({
            title: 'Kritik servis durduruluyor',
            message: `${s.name} KRİTİK bir servis. Durdurmak panel erişimini veya hizmetleri etkileyebilir.`,
            variant: 'danger',
            confirmText: 'Yine de Durdur',
            cancelText: 'İptal',
        })
        if (!okCritical) return
    }
    const ok = await ask({
        title: 'Servisi durdur',
        message: `${s.name} durdurulacak.`,
        variant: 'warning',
        confirmText: 'Durdur',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('admin.services.stop', s.unit), {}, { preserveScroll: true })
}

const start = (s) => {
    router.post(route('admin.services.start', s.unit), {}, { preserveScroll: true })
}

// Toplu işlemler
const bulkInFlight = ref(false)
const bulkMessage = ref(null)

const restartAll = async (mode) => {
    const verb = mode === 'reload' ? 'kesintisiz yeniden yükle' : 'hepsini yeniden başlat'
    const ok = await ask({
        title: mode === 'reload' ? 'Tümünü reload et' : 'Tüm servisleri restart et',
        message: `Tüm yönetilen servisleri ${verb}? İşlem birkaç saniye sürebilir.`,
        variant: 'warning',
        confirmText: mode === 'reload' ? 'Tümünü Reload Et' : 'Tümünü Restart Et',
        cancelText: 'İptal',
    })
    if (!ok) return

    bulkInFlight.value = true
    bulkMessage.value = null
    try {
        const res = await fetch(route('admin.services.restart-all'), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            },
            body: JSON.stringify({ mode }),
        })
        const data = await res.json()
        bulkMessage.value = { success: data.success, text: data.message }
        router.reload({ only: ['services', 'grouped', 'summary'] })
    } catch (e) {
        bulkMessage.value = { success: false, text: e.message }
    } finally {
        bulkInFlight.value = false
        setTimeout(() => { bulkMessage.value = null }, 5000)
    }
}

const enableAll = async () => {
    const ok = await ask({
        title: 'Tüm servisleri enable et',
        message: 'Tüm servisler reboot sonrası otomatik açılmak üzere enable edilecek. Lisanssız mail servisleri atlanır.',
        variant: 'info',
        confirmText: 'Tümünü Enable Et',
        cancelText: 'İptal',
    })
    if (!ok) return
    bulkInFlight.value = true
    bulkMessage.value = null
    try {
        const res = await fetch(route('admin.services.enable-all'), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            },
        })
        const data = await res.json()
        bulkMessage.value = { success: data.success, text: data.message }
    } catch (e) {
        bulkMessage.value = { success: false, text: e.message }
    } finally {
        bulkInFlight.value = false
        setTimeout(() => { bulkMessage.value = null }, 5000)
    }
}

const categoryLabel = (c) => ({
    web: 'Web Sunucu',
    database: 'Veritabanı',
    dns: 'DNS',
    file: 'Dosya',
    cache: 'Önbellek',
    security: 'Güvenlik',
    system: 'Sistem',
    mail: 'Posta',
    panel: 'Panel',
}[c] || c)

const categoryColor = (c) => ({
    web: 'border-l-blue-500',
    database: 'border-l-cyan-500',
    dns: 'border-l-indigo-500',
    file: 'border-l-amber-500',
    cache: 'border-l-red-500',
    security: 'border-l-purple-500',
    system: 'border-l-slate-500',
    mail: 'border-l-rose-500',
    panel: 'border-l-emerald-500',
}[c] || 'border-l-slate-500')
</script>

<template>
    <Head title="Servis Durumu" />
    <AdminLayout>
        <template #header>Servis Durumu (systemctl)</template>

        <!-- Toplu işlem barı: Restart All + Reload All + Enable All -->
        <div class="mb-4 rounded-xl border border-indigo-200 bg-indigo-50 dark:border-indigo-900 dark:bg-indigo-950/30 p-4">
            <div class="flex flex-wrap items-center gap-3 justify-between">
                <div>
                    <h3 class="text-sm font-semibold text-indigo-900 dark:text-indigo-200">Sunucu Yönetimi</h3>
                    <p class="text-xs text-indigo-700 dark:text-indigo-400 mt-0.5">
                        Bütün servisleri tek tıkla yönet · Reboot sonrası otomatik başlatma · License-gated mail servisleri
                    </p>
                </div>
                <div class="flex flex-wrap gap-2">
                    <button @click="restartAll('reload')"
                            :disabled="bulkInFlight"
                            class="inline-flex items-center gap-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white px-3 py-2 text-xs font-semibold disabled:opacity-50 shadow-sm">
                        <ArrowPathIcon class="h-4 w-4" :class="bulkInFlight ? 'animate-spin' : ''" />
                        Graceful Reload (kesintisiz)
                    </button>
                    <button @click="restartAll('restart')"
                            :disabled="bulkInFlight"
                            class="inline-flex items-center gap-1.5 rounded-lg bg-amber-600 hover:bg-amber-700 text-white px-3 py-2 text-xs font-semibold disabled:opacity-50 shadow-sm">
                        <ArrowPathIcon class="h-4 w-4" :class="bulkInFlight ? 'animate-spin' : ''" />
                        Hard Restart (tüm servisler)
                    </button>
                    <button @click="enableAll"
                            :disabled="bulkInFlight"
                            class="inline-flex items-center gap-1.5 rounded-lg border border-indigo-300 dark:border-indigo-700 bg-white dark:bg-slate-800 text-indigo-700 dark:text-indigo-300 hover:bg-indigo-50 dark:hover:bg-indigo-900/40 px-3 py-2 text-xs font-semibold disabled:opacity-50">
                        <CheckCircleIcon class="h-4 w-4" />
                        Reboot Resilience (enable all)
                    </button>
                </div>
            </div>
            <div v-if="bulkMessage" :class="['mt-3 text-xs flex items-center gap-2 rounded-lg px-3 py-2',
                bulkMessage.success ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300' : 'bg-red-100 text-red-700 dark:bg-red-950/40 dark:text-red-300']">
                <CheckCircleIcon v-if="bulkMessage.success" class="h-4 w-4" />
                <XCircleIcon v-else class="h-4 w-4" />
                {{ bulkMessage.text }}
            </div>
        </div>

        <!-- Summary cards -->
        <div class="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-4">
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="flex items-center justify-between">
                    <Cog6ToothIcon class="h-5 w-5 text-slate-400" />
                </div>
                <div class="mt-2 text-2xl font-bold">{{ summary.total }}</div>
                <p class="text-xs text-slate-500">Toplam Servis</p>
            </div>
            <div class="rounded-xl border border-emerald-200 bg-emerald-50 p-4">
                <div class="flex items-center justify-between">
                    <CheckCircleIcon class="h-5 w-5 text-emerald-600" />
                </div>
                <div class="mt-2 text-2xl font-bold text-emerald-700">{{ summary.running }}</div>
                <p class="text-xs text-emerald-700">Çalışıyor</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="flex items-center justify-between">
                    <XCircleIcon class="h-5 w-5 text-slate-400" />
                </div>
                <div class="mt-2 text-2xl font-bold text-slate-500">{{ summary.stopped }}</div>
                <p class="text-xs text-slate-500">Durduruldu</p>
            </div>
            <div :class="['rounded-xl border p-4', summary.critical_down > 0 ? 'border-red-200 bg-red-50' : 'border-slate-200 bg-white shadow-sm']">
                <div class="flex items-center justify-between">
                    <ExclamationTriangleIcon :class="['h-5 w-5', summary.critical_down > 0 ? 'text-red-600' : 'text-slate-400']" />
                </div>
                <div :class="['mt-2 text-2xl font-bold', summary.critical_down > 0 ? 'text-red-700' : 'text-slate-700']">{{ summary.critical_down }}</div>
                <p class="text-xs text-slate-500">Kritik Sorunlu</p>
            </div>
        </div>

        <!-- Failed units alert banner (Phase 2) -->
        <div v-if="failed_units.length > 0" class="mb-4 rounded-xl border-2 border-red-300 bg-red-50 p-4">
            <div class="mb-2 flex items-center gap-2">
                <ExclamationTriangleIcon class="h-5 w-5 text-red-600" />
                <h3 class="font-semibold text-red-900">
                    {{ failed_units.length }} servis FAILED durumda
                </h3>
            </div>
            <p class="mb-3 text-xs text-red-800">
                Aşağıdaki systemd unit'leri "failed" state'inde — manuel müdahale gerek. journal log'unu inceleyip restart deneyin.
            </p>
            <div class="flex flex-wrap gap-2">
                <div v-for="u in failed_units" :key="u.unit"
                     class="flex items-center gap-2 rounded-lg border border-red-300 bg-white px-3 py-1.5 text-xs">
                    <span class="text-base">{{ u.icon }}</span>
                    <span class="font-semibold">{{ u.name }}</span>
                    <code class="text-[10px] text-slate-500">({{ u.unit }})</code>
                    <Link :href="route('admin.services.logs', u.unit)"
                          class="ml-1 rounded bg-red-100 px-2 py-0.5 text-[10px] font-medium text-red-700 hover:bg-red-200">
                        Log
                    </Link>
                </div>
            </div>
        </div>

        <!-- Filter bar -->
        <div class="mb-4 flex flex-wrap gap-3">
            <div class="relative flex-1 min-w-[240px]">
                <MagnifyingGlassIcon class="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                <input v-model="search" type="text" placeholder="Servis adı veya unit ara..."
                       class="w-full rounded-lg border border-slate-300 bg-white py-2 pl-9 pr-3 text-sm" />
            </div>
            <select v-model="filterStatus" class="rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm">
                <option value="all">Tümü</option>
                <option value="running">Çalışan</option>
                <option value="stopped">Durmuş</option>
                <option value="failed">Failed</option>
            </select>
        </div>

        <!-- Services list -->
        <div class="grid grid-cols-1 gap-3 lg:grid-cols-2">
            <div v-for="s in filtered" :key="s.unit"
                 :class="['rounded-xl border border-slate-200 bg-white p-4 shadow-sm border-l-4', categoryColor(s.category)]">
                <div class="flex items-start justify-between gap-3">
                    <div class="flex items-start gap-3 flex-1 min-w-0">
                        <div class="text-3xl">{{ s.icon }}</div>
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center gap-2 flex-wrap">
                                <h3 class="font-semibold text-slate-900">{{ s.name }}</h3>
                                <span v-if="s.critical" class="rounded bg-red-100 px-1.5 py-0.5 text-[10px] font-semibold text-red-700">KRİTİK</span>
                                <span class="rounded bg-slate-100 px-1.5 py-0.5 text-[10px] text-slate-600">{{ categoryLabel(s.category) }}</span>
                            </div>
                            <p class="text-xs text-slate-500">{{ s.description }}</p>
                            <p class="mt-1 font-mono text-[11px] text-slate-400">{{ s.unit }}</p>
                        </div>
                    </div>
                    <div class="flex flex-col items-end gap-2">
                        <span v-if="s.status === 'running'" class="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-1 text-xs font-semibold text-emerald-700">
                            <span class="h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse"></span>
                            Çalışıyor
                        </span>
                        <span v-else-if="s.status === 'failed'" class="inline-flex items-center gap-1 rounded-full bg-red-100 px-2 py-1 text-xs font-semibold text-red-700">
                            <ExclamationTriangleIcon class="h-3 w-3" /> FAILED
                        </span>
                        <span v-else class="inline-flex items-center gap-1 rounded-full bg-slate-100 px-2 py-1 text-xs font-semibold text-slate-500">
                            <XCircleIcon class="h-3 w-3" /> Durdu
                        </span>
                    </div>
                </div>

                <!-- Last action info (Phase 2) -->
                <div v-if="s.last_action" class="mt-2 flex items-center gap-2 text-[10px] text-slate-500">
                    <ClockIcon class="h-3 w-3" />
                    Son işlem: <strong>{{ s.last_action.action }}</strong>
                    ({{ s.last_action.outcome === 'success' ? '✓' : '✗' }})
                    · {{ s.last_action.actor_name || '—' }}
                    · {{ formatRelative(s.last_action.occurred_at) }}
                </div>

                <!-- Metrics row -->
                <div v-if="s.status === 'running'" class="mt-3 grid grid-cols-3 gap-2 text-xs">
                    <div class="rounded bg-slate-50 px-2 py-1.5">
                        <div class="text-slate-500">PID</div>
                        <div class="font-mono font-medium">{{ s.pid }}</div>
                    </div>
                    <div class="rounded bg-slate-50 px-2 py-1.5">
                        <div class="text-slate-500">Bellek</div>
                        <div class="font-medium">{{ s.memory_mb }} MB</div>
                    </div>
                    <div class="rounded bg-slate-50 px-2 py-1.5">
                        <div class="text-slate-500">Uptime</div>
                        <div class="font-medium">{{ s.uptime }}</div>
                    </div>
                </div>

                <!-- Action buttons -->
                <div class="mt-3 flex flex-wrap gap-1">
                    <button v-if="s.status === 'running'" @click="reload(s)"
                            class="inline-flex items-center gap-1 rounded border border-emerald-300 bg-emerald-50 px-2 py-1 text-xs font-medium text-emerald-700 hover:bg-emerald-100"
                            title="Graceful reload — kesintisiz yeniden yükle">
                        <ArrowPathIcon class="h-3 w-3" /> Reload
                    </button>
                    <button v-if="s.status === 'running'" @click="restart(s)"
                            class="inline-flex items-center gap-1 rounded border border-amber-300 bg-amber-50 px-2 py-1 text-xs font-medium text-amber-700 hover:bg-amber-100"
                            title="Hard restart — kısa kesinti yaratır">
                        <ArrowPathIcon class="h-3 w-3" /> Restart
                    </button>
                    <button v-if="s.status === 'running'" @click="stop(s)"
                            class="inline-flex items-center gap-1 rounded border border-red-300 bg-white px-2 py-1 text-xs font-medium text-red-700 hover:bg-red-50">
                        <StopIcon class="h-3 w-3" /> Stop
                    </button>
                    <button v-else @click="start(s)"
                            class="inline-flex items-center gap-1 rounded border border-emerald-300 bg-emerald-50 px-2 py-1 text-xs font-medium text-emerald-700 hover:bg-emerald-100">
                        <PlayIcon class="h-3 w-3" /> Start
                    </button>
                    <Link :href="route('admin.services.logs', s.unit)"
                          class="inline-flex items-center gap-1 rounded border border-slate-300 bg-white px-2 py-1 text-xs font-medium text-slate-700 hover:bg-slate-50">
                        <DocumentTextIcon class="h-3 w-3" /> Loglar
                    </Link>
                </div>
            </div>
        </div>

        <div v-if="filtered.length === 0" class="rounded-xl border border-dashed border-slate-300 bg-white p-12 text-center">
            <p class="text-sm text-slate-500">Filtreyle eşleşen servis bulunamadı.</p>
        </div>
    </AdminLayout>
</template>
