<script setup>
import { ref, computed } from 'vue'
import { Head, router, usePage } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    PlusIcon,
    CheckCircleIcon,
    ChevronDownIcon,
    PaperAirplaneIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    incidents:  { type: Object, default: () => ({}) },  // paginated
    components: { type: Array,  default: () => [] },
})

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

// ── Create incident modal ────────────────────────────────────────────────────
const defaultForm = () => ({
    title: '', description: '', impact: 'minor', status: 'investigating',
    affected_component_ids: [], public: true, started_at: null,
})

const createModal = ref(false)
const createForm  = ref(defaultForm())
const createErr   = ref({})
const creating    = ref(false)

const openCreate = () => {
    createForm.value = defaultForm()
    createErr.value  = {}
    createModal.value = true
}

const submitCreate = () => {
    creating.value = true
    router.post(route('admin.status.incidents.store'), createForm.value, {
        onSuccess: () => { createModal.value = false; creating.value = false },
        onError:   (e) => { createErr.value  = e;    creating.value = false },
    })
}

// ── Update modal ─────────────────────────────────────────────────────────────
const updateModal    = ref(false)
const selectedIncident = ref(null)
const updateForm     = ref({ status: 'monitoring', message: '' })
const updateErr      = ref({})
const posting        = ref(false)

const openUpdate = (incident) => {
    selectedIncident.value = incident
    updateForm.value       = { status: incident.status, message: '' }
    updateErr.value        = {}
    updateModal.value      = true
}

const submitUpdate = () => {
    posting.value = true
    router.post(
        route('admin.status.incidents.update.post', selectedIncident.value.id),
        updateForm.value,
        {
            onSuccess: () => { updateModal.value = false; posting.value = false },
            onError:   (e) => { updateErr.value = e;     posting.value = false },
        }
    )
}

// ── Resolve ──────────────────────────────────────────────────────────────────
const resolving = ref(null)
const resolveIncident = async (incident) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `"${incident.title}" olayını çözüldü olarak işaretle?`,
        variant: 'warning',
        confirmText: 'Onayla',
        cancelText: 'İptal',
    })
    if (!ok) return
    resolving.value = incident.id
    router.post(route('admin.status.incidents.resolve', incident.id), {}, {
        onFinish: () => { resolving.value = null },
    })
}

// ── Expanded details ─────────────────────────────────────────────────────────
const expanded = ref(new Set())
const toggleExpand = (id) => {
    if (expanded.value.has(id)) expanded.value.delete(id)
    else expanded.value.add(id)
}

// ── Helpers ──────────────────────────────────────────────────────────────────
const impactCls = (impact) => ({
    none:     'bg-gray-100  text-gray-600',
    minor:    'bg-yellow-100 text-yellow-700',
    major:    'bg-orange-100 text-orange-700',
    critical: 'bg-red-100   text-red-700',
}[impact] ?? 'bg-gray-100 text-gray-600')

const impactLabel = (i) => ({ none:'Yok', minor:'Küçük', major:'Büyük', critical:'Kritik' }[i] ?? i)

const statusCls = (s) => ({
    investigating: 'bg-orange-100 text-orange-700',
    identified:    'bg-yellow-100 text-yellow-700',
    monitoring:    'bg-blue-100   text-blue-700',
    resolved:      'bg-emerald-100 text-emerald-700',
    postmortem:    'bg-slate-100  text-slate-700',
}[s] ?? 'bg-gray-100 text-gray-600')

const statusLabel = (s) => ({
    investigating: 'İnceleniyor',
    identified:    'Tespit Edildi',
    monitoring:    'İzleniyor',
    resolved:      'Çözüldü',
    postmortem:    'Olay Raporu',
}[s] ?? s)

const fmt = (iso) => iso ? new Date(iso).toLocaleString('tr-TR') : '—'

const allStatuses = ['investigating', 'identified', 'monitoring', 'resolved', 'postmortem']
const allImpacts  = ['none', 'minor', 'major', 'critical']
</script>

