<script setup>
import { ref, computed } from 'vue'
import { Head, router, usePage } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    PlusIcon,
    PencilSquareIcon,
    TrashIcon,
    PlayIcon,
    CheckCircleIcon,
    ExclamationCircleIcon,
    ExclamationTriangleIcon,
    WrenchScrewdriverIcon,
    SignalIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    components:      { type: Array,  default: () => [] },
    stats:           { type: Object, default: () => ({}) },
    activeIncidents: { type: Number, default: 0 },
})

const page  = usePage()
const flash = computed(() => page.props.flash ?? {})

// ── New / edit modal ─────────────────────────────────────────────────────────
const defaultForm = () => ({
    name: '', slug: '', description: '', category: 'infrastructure',
    check_type: 'http', endpoint: '', expected_status_code: 200,
    expected_response_substring: '', check_interval_seconds: 60,
    timeout_seconds: 10, display_order: 0, public: true,
})

const modal    = ref(false)
const editing  = ref(null)  // null = create, else StatusComponent
const form     = ref(defaultForm())
const formErr  = ref({})
const saving   = ref(false)

const openCreate = () => {
    editing.value = null
    form.value    = defaultForm()
    formErr.value = {}
    modal.value   = true
}

const openEdit = (c) => {
    editing.value = c
    form.value    = { ...c }
    formErr.value = {}
    modal.value   = true
}

const closeModal = () => { modal.value = false }

const saveComponent = () => {
    saving.value = true
    const url    = editing.value
        ? route('admin.status.components.update', editing.value.id)
        : route('admin.status.components.store')
    const method = editing.value ? 'patch' : 'post'

    router[method](url, form.value, {
        onSuccess: () => { modal.value = false; saving.value = false },
        onError:   (e) => { formErr.value = e; saving.value = false },
    })
}

// ── Delete ───────────────────────────────────────────────────────────────────
const confirmDelete = async (c) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `"${c.name}" bileşenini silmek istediğinize emin misiniz? Tüm check geçmişi de silinir.`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('admin.status.components.destroy', c.id))
}

// ── Run check ────────────────────────────────────────────────────────────────
const checking = ref(null)
const runCheck = (c) => {
    checking.value = c.id
    router.post(route('admin.status.components.check', c.id), {}, {
        onFinish: () => { checking.value = null },
    })
}

// ── Status display ───────────────────────────────────────────────────────────
const statusBadge = (status) => ({
    operational:    { label: 'Operasyonel',   cls: 'bg-emerald-100 text-emerald-700' },
    degraded:       { label: 'Yavaşlama',     cls: 'bg-yellow-100  text-yellow-700' },
    partial_outage: { label: 'Kısmi Kesinti', cls: 'bg-orange-100  text-orange-700' },
    major_outage:   { label: 'Büyük Kesinti', cls: 'bg-red-100     text-red-700' },
    maintenance:    { label: 'Bakımda',        cls: 'bg-blue-100    text-blue-700' },
}[status] ?? { label: status, cls: 'bg-gray-100 text-gray-600' })

const categories  = ['infrastructure', 'customer-facing', 'internal']
const checkTypes  = ['http', 'tcp', 'ping', 'dns', 'cmd', 'manual']
</script>

