<script setup>
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { Head, Link, router, useForm } from '@inertiajs/vue3'
import { computed, ref } from 'vue'
import {
    ArrowLeftIcon, ArrowPathIcon, CheckCircleIcon, ExclamationTriangleIcon,
    XCircleIcon, ServerStackIcon, SignalIcon, GlobeAltIcon, LockClosedIcon,
    SparklesIcon, InformationCircleIcon, HeartIcon, PaperAirplaneIcon,
    XMarkIcon, WrenchScrewdriverIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    report: { type: Object, required: true },
    is_windows_dev: { type: Boolean, default: false },
})

const showTestModal = ref(false)
const testForm = useForm({ to: '' })

function submitTest() {
    testForm.post(route('admin.mail.health.test-mail'), {
        preserveScroll: true,
        onSuccess: () => { showTestModal.value = false; testForm.reset() },
    })
}

const showFixModal = ref(false)
const fixForm = useForm({ domain: '' })

function submitAutoFix() {
    fixForm.post(route('admin.mail.health.auto-fix'), {
        preserveScroll: true,
        onSuccess: () => {
            showFixModal.value = false
            fixForm.reset()
            // Refresh report
            router.reload({ only: ['report'] })
        },
    })
}

const iconMap = {
    ServerStackIcon, SignalIcon, GlobeAltIcon, LockClosedIcon, CheckCircleIcon,
}

const summary = computed(() => props.report?.summary || {})

const healthColor = computed(() => {
    const h = summary.value.health
    if (h === 'healthy') return { bg: 'from-emerald-500 to-teal-500', text: 'text-emerald-700 dark:text-emerald-400', label: 'Sağlıklı', icon: CheckCircleIcon }
    if (h === 'warning') return { bg: 'from-amber-500 to-orange-500', text: 'text-amber-700 dark:text-amber-400', label: 'Uyarılar Var', icon: ExclamationTriangleIcon }
    return { bg: 'from-red-500 to-rose-500', text: 'text-red-700 dark:text-red-400', label: 'Kritik Sorunlar', icon: XCircleIcon }
})

function statusBadge(status) {
    return {
        pass: { color: 'emerald', icon: CheckCircleIcon, label: 'OK' },
        warn: { color: 'amber', icon: ExclamationTriangleIcon, label: 'UYARI' },
        fail: { color: 'red', icon: XCircleIcon, label: 'HATA' },
    }[status] || { color: 'slate', icon: InformationCircleIcon, label: '?' }
}

function refresh() {
    router.post(route('admin.mail.health.refresh'), {}, {
        preserveScroll: true,
        onSuccess: () => router.reload({ only: ['report'] }),
    })
}

function fmtDate(iso) {
    if (!iso) return '—'
    return new Date(iso).toLocaleString('tr-TR', { dateStyle: 'short', timeStyle: 'medium' })
}
</script>