<template>
    <Head title="Olaylar — Admin Status" />

    <AdminLayout>
        <template #header>
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-xl font-bold text-slate-900">Servis Olayları</h1>
                    <p class="mt-0.5 text-sm text-slate-500">Aktif ve geçmiş olayları yönetin.</p>
                </div>
                <div class="flex items-center gap-2">
                    <a :href="route('admin.status.index')"
                       class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
                        ← Bileşenler
                    </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" />
                        Olay Oluştur
                    </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>

        <!-- Incidents list -->
        <div class="space-y-3">
            <div v-for="incident in incidents.data" :key="incident.id"
                 class="rounded-xl border border-slate-200 bg-white overflow-hidden">
                <!-- Header row -->
                <div class="px-5 py-4 flex flex-wrap items-center justify-between gap-3">
                    <div class="flex items-center gap-3">
                        <button @click="toggleExpand(incident.id)" class="text-slate-400 hover:text-slate-600">
                            <ChevronDownIcon :class="['h-4 w-4 transition-transform', expanded.has(incident.id) ? 'rotate-180' : '']" />
                        </button>
                        <div>
                            <h3 class="font-semibold text-slate-900 text-sm">{{ incident.title }}</h3>
                            <p class="text-xs text-slate-400 mt-0.5">Başladı: {{ fmt(incident.started_at) }}</p>
                        </div>
                    </div>
                    <div class="flex items-center gap-2">
                        <span :class="['rounded-full px-2.5 py-0.5 text-xs font-medium', impactCls(incident.impact)]">
                            {{ impactLabel(incident.impact) }}
                        </span>
                        <span :class="['rounded-full px-2.5 py-0.5 text-xs font-medium', statusCls(incident.status)]">
                            {{ statusLabel(incident.status) }}
                        </span>
                        <button v-if="incident.status !== 'resolved'"
                                @click="openUpdate(incident)"
                                class="inline-flex items-center gap-1 rounded-lg border border-slate-200 px-2.5 py-1 text-xs font-medium text-slate-700 hover:bg-slate-50">
                            <PaperAirplaneIcon class="h-3.5 w-3.5" />
                            Güncelleme Ekle
                        </button>
                        <button v-if="!['resolved','postmortem'].includes(incident.status)"
                                @click="resolveIncident(incident)"
                                :disabled="resolving === incident.id"
                                class="inline-flex items-center gap-1 rounded-lg border border-emerald-200 bg-emerald-50 px-2.5 py-1 text-xs font-medium text-emerald-700 hover:bg-emerald-100 disabled:opacity-40">
                            <CheckCircleIcon class="h-3.5 w-3.5" />
                            Çöz
                        </button>
                    </div>
                </div>

                <!-- Expanded updates timeline -->
                <div v-if="expanded.has(incident.id)" class="border-t border-slate-100 px-5 py-4 space-y-3">
                    <p v-if="incident.description" class="text-sm text-slate-600 mb-3">{{ incident.description }}</p>

                    <div v-if="incident.updates?.length" class="space-y-2">
                        <div v-for="upd in incident.updates" :key="upd.id"
                             class="flex gap-3 text-sm">
                            <div class="mt-1.5 h-2 w-2 shrink-0 rounded-full bg-slate-400"></div>
                            <div>
                                <span class="font-medium text-slate-700">{{ statusLabel(upd.status) }}</span>
                                <span class="mx-1 text-slate-300">—</span>
                                <span class="text-slate-600">{{ upd.message }}</span>
                                <p class="text-xs text-slate-400 mt-0.5">{{ fmt(upd.posted_at) }}</p>
                            </div>
                        </div>
                    </div>
                    <p v-else class="text-xs text-slate-400">Güncelleme yok.</p>

                    <div v-if="incident.resolved_at" class="mt-3 text-xs text-slate-500">
                        Çözüldü: {{ fmt(incident.resolved_at) }}
                    </div>
                </div>
            </div>

            <p v-if="!incidents.data?.length" class="py-12 text-center text-sm text-slate-400">
                Henüz olay oluşturulmamış.
            </p>
        </div>

        <!-- Pagination -->
        <div v-if="incidents.last_page > 1" class="mt-6 flex justify-center gap-2 text-sm">
            <a v-for="link in incidents.links" :key="link.label"
               :href="link.url ?? '#'"
               v-html="link.label"
               :class="[
                   'rounded-md px-3 py-1.5 border',
                   link.active ? 'border-slate-900 bg-slate-900 text-white' : 'border-slate-200 text-slate-600 hover:bg-slate-50',
                   !link.url && 'opacity-40 pointer-events-none',
               ]"
            ></a>
        </div>

        <!-- ── Create modal ──────────────────────────────────────────────── -->
        <Teleport to="body">
            <div v-if="createModal" 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="createModal = false"></div>
                <div class="relative w-full max-w-lg 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">Yeni Olay</h2>
                        <button @click="createModal = false" 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="submitCreate" class="px-6 py-5 space-y-4">
                        <div>
                            <label class="block text-xs font-medium text-slate-700 mb-1">Başlık *</label>
                            <input v-model="createForm.title" required type="text"
                                   class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:border-slate-500" />
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-slate-700 mb-1">Açıklama</label>
                            <textarea v-model="createForm.description" rows="3"
                                      class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:border-slate-500"></textarea>
                        </div>
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-medium text-slate-700 mb-1">Etki</label>
                                <select v-model="createForm.impact"
                                        class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:border-slate-500">
                                    <option v-for="i in allImpacts" :key="i" :value="i">{{ impactLabel(i) }}</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-slate-700 mb-1">Başlangıç Durumu</label>
                                <select v-model="createForm.status"
                                        class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:border-slate-500">
                                    <option v-for="s in allStatuses" :key="s" :value="s">{{ statusLabel(s) }}</option>
                                </select>
                            </div>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-slate-700 mb-1">Etkilenen Bileşenler</label>
                            <div class="grid grid-cols-2 gap-1.5 max-h-32 overflow-y-auto rounded-lg border border-slate-200 p-2">
                                <label v-for="c in components" :key="c.id" class="flex items-center gap-2 text-sm cursor-pointer">
                                    <input type="checkbox" :value="c.id" v-model="createForm.affected_component_ids"
                                           class="h-3.5 w-3.5 rounded border-slate-300" />
                                    {{ c.name }}
                                </label>
                            </div>
                        </div>
                        <div class="flex items-center gap-2">
                            <input v-model="createForm.public" id="pub" type="checkbox" class="h-4 w-4 rounded border-slate-300" />
                            <label for="pub" class="text-sm text-slate-700">Herkese Açık Sayfada Göster</label>
                        </div>
                        <div class="flex justify-end gap-3 pt-2">
                            <button type="button" @click="createModal = false"
                                    class="rounded-lg border border-slate-200 px-4 py-2 text-sm text-slate-700 hover:bg-slate-50">
                                İptal
                            </button>
                            <button type="submit" :disabled="creating"
                                    class="rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-700 disabled:opacity-50">
                                {{ creating ? 'Oluşturuluyor…' : 'Olay Oluştur' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </Teleport>

        <!-- ── Update modal ──────────────────────────────────────────────── -->
        <Teleport to="body">
            <div v-if="updateModal" 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="updateModal = false"></div>
                <div class="relative w-full max-w-md rounded-2xl bg-white shadow-2xl">
                    <div class="px-6 py-5 border-b border-slate-200 flex items-center justify-between">
                        <h2 class="text-base font-semibold">Olay Güncellemesi</h2>
                        <button @click="updateModal = false" 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="submitUpdate" class="px-6 py-5 space-y-4">
                        <p class="text-sm text-slate-600 font-medium">{{ selectedIncident?.title }}</p>
                        <div>
                            <label class="block text-xs font-medium text-slate-700 mb-1">Yeni Durum</label>
                            <select v-model="updateForm.status"
                                    class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:border-slate-500">
                                <option v-for="s in allStatuses" :key="s" :value="s">{{ statusLabel(s) }}</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-slate-700 mb-1">Güncelleme Mesajı *</label>
                            <textarea v-model="updateForm.message" required rows="3" placeholder="Kullanıcılara gösterilecek mesaj…"
                                      class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:border-slate-500"></textarea>
                            <p v-if="updateErr.message" class="mt-1 text-xs text-red-500">{{ updateErr.message }}</p>
                        </div>
                        <div class="flex justify-end gap-3">
                            <button type="button" @click="updateModal = false"
                                    class="rounded-lg border border-slate-200 px-4 py-2 text-sm text-slate-700 hover:bg-slate-50">
                                İptal
                            </button>
                            <button type="submit" :disabled="posting"
                                    class="rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-700 disabled:opacity-50">
                                {{ posting ? 'Gönderiliyor…' : 'Yayınla' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </Teleport>
    </AdminLayout>
</template>