<template>
    <Head title="Sistem Durumu — Admin" />

    <AdminLayout>
        <template #header>
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-xl font-bold text-slate-900">Sistem Durumu</h1>
                    <p class="mt-0.5 text-sm text-slate-500">Servis bileşenlerini ve kontrolleri yönetin.</p>
                </div>
                <div class="flex items-center gap-2">
                    <a :href="route('admin.status.incidents')"
                       class="relative inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
                        Olaylar
                        <span v-if="activeIncidents > 0"
                              class="absolute -top-1.5 -right-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-red-500 text-[10px] font-bold text-white">
                            {{ activeIncidents }}
                        </span>
                    </a>
                    <a :href="route('admin.status.maintenance')"
                       class="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
                        <WrenchScrewdriverIcon class="h-4 w-4" />
                        Bakım
                    </a>
                    <a :href="route('status.index')" target="_blank"
                       class="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
                        <SignalIcon class="h-4 w-4" />
                        Herkese Açık Sayfa
                    </a>
                    <button @click="openCreate"
                            class="inline-flex items-center gap-2 rounded-lg bg-slate-900 px-3 py-2 text-sm font-medium text-white hover:bg-slate-700">
                        <PlusIcon class="h-4 w-4" />
                        Bileşen Ekle
                    </button>
                </div>
            </div>
        </template>

        <!-- Flash -->
        <div v-if="flash.success" class="mb-4 rounded-lg bg-emerald-50 border border-emerald-200 px-4 py-3 text-sm text-emerald-700">
            {{ flash.success }}
        </div>
        <div v-if="flash.error" class="mb-4 rounded-lg bg-red-50 border border-red-200 px-4 py-3 text-sm text-red-700">
            {{ flash.error }}
        </div>

        <!-- Stats bar -->
        <div class="mb-6 grid grid-cols-2 gap-4 sm:grid-cols-4">
            <div class="rounded-xl border border-slate-200 bg-white p-4 text-center">
                <p class="text-2xl font-bold text-slate-900">{{ stats.total }}</p>
                <p class="text-xs text-slate-500 mt-1">Toplam</p>
            </div>
            <div class="rounded-xl border border-emerald-200 bg-emerald-50 p-4 text-center">
                <p class="text-2xl font-bold text-emerald-700">{{ stats.operational }}</p>
                <p class="text-xs text-emerald-600 mt-1">Operasyonel</p>
            </div>
            <div class="rounded-xl border border-red-200 bg-red-50 p-4 text-center">
                <p class="text-2xl font-bold text-red-700">{{ stats.degraded }}</p>
                <p class="text-xs text-red-600 mt-1">Sorunlu</p>
            </div>
            <div class="rounded-xl border border-blue-200 bg-blue-50 p-4 text-center">
                <p class="text-2xl font-bold text-blue-700">{{ stats.maintenance }}</p>
                <p class="text-xs text-blue-600 mt-1">Bakımda</p>
            </div>
        </div>

        <!-- Components table -->
        <div class="overflow-hidden rounded-xl border border-slate-200 bg-white">
            <table class="min-w-full divide-y divide-slate-200 text-sm">
                <thead class="bg-slate-50">
                    <tr>
                        <th class="px-4 py-3 text-left font-semibold text-slate-700">Bileşen</th>
                        <th class="px-4 py-3 text-left font-semibold text-slate-700">Tip</th>
                        <th class="px-4 py-3 text-left font-semibold text-slate-700">Durum</th>
                        <th class="px-4 py-3 text-left font-semibold text-slate-700">Uptime 24s</th>
                        <th class="px-4 py-3 text-left font-semibold text-slate-700">Son Kontrol</th>
                        <th class="px-4 py-3 text-right font-semibold text-slate-700">İşlem</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <tr v-for="c in components" :key="c.id" class="hover:bg-slate-50/50">
                        <td class="px-4 py-3">
                            <div class="font-medium text-slate-900">{{ c.name }}</div>
                            <div class="text-xs text-slate-400 mt-0.5 font-mono">{{ c.endpoint }}</div>
                        </td>
                        <td class="px-4 py-3">
                            <span class="rounded-md bg-slate-100 px-2 py-0.5 text-xs font-mono font-medium text-slate-700 uppercase">
                                {{ c.check_type }}
                            </span>
                        </td>
                        <td class="px-4 py-3">
                            <span :class="['rounded-full px-2.5 py-0.5 text-xs font-medium', statusBadge(c.current_status).cls]">
                                {{ statusBadge(c.current_status).label }}
                            </span>
                        </td>
                        <td class="px-4 py-3 tabular-nums">
                            <span :class="[
                                'font-semibold',
                                c.uptime_24h >= 99 ? 'text-emerald-600' :
                                c.uptime_24h >= 95 ? 'text-yellow-600' : 'text-red-600'
                            ]">%{{ c.uptime_24h }}</span>
                        </td>
                        <td class="px-4 py-3 text-xs text-slate-500">
                            {{ c.last_check_at ? new Date(c.last_check_at).toLocaleString('tr-TR') : '—' }}
                        </td>
                        <td class="px-4 py-3 text-right">
                            <div class="inline-flex items-center gap-1">
                                <button
                                    @click="runCheck(c)"
                                    :disabled="checking === c.id || c.check_type === 'manual'"
                                    title="Şimdi Kontrol Et"
                                    class="rounded p-1 text-slate-500 hover:bg-slate-100 hover:text-slate-900 disabled:opacity-40">
                                    <PlayIcon v-if="checking !== c.id" class="h-4 w-4" />
                                    <svg v-else class="h-4 w-4 animate-spin" viewBox="0 0 24 24" fill="none">
                                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
                                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/>
                                    </svg>
                                </button>
                                <button @click="openEdit(c)" title="Düzenle"
                                        class="rounded p-1 text-slate-500 hover:bg-slate-100 hover:text-slate-900">
                                    <PencilSquareIcon class="h-4 w-4" />
                                </button>
                                <button @click="confirmDelete(c)" title="Sil"
                                        class="rounded p-1 text-red-400 hover:bg-red-50 hover:text-red-600">
                                    <TrashIcon class="h-4 w-4" />
                                </button>
                            </div>
                        </td>
                    </tr>
                    <tr v-if="!components.length">
                        <td colspan="6" class="px-4 py-10 text-center text-sm text-slate-400">
                            Henüz bileşen eklenmemiş.
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- ── Create / Edit Modal ───────────────────────────────────────── -->
        <Teleport to="body">
            <div v-if="modal" class="fixed inset-0 z-50 flex items-center justify-center p-4">
                <div class="absolute inset-0 bg-black/40 backdrop-blur-sm" @click="closeModal"></div>
                <div class="relative w-full max-w-xl rounded-2xl bg-white shadow-2xl overflow-y-auto max-h-[90vh]">
                    <div class="px-6 py-5 border-b border-slate-200 flex items-center justify-between">
                        <h2 class="text-base font-semibold text-slate-900">
                            {{ editing ? 'Bileşeni Düzenle' : 'Yeni Bileşen Ekle' }}
                        </h2>
                        <button @click="closeModal" class="text-slate-400 hover:text-slate-600">
                            <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                            </svg>
                        </button>
                    </div>
                    <form @submit.prevent="saveComponent" class="px-6 py-5 space-y-4">
                        <div class="grid grid-cols-2 gap-4">
                            <div class="col-span-2">
                                <label class="block text-xs font-medium text-slate-700 mb-1">Ad *</label>
                                <input v-model="form.name" required type="text"
                                       class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-slate-500 focus:outline-none" />
                                <p v-if="formErr.name" class="mt-1 text-xs text-red-500">{{ formErr.name }}</p>
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-slate-700 mb-1">Slug</label>
                                <input v-model="form.slug" type="text" placeholder="otomatik"
                                       class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-slate-500 focus:outline-none" />
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-slate-700 mb-1">Kategori *</label>
                                <select v-model="form.category"
                                        class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-slate-500 focus:outline-none">
                                    <option value="infrastructure">Altyapı</option>
                                    <option value="customer-facing">Müşteri Servisi</option>
                                    <option value="internal">Dahili</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-slate-700 mb-1">Kontrol Tipi *</label>
                                <select v-model="form.check_type"
                                        class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-slate-500 focus:outline-none">
                                    <option v-for="t in checkTypes" :key="t" :value="t">{{ t.toUpperCase() }}</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-slate-700 mb-1">Endpoint</label>
                                <input v-model="form.endpoint" type="text" placeholder="https://... veya host:port"
                                       class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-slate-500 focus:outline-none" />
                            </div>
                            <div v-if="form.check_type === 'http'">
                                <label class="block text-xs font-medium text-slate-700 mb-1">Beklenen HTTP Kodu</label>
                                <input v-model.number="form.expected_status_code" type="number" min="100" max="599"
                                       class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-slate-500 focus:outline-none" />
                            </div>
                            <div v-if="form.check_type === 'http'" class="col-span-2">
                                <label class="block text-xs font-medium text-slate-700 mb-1">Yanıtta Aranan Metin</label>
                                <input v-model="form.expected_response_substring" type="text" placeholder="İsteğe bağlı"
                                       class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-slate-500 focus:outline-none" />
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-slate-700 mb-1">Kontrol Aralığı (sn)</label>
                                <input v-model.number="form.check_interval_seconds" type="number" min="10" max="3600"
                                       class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-slate-500 focus:outline-none" />
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-slate-700 mb-1">Zaman Aşımı (sn)</label>
                                <input v-model.number="form.timeout_seconds" type="number" min="1" max="60"
                                       class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-slate-500 focus:outline-none" />
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-slate-700 mb-1">Sıralama</label>
                                <input v-model.number="form.display_order" type="number" min="0"
                                       class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-slate-500 focus:outline-none" />
                            </div>
                            <div class="flex items-center gap-2 pt-4">
                                <input v-model="form.public" id="public" type="checkbox"
                                       class="h-4 w-4 rounded border-slate-300" />
                                <label for="public" class="text-sm text-slate-700">Herkese Açık Sayfada Göster</label>
                            </div>
                        </div>
                        <div class="col-span-2">
                            <label class="block text-xs font-medium text-slate-700 mb-1">Açıklama</label>
                            <textarea v-model="form.description" rows="2"
                                      class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-slate-500 focus:outline-none"></textarea>
                        </div>

                        <div class="flex justify-end gap-3 pt-2">
                            <button type="button" @click="closeModal"
                                    class="rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
                                İptal
                            </button>
                            <button type="submit" :disabled="saving"
                                    class="rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-700 disabled:opacity-50">
                                {{ saving ? 'Kaydediliyor…' : (editing ? 'Güncelle' : 'Ekle') }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </Teleport>
    </AdminLayout>
</template>
