<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'
import {
    EnvelopeIcon,
    CheckCircleIcon,
    XCircleIcon,
    ExclamationTriangleIcon,
    InformationCircleIcon,
    ArrowPathIcon,
    BoltIcon,
    ServerIcon,
    ShieldExclamationIcon,
    GlobeAltIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    domains: { type: Array, default: () => [] },
    summary: { type: Object, required: true },
    server: { type: Object, required: true },
    filters: { type: Object, default: () => ({}) },
})

const { ask } = useConfirm()

const search = ref(props.filters.search || '')
const statusFilter = ref(props.filters.status || 'all')

const applyFilters = () => {
    router.get(route('admin.mail.deliverability.index'), {
        search: search.value,
        status: statusFilter.value,
    }, { preserveState: false, replace: true })
}

const refreshAll = () => router.post(route('admin.mail.deliverability.refresh'), {}, { preserveScroll: true })
const refreshOne = (domain) => router.post(route('admin.mail.deliverability.refresh'), { domain: domain.name }, { preserveScroll: true })

const autoFix = async (domain) => {
    const ok = await ask({
        title: `${domain.name} — Auto-fix`,
        message: 'Eksik SPF/DKIM/DMARC/MX kayıtları panel DNS zone\'una otomatik eklenecek. DNS propagation 5-30 dk sürer.',
        confirmText: 'Uygula',
    })
    if (!ok) return
    router.post(route('admin.mail.deliverability.auto-fix', domain.id))
}

const showBulkFix = ref(false)
const bulkConfirm = ref('')

const submitBulkFix = () => {
    if (bulkConfirm.value !== 'TUMUNE UYGULA') return
    router.post(route('admin.mail.deliverability.bulk-auto-fix'), { confirm_string: bulkConfirm.value }, {
        onFinish: () => { showBulkFix.value = false; bulkConfirm.value = '' },
    })
}

const statusBadge = (s) => ({
    ok: { class: 'bg-emerald-100 text-emerald-700', icon: CheckCircleIcon, label: '✓' },
    invalid: { class: 'bg-amber-100 text-amber-700', icon: ExclamationTriangleIcon, label: '!' },
    missing: { class: 'bg-red-100 text-red-700', icon: XCircleIcon, label: '✗' },
}[s] || { class: 'bg-slate-100 text-slate-600', icon: XCircleIcon, label: '?' })

const severityBadge = (sev) => ({
    critical: 'bg-red-100 text-red-700',
    warning: 'bg-amber-100 text-amber-700',
    good: 'bg-emerald-100 text-emerald-700',
}[sev] || 'bg-slate-100 text-slate-600')

const severityLabel = (sev) => ({
    critical: 'Kritik',
    warning: 'Uyarı',
    good: 'İyi',
}[sev] || sev)

const scoreColor = (score) => {
    if (score >= 75) return 'text-emerald-700'
    if (score >= 40) return 'text-amber-700'
    return 'text-red-700'
}
</script>