<template>
    <Head title="Mail Stack Sağlık Kontrolü" />
    <AdminLayout>
        <template #header>
            <Link :href="route('admin.mail.dashboard')" class="text-slate-400 hover:text-indigo-600 mr-2">
                <ArrowLeftIcon class="h-5 w-5" />
            </Link>
            Mail Stack Sağlık Kontrolü
        </template>

        <!-- Windows dev banner -->
        <div v-if="is_windows_dev"
             class="mb-6 rounded-xl border border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-950/30 p-4 flex items-start gap-3">
            <InformationCircleIcon class="h-5 w-5 text-blue-600 dark:text-blue-400 shrink-0 mt-0.5" />
            <div>
                <p class="text-sm font-semibold text-blue-900 dark:text-blue-200">Geliştirme ortamı (Windows)</p>
                <p class="mt-0.5 text-sm text-blue-800 dark:text-blue-300">
                    Linux mail servisleri Windows'ta yok — port testleri ve service status fail döner. Production AlmaLinux'ta gerçek sonuç görürsünüz.
                </p>
            </div>
        </div>

        <!-- Overall Health üst kart -->
        <div :class="['rounded-2xl p-px shadow-2xl', `bg-gradient-to-br ${healthColor.bg}`]">
            <div class="rounded-2xl bg-white dark:bg-slate-900 p-6 lg:p-8">
                <div class="flex items-start justify-between flex-wrap gap-6">
                    <div class="flex items-start gap-4">
                        <div :class="['rounded-xl p-3 shadow-lg', `bg-gradient-to-br ${healthColor.bg}`]">
                            <component :is="healthColor.icon" class="h-7 w-7 text-white" />
                        </div>
                        <div>
                            <p class="text-xs uppercase tracking-widest font-semibold text-slate-500">Genel Sağlık</p>
                            <h2 class="mt-1 text-3xl font-bold text-slate-900 dark:text-white">{{ healthColor.label }}</h2>
                            <div class="mt-2 flex items-center gap-4 flex-wrap text-sm">
                                <span class="flex items-center gap-1.5">
                                    <CheckCircleIcon class="h-4 w-4 text-emerald-500" />
                                    <strong class="text-emerald-700 dark:text-emerald-400">{{ summary.passed }}</strong>
                                    <span class="text-slate-500">geçti</span>
                                </span>
                                <span class="flex items-center gap-1.5">
                                    <ExclamationTriangleIcon class="h-4 w-4 text-amber-500" />
                                    <strong class="text-amber-700 dark:text-amber-400">{{ summary.warnings }}</strong>
                                    <span class="text-slate-500">uyarı</span>
                                </span>
                                <span class="flex items-center gap-1.5">
                                    <XCircleIcon class="h-4 w-4 text-red-500" />
                                    <strong class="text-red-700 dark:text-red-400">{{ summary.failures }}</strong>
                                    <span class="text-slate-500">hata</span>
                                </span>
                                <span class="text-slate-400">/ Toplam: <strong>{{ summary.total }}</strong> kontrol</span>
                            </div>
                            <p class="mt-2 text-xs text-slate-400">
                                Son kontrol: {{ fmtDate(report.checked_at) }} · Hostname:
                                <code class="font-mono">{{ report.mail_host }}</code>
                            </p>
                        </div>
                    </div>

                    <div class="flex items-center gap-3">
                        <!-- Score circle -->
                        <div class="relative h-20 w-20">
                            <svg class="h-20 w-20 transform -rotate-90">
                                <circle cx="40" cy="40" r="36" stroke="currentColor" stroke-width="8" fill="none" class="text-slate-200 dark:text-slate-700" />
                                <circle cx="40" cy="40" r="36" stroke="currentColor" stroke-width="8" fill="none"
                                    :stroke-dasharray="`${(summary.score / 100) * 226} 226`"
                                    :class="summary.health === 'healthy' ? 'text-emerald-500' : summary.health === 'warning' ? 'text-amber-500' : 'text-red-500'" />
                            </svg>
                            <div class="absolute inset-0 flex items-center justify-center">
                                <span class="text-xl font-bold text-slate-900 dark:text-white">{{ summary.score }}%</span>
                            </div>
                        </div>

                        <button @click="showFixModal = true" type="button"
                                class="inline-flex items-center gap-1.5 rounded-lg bg-amber-600 px-4 py-2 text-sm font-semibold text-white hover:bg-amber-700"
                                title="Eksik DNS kayıtlarını PowerDNS'e otomatik ekle">
                            <WrenchScrewdriverIcon class="h-4 w-4" />
                            DNS Düzelt
                        </button>
                        <button @click="showTestModal = true" type="button"
                                class="inline-flex items-center gap-1.5 rounded-lg bg-emerald-600 px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-700">
                            <PaperAirplaneIcon class="h-4 w-4" />
                            Test Mail
                        </button>
                        <button @click="refresh" type="button"
                                class="inline-flex items-center gap-1.5 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-semibold text-white hover:bg-indigo-700">
                            <ArrowPathIcon class="h-4 w-4" />
                            Yenile
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Test Mail Modal -->
        <div v-if="showTestModal"
             class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 backdrop-blur-sm p-4">
            <div class="w-full max-w-md rounded-2xl bg-white dark:bg-slate-800 p-6 shadow-2xl">
                <div class="mb-5 flex items-center justify-between">
                    <h3 class="text-lg font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
                        <PaperAirplaneIcon class="h-5 w-5 text-emerald-500" />
                        Uçtan Uca Mail Test
                    </h3>
                    <button @click="showTestModal = false" type="button" class="text-slate-400 hover:text-slate-600">
                        <XMarkIcon class="h-5 w-5" />
                    </button>
                </div>
                <p class="text-sm text-slate-500 dark:text-slate-400 mb-4">
                    Mail stack'in uçtan uca çalışıp çalışmadığını test eder. Aşağıdaki adrese test maili gönderilecek.
                    Maili 1-2 dakika içinde alıp DKIM/SPF/DMARC sonuçlarını incelemenizi öneririz.
                </p>
                <form @submit.prevent="submitTest" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Alıcı E-posta</label>
                        <input v-model="testForm.to" type="email" required
                               class="w-full rounded-lg border border-slate-300 dark:border-slate-600 dark:bg-slate-900 px-3 py-2 text-sm"
                               placeholder="admin@externaldomain.com" />
                        <p class="mt-1 text-xs text-slate-500">
                            Tercihen Gmail/Outlook/Yandex gibi harici provider — DKIM/DMARC sonuçlarını header'da görebilirsiniz.
                        </p>
                    </div>
                    <div class="flex justify-end gap-2 pt-2">
                        <button type="button" @click="showTestModal = false"
                                class="rounded-lg border border-slate-300 dark:border-slate-600 px-4 py-2 text-sm">
                            İptal
                        </button>
                        <button type="submit" :disabled="testForm.processing"
                                class="rounded-lg bg-emerald-600 px-5 py-2 text-sm font-semibold text-white hover:bg-emerald-700 disabled:opacity-50">
                            <span v-if="testForm.processing">Gönderiliyor...</span>
                            <span v-else>Test Mail Gönder</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- DNS Auto-Fix Modal -->
        <div v-if="showFixModal"
             class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 backdrop-blur-sm p-4">
            <div class="w-full max-w-md rounded-2xl bg-white dark:bg-slate-800 p-6 shadow-2xl">
                <div class="mb-5 flex items-center justify-between">
                    <h3 class="text-lg font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
                        <WrenchScrewdriverIcon class="h-5 w-5 text-amber-500" />
                        DNS Kayıtlarını Otomatik Düzelt
                    </h3>
                    <button @click="showFixModal = false" type="button" class="text-slate-400 hover:text-slate-600">
                        <XMarkIcon class="h-5 w-5" />
                    </button>
                </div>
                <p class="text-sm text-slate-500 dark:text-slate-400 mb-4">
                    Eksik <strong>MX, SPF, DMARC ve DKIM</strong> kayıtlarını PowerDNS'e otomatik ekler. Mevcut kayıtlar atlanır.
                </p>
                <div class="mb-4 rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-950/30 p-3 text-xs text-amber-900 dark:text-amber-200">
                    <strong>Ön koşul:</strong> Domain için DNS zone önceden oluşturulmuş olmalı.
                    Bu sayfa kayıtları upsert eder — varolanı override etmez, sadece eksikleri ekler.
                </div>
                <form @submit.prevent="submitAutoFix" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                            Domain <span class="text-slate-400 text-xs">(boş = panel base domain)</span>
                        </label>
                        <input v-model="fixForm.domain" type="text"
                               class="w-full rounded-lg border border-slate-300 dark:border-slate-600 dark:bg-slate-900 px-3 py-2 font-mono text-sm"
                               :placeholder="report.hostname.replace(/^[^.]+\./, '')" />
                        <p class="mt-1 text-xs text-slate-500">
                            Hangi domain için DNS kayıtları eklensin? Boş bırakırsanız panelin base domain'i kullanılır.
                        </p>
                    </div>
                    <div class="flex justify-end gap-2 pt-2">
                        <button type="button" @click="showFixModal = false"
                                class="rounded-lg border border-slate-300 dark:border-slate-600 px-4 py-2 text-sm">
                            İptal
                        </button>
                        <button type="submit" :disabled="fixForm.processing"
                                class="rounded-lg bg-amber-600 px-5 py-2 text-sm font-semibold text-white hover:bg-amber-700 disabled:opacity-50 inline-flex items-center gap-1.5">
                            <WrenchScrewdriverIcon class="h-4 w-4" />
                            <span v-if="fixForm.processing">Ekleniyor...</span>
                            <span v-else>DNS Kayıtlarını Ekle</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Group cards -->
        <div class="mt-6 grid grid-cols-1 lg:grid-cols-2 gap-5">
            <div v-for="(group, key) in report.groups" :key="key"
                 class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 overflow-hidden">
                <div class="px-5 py-4 border-b border-slate-100 dark:border-slate-700 flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <component :is="iconMap[group.icon] || CheckCircleIcon" class="h-5 w-5 text-indigo-500" />
                        <h3 class="text-base font-semibold text-slate-900 dark:text-slate-100">{{ group.name }}</h3>
                    </div>
                    <span class="text-xs text-slate-500">{{ group.checks.length }} kontrol</span>
                </div>
                <ul class="divide-y divide-slate-100 dark:divide-slate-700">
                    <li v-for="(check, i) in group.checks" :key="i" class="px-5 py-3.5">
                        <div class="flex items-start gap-3">
                            <span :class="['inline-flex h-6 w-6 items-center justify-center rounded-full shrink-0 mt-0.5',
                                `bg-${statusBadge(check.status).color}-100 dark:bg-${statusBadge(check.status).color}-900/30`,
                                `text-${statusBadge(check.status).color}-600 dark:text-${statusBadge(check.status).color}-400`]">
                                <component :is="statusBadge(check.status).icon" class="h-3.5 w-3.5 stroke-2" />
                            </span>
                            <div class="flex-1 min-w-0">
                                <div class="flex items-baseline gap-2 flex-wrap">
                                    <p class="text-sm font-medium text-slate-900 dark:text-slate-100">{{ check.name }}</p>
                                    <span :class="['text-[10px] font-bold tracking-wider px-1.5 py-0.5 rounded',
                                        `bg-${statusBadge(check.status).color}-100 dark:bg-${statusBadge(check.status).color}-900/30`,
                                        `text-${statusBadge(check.status).color}-700 dark:text-${statusBadge(check.status).color}-400`]">
                                        {{ statusBadge(check.status).label }}
                                    </span>
                                </div>
                                <p :class="['mt-0.5 text-xs',
                                    `text-${statusBadge(check.status).color}-700 dark:text-${statusBadge(check.status).color}-400`]">
                                    {{ check.message }}
                                </p>
                                <p v-if="check.value" class="mt-1 text-xs font-mono text-slate-500 dark:text-slate-400 truncate">
                                    {{ check.value }}
                                </p>
                                <p v-if="check.hint" class="mt-1 text-xs text-slate-500 dark:text-slate-400 italic">
                                    💡 {{ check.hint }}
                                </p>
                            </div>
                        </div>
                    </li>
                </ul>
            </div>
        </div>

        <!-- Tips footer -->
        <div class="mt-6 rounded-xl border border-indigo-200 dark:border-indigo-800 bg-gradient-to-br from-indigo-50 to-purple-50 dark:from-indigo-950/30 dark:to-purple-950/30 p-5">
            <div class="flex items-start gap-3">
                <SparklesIcon class="h-5 w-5 text-indigo-600 dark:text-indigo-400 shrink-0 mt-0.5" />
                <div>
                    <h3 class="text-base font-semibold text-slate-900 dark:text-slate-100">Production Sağlık İpuçları</h3>
                    <ul class="mt-2 space-y-1.5 text-sm text-slate-700 dark:text-slate-300 list-disc list-inside">
                        <li><strong>PTR kaydı zorunlu:</strong> Hosting sağlayıcıdan IP için reverse DNS isteyin (mail.{{ report.hostname }})</li>
                        <li><strong>SPF + DKIM + DMARC:</strong> Gmail/Outlook bu 3'ünü ister, eksikse mailler spam'e düşer</li>
                        <li><strong>Let's Encrypt cert:</strong> Self-signed cert müşteri mail client'larında uyarı verir — production cert şart</li>
                        <li><strong>Port 25 outbound:</strong> Bazı bulut sağlayıcılar (AWS, GCP) varsayılan engeller — destek ile açtırın</li>
                        <li><strong>Rspamd web UI parolası:</strong> <code class="font-mono bg-white/60 dark:bg-slate-800/60 px-1 rounded">/etc/onoxsoft/rspamd.env</code> dosyasında</li>
                    </ul>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