<template>
    <Head title="Email Deliverability" />
    <AdminLayout>
        <template #header>
            <div class="flex items-center gap-2">
                <EnvelopeIcon class="h-6 w-6 text-indigo-500" />
                <span>Email Deliverability (Tüm Domainler)</span>
            </div>
        </template>

        <!-- Intro -->
        <div class="mb-4 rounded-xl border border-indigo-200 bg-indigo-50 p-4 text-sm text-indigo-900">
            <div class="flex gap-3">
                <InformationCircleIcon class="h-5 w-5 flex-shrink-0 text-indigo-600" />
                <div>
                    <strong>WHM "Email Deliverability" muadili.</strong>
                    Tüm hesapların domain'leri için SPF / DKIM / DMARC / MX kontrolü +
                    sunucu IP'sinin PTR (reverse DNS) ve RBL (Spamhaus/SpamCop/Barracuda) durumu.
                    Eksik kayıtları tek tıkla panel DNS zone'una otomatik ekleyebilirsin.
                </div>
            </div>
        </div>

        <!-- Server-level checks (PTR + RBL) -->
        <div class="mb-4 grid gap-3 sm:grid-cols-2">
            <!-- PTR -->
            <div :class="['rounded-xl border p-4', server.ptr.valid ? 'border-emerald-200 bg-emerald-50' : 'border-red-200 bg-red-50']">
                <div class="mb-2 flex items-center gap-2">
                    <ServerIcon :class="['h-5 w-5', server.ptr.valid ? 'text-emerald-600' : 'text-red-600']" />
                    <h3 class="font-semibold">PTR (Reverse DNS)</h3>
                    <CheckCircleIcon v-if="server.ptr.valid" class="h-4 w-4 text-emerald-600" />
                    <XCircleIcon v-else class="h-4 w-4 text-red-600" />
                </div>
                <dl class="text-xs space-y-1">
                    <div class="flex justify-between">
                        <dt class="text-slate-600">Sunucu IP:</dt>
                        <dd class="font-mono">{{ server.ipv4 || '—' }}</dd>
                    </div>
                    <div class="flex justify-between">
                        <dt class="text-slate-600">PTR:</dt>
                        <dd class="font-mono">{{ server.ptr.ptr || 'Yok' }}</dd>
                    </div>
                    <div class="flex justify-between">
                        <dt class="text-slate-600">Beklenen:</dt>
                        <dd class="font-mono">{{ server.ptr.expected || '—' }}</dd>
                    </div>
                </dl>
                <ul v-if="server.ptr.issues?.length" class="mt-2 space-y-0.5">
                    <li v-for="(iss, i) in server.ptr.issues" :key="i" class="text-[11px] text-red-700">• {{ iss }}</li>
                </ul>
            </div>

            <!-- RBL -->
            <div :class="['rounded-xl border p-4', server.rbl.valid ? 'border-emerald-200 bg-emerald-50' : 'border-red-200 bg-red-50']">
                <div class="mb-2 flex items-center gap-2">
                    <ShieldExclamationIcon :class="['h-5 w-5', server.rbl.valid ? 'text-emerald-600' : 'text-red-600']" />
                    <h3 class="font-semibold">RBL (Kara Liste)</h3>
                    <span v-if="server.rbl.valid" class="text-xs font-medium text-emerald-700">Temiz</span>
                    <span v-else class="text-xs font-medium text-red-700">{{ server.rbl.listed_count }} listelemiş</span>
                </div>
                <div class="grid grid-cols-2 gap-1 text-[11px]">
                    <div v-for="rbl in server.rbl.checked" :key="rbl.zone"
                         :class="['flex items-center gap-1 rounded px-1.5 py-0.5', rbl.listed ? 'bg-red-100 text-red-700' : 'bg-emerald-100/50 text-emerald-700']">
                        <CheckCircleIcon v-if="!rbl.listed" class="h-3 w-3" />
                        <XCircleIcon v-else class="h-3 w-3" />
                        <span class="font-mono">{{ rbl.name }}</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Stats -->
        <div class="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-9">
            <div class="rounded-xl border border-slate-200 bg-white p-3">
                <p class="text-[10px] uppercase text-slate-500">Toplam</p>
                <p class="mt-1 text-xl font-bold">{{ summary.total }}</p>
            </div>
            <div class="rounded-xl border border-emerald-200 bg-emerald-50 p-3">
                <p class="text-[10px] uppercase text-emerald-700">Ort. Skor</p>
                <p :class="['mt-1 text-xl font-bold', scoreColor(summary.avg_score)]">{{ summary.avg_score }}</p>
            </div>
            <div class="rounded-xl border border-emerald-200 bg-emerald-50 p-3">
                <p class="text-[10px] uppercase text-emerald-700">İyi (≥75)</p>
                <p class="mt-1 text-xl font-bold text-emerald-800">{{ summary.good }}</p>
            </div>
            <div class="rounded-xl border border-amber-200 bg-amber-50 p-3">
                <p class="text-[10px] uppercase text-amber-700">Uyarı</p>
                <p class="mt-1 text-xl font-bold text-amber-800">{{ summary.warning }}</p>
            </div>
            <div class="rounded-xl border border-red-200 bg-red-50 p-3">
                <p class="text-[10px] uppercase text-red-700">Kritik</p>
                <p class="mt-1 text-xl font-bold text-red-800">{{ summary.critical }}</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-3">
                <p class="text-[10px] uppercase text-slate-500">SPF Yok</p>
                <p class="mt-1 text-xl font-bold text-red-700">{{ summary.missing_spf }}</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-3">
                <p class="text-[10px] uppercase text-slate-500">DKIM Yok</p>
                <p class="mt-1 text-xl font-bold text-red-700">{{ summary.missing_dkim }}</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-3">
                <p class="text-[10px] uppercase text-slate-500">DMARC Yok</p>
                <p class="mt-1 text-xl font-bold text-red-700">{{ summary.missing_dmarc }}</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-3">
                <p class="text-[10px] uppercase text-slate-500">MX Yok</p>
                <p class="mt-1 text-xl font-bold text-red-700">{{ summary.missing_mx }}</p>
            </div>
        </div>

        <!-- Filters -->
        <div class="mb-4 flex flex-wrap items-center gap-2 rounded-xl border border-slate-200 bg-white p-3">
            <input v-model="search" @keyup.enter="applyFilters" type="text"
                   placeholder="Domain veya kullanıcı ara..."
                   class="flex-1 min-w-[200px] rounded-lg border border-slate-300 px-3 py-1.5 text-sm" />
            <select v-model="statusFilter" class="rounded-lg border border-slate-300 px-3 py-1.5 text-sm">
                <option value="all">Tümü</option>
                <option value="critical">Kritik (skor &lt;40)</option>
                <option value="warning">Uyarı (40-74)</option>
                <option value="good">İyi (≥75)</option>
                <option value="missing_spf">SPF Eksik</option>
                <option value="missing_dkim">DKIM Eksik</option>
                <option value="missing_dmarc">DMARC Eksik</option>
                <option value="missing_mx">MX Eksik</option>
            </select>
            <button @click="applyFilters" class="rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-indigo-700">
                Uygula
            </button>
            <button @click="refreshAll" class="inline-flex items-center gap-1 rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-xs font-medium hover:bg-slate-50">
                <ArrowPathIcon class="h-3.5 w-3.5" /> Tüm Cache Temizle
            </button>
            <button v-if="summary.missing_spf + summary.missing_dkim + summary.missing_dmarc + summary.missing_mx > 0"
                    @click="showBulkFix = true"
                    class="ml-auto inline-flex items-center gap-1.5 rounded-lg bg-emerald-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-emerald-700">
                <BoltIcon class="h-4 w-4" />
                Eksik Olanları Toplu Düzelt
            </button>
        </div>

        <!-- Bulk fix modal -->
        <div v-if="showBulkFix" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
                <h3 class="mb-2 text-lg font-semibold">Toplu Auto-fix</h3>
                <p class="mb-3 text-sm text-slate-700">
                    Eksik SPF/DKIM/DMARC/MX kaydı olan TÜM domain'lere panel DNS zone'una otomatik ekleme yapılacak.
                    Sadece eksik olanlar eklenir; mevcut kayıtlar atlanır.
                </p>
                <p class="mb-2 text-xs text-slate-500">
                    Onay metni: <code class="rounded bg-slate-100 px-1.5">TUMUNE UYGULA</code>
                </p>
                <input v-model="bulkConfirm" type="text" class="mb-3 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                <div class="flex justify-end gap-2">
                    <button @click="showBulkFix = false; bulkConfirm = ''" class="rounded-lg border border-slate-300 px-4 py-2 text-sm">İptal</button>
                    <button @click="submitBulkFix" :disabled="bulkConfirm !== 'TUMUNE UYGULA'"
                            class="rounded-lg bg-emerald-600 px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-700 disabled:opacity-50">
                        Toplu Uygula
                    </button>
                </div>
            </div>
        </div>

        <!-- Domains table -->
        <div v-if="domains.length === 0" class="rounded-xl border border-dashed border-slate-300 bg-white p-12 text-center">
            <GlobeAltIcon class="mx-auto h-10 w-10 text-slate-300" />
            <p class="mt-2 text-sm text-slate-500">Filtrelerle eşleşen domain yok.</p>
        </div>

        <div v-else class="overflow-x-auto rounded-xl border border-slate-200 bg-white shadow-sm">
            <table class="min-w-full divide-y divide-slate-100 text-sm">
                <thead class="bg-slate-50 text-xs uppercase text-slate-500">
                    <tr>
                        <th class="px-3 py-2 text-left">Domain / Hesap</th>
                        <th class="px-3 py-2 text-center">SPF</th>
                        <th class="px-3 py-2 text-center">DKIM</th>
                        <th class="px-3 py-2 text-center">DMARC</th>
                        <th class="px-3 py-2 text-center">MX</th>
                        <th class="px-3 py-2 text-center">Skor</th>
                        <th class="px-3 py-2 text-center">Durum</th>
                        <th class="px-3 py-2"></th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <tr v-for="d in domains" :key="d.id"
                        :class="[
                            d.severity === 'critical' ? 'bg-red-50/40' :
                            d.severity === 'warning' ? 'bg-amber-50/40' : '',
                        ]">
                        <td class="px-3 py-2">
                            <p class="font-mono text-sm font-semibold text-slate-900">{{ d.name }}</p>
                            <p class="text-xs text-slate-500">{{ d.username }}</p>
                        </td>
                        <td v-for="check in ['spf', 'dkim', 'dmarc', 'mx']" :key="check" class="px-3 py-2 text-center">
                            <span :class="['inline-flex items-center justify-center w-7 h-7 rounded-full font-bold text-xs', statusBadge(d[check]).class]">
                                {{ statusBadge(d[check]).label }}
                            </span>
                        </td>
                        <td class="px-3 py-2 text-center">
                            <span :class="['font-mono text-lg font-bold', scoreColor(d.overall_score)]">{{ d.overall_score }}</span>
                            <span class="text-xs text-slate-400">/100</span>
                        </td>
                        <td class="px-3 py-2 text-center">
                            <span :class="['rounded-full px-2 py-0.5 text-xs font-medium', severityBadge(d.severity)]">
                                {{ severityLabel(d.severity) }}
                            </span>
                        </td>
                        <td class="px-3 py-2 text-right">
                            <div class="inline-flex gap-1">
                                <Link :href="route('admin.mail.deliverability.show', d.id)"
                                      class="rounded border border-slate-300 bg-white px-2 py-1 text-xs hover:bg-slate-50">
                                    Detay
                                </Link>
                                <button v-if="d.overall_score < 100" @click="autoFix(d)"
                                        class="rounded border border-emerald-300 bg-emerald-50 px-2 py-1 text-xs text-emerald-700 hover:bg-emerald-100"
                                        title="Eksik kayıtları panel DNS'ine ekle">
                                    Düzelt
                                </button>
                                <button @click="refreshOne(d)"
                                        class="rounded p-1 text-slate-500 hover:bg-slate-100 hover:text-indigo-600"
                                        title="Cache temizle + tekrar kontrol">
                                    <ArrowPathIcon class="h-3.5 w-3.5" />
                                </button>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </AdminLayout>
</template>
