<script setup>
import { ref, computed } from 'vue'
import { Head, Link, router, useForm } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { useConfirm } from '@/composables/useConfirm'
import {
    GlobeAltIcon,
    ServerIcon,
    CheckCircleIcon,
    ExclamationTriangleIcon,
    InformationCircleIcon,
    ShieldCheckIcon,
    ArrowPathIcon,
    BoltIcon,
    BeakerIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    settings: { type: Object, required: true },
    configured_ns: { type: Array, required: true },
    zones: { type: Array, required: true },
    stats: { type: Object, required: true },
})

const { ask } = useConfirm()

const form = useForm({
    ns1: props.settings.ns1 || '',
    ns2: props.settings.ns2 || '',
    ns3: props.settings.ns3 || '',
    ns4: props.settings.ns4 || '',
    soa_email: props.settings.soa_email || '',
    default_ttl: props.settings.default_ttl || 14400,
    soa_refresh: props.settings.soa_refresh || 7200,
    soa_retry: props.settings.soa_retry || 3600,
    soa_expire: props.settings.soa_expire || 1209600,
    soa_minimum: props.settings.soa_minimum || 3600,
})

const submitForm = () => form.patch(route('admin.dns.nameservers.update'), { preserveScroll: true })

const filterText = ref('')
const filterStatus = ref('all')   // all | in_sync | drift | dnssec

const filteredZones = computed(() => {
    let list = props.zones
    if (filterStatus.value === 'in_sync') list = list.filter((z) => z.in_sync)
    if (filterStatus.value === 'drift') list = list.filter((z) => !z.in_sync)
    if (filterStatus.value === 'dnssec') list = list.filter((z) => z.dnssec_enabled)
    if (filterText.value.trim() !== '') {
        const q = filterText.value.toLowerCase()
        list = list.filter((z) => z.name.toLowerCase().includes(q))
    }
    return list
})

const applyAllConfirm = ref(false)
const applyAllString = ref('')

const submitApplyAll = async () => {
    if (applyAllString.value !== 'TUMUNE UYGULA') return
    router.post(route('admin.dns.nameservers.apply-all'), {
        confirm_string: applyAllString.value,
    }, {
        onFinish: () => { applyAllConfirm.value = false; applyAllString.value = '' },
    })
}

const resyncZone = async (zone) => {
    const ok = await ask({
        title: `${zone.name} — NS resync`,
        message: 'Bu zone\'un NS kayıtları panelin mevcut NS ayarlarına göre yeniden yazılacak. Devam edilsin mi?',
        confirmText: 'Resync',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('admin.dns.nameservers.zone.resync', zone.id))
}

const runDryRun = () => router.post(route('admin.dns.nameservers.dry-run'), {}, { preserveScroll: true })
</script>

<template>
    <Head title="DNS Nameserver Yönetimi" />

    <AdminLayout>
        <template #header>
            <div class="flex items-center gap-2">
                <ServerIcon class="h-6 w-6 text-indigo-500" />
                <span>DNS Nameserver Yönetimi</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>cPanel "Basic WebHost Manager Setup → Nameservers" muadili.</strong>
                    Buradan ayarlanan NS1-NS4 panel-wide default'tur — yeni eklenen tüm zone'lar
                    bu NS'lerle oluşturulur. Mevcut zone'lar otomatik güncellenmez (drift kolonu
                    eşleşmeyenleri gösterir); değiştikten sonra "Tüm Zone'lara Uygula" butonunu kullanın.
                </div>
            </div>
        </div>

        <!-- Stats -->
        <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">
                <p class="text-xs uppercase text-slate-500">Toplam Zone</p>
                <p class="mt-1 text-2xl font-bold text-slate-900">{{ stats.total_zones }}</p>
            </div>
            <div class="rounded-xl border border-emerald-200 bg-emerald-50 p-4">
                <p class="text-xs uppercase text-emerald-600">Senkron</p>
                <p class="mt-1 text-2xl font-bold text-emerald-700">{{ stats.in_sync }}</p>
            </div>
            <div class="rounded-xl border border-amber-200 bg-amber-50 p-4">
                <p class="text-xs uppercase text-amber-700">Drift</p>
                <p class="mt-1 text-2xl font-bold text-amber-800">{{ stats.drift }}</p>
            </div>
            <div class="rounded-xl border border-indigo-200 bg-indigo-50 p-4">
                <p class="text-xs uppercase text-indigo-600">DNSSEC Aktif</p>
                <p class="mt-1 text-2xl font-bold text-indigo-700">{{ stats.dnssec_enabled }}</p>
            </div>
        </div>

        <!-- NS / SOA Form -->
        <div class="mb-4 rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
            <h3 class="mb-3 flex items-center gap-2 text-lg font-semibold text-slate-900">
                <GlobeAltIcon class="h-5 w-5 text-indigo-500" /> Panel Default Nameservers
            </h3>
            <form @submit.prevent="submitForm" class="space-y-4">
                <div class="grid gap-3 sm:grid-cols-2">
                    <div>
                        <label class="block text-sm font-medium text-slate-700">NS1 (zorunlu)</label>
                        <input v-model="form.ns1" type="text" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" placeholder="ns1.onox.com.tr" />
                        <p v-if="form.errors.ns1" class="mt-1 text-xs text-red-600">{{ form.errors.ns1 }}</p>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700">NS2 (zorunlu)</label>
                        <input v-model="form.ns2" type="text" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" placeholder="ns2.onox.com.tr" />
                        <p v-if="form.errors.ns2" class="mt-1 text-xs text-red-600">{{ form.errors.ns2 }}</p>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700">NS3 (opsiyonel)</label>
                        <input v-model="form.ns3" type="text" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" placeholder="ns3.onox.com.tr" />
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700">NS4 (opsiyonel)</label>
                        <input v-model="form.ns4" type="text" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" placeholder="ns4.onox.com.tr" />
                    </div>
                </div>

                <details class="rounded-lg border border-slate-200 bg-slate-50 p-3 text-sm">
                    <summary class="cursor-pointer text-sm font-medium text-slate-700">SOA Parametreleri (gelişmiş)</summary>
                    <div class="mt-3 grid gap-3 sm:grid-cols-3">
                        <div>
                            <label class="block text-xs font-medium text-slate-600">SOA Hostmaster E-posta</label>
                            <input v-model="form.soa_email" type="text" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-xs" placeholder="hostmaster.example.com" />
                            <p class="mt-1 text-[10px] text-slate-500">RFC 1035: @ yerine . (örn. hostmaster.onox.com.tr)</p>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-slate-600">Default TTL (sn)</label>
                            <input v-model.number="form.default_ttl" type="number" min="60" max="604800" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-xs" />
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-slate-600">SOA Refresh (sn)</label>
                            <input v-model.number="form.soa_refresh" type="number" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-xs" />
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-slate-600">SOA Retry (sn)</label>
                            <input v-model.number="form.soa_retry" type="number" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-xs" />
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-slate-600">SOA Expire (sn)</label>
                            <input v-model.number="form.soa_expire" type="number" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-xs" />
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-slate-600">SOA Min/Negative TTL (sn)</label>
                            <input v-model.number="form.soa_minimum" type="number" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-xs" />
                        </div>
                    </div>
                </details>

                <div class="flex flex-wrap items-center justify-between gap-3">
                    <div class="text-xs text-slate-500">
                        <span class="font-medium text-slate-700">Mevcut yapılandırılmış NS listesi:</span>
                        <span v-if="configured_ns.length === 0" class="text-amber-600">Boş (ayarla → kaydet)</span>
                        <code v-else v-for="(ns, i) in configured_ns" :key="ns" class="ml-1 rounded bg-slate-100 px-1.5 py-0.5 font-mono">{{ ns }}<span v-if="i < configured_ns.length - 1">,</span></code>
                    </div>
                    <button type="submit" :disabled="form.processing" class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50">
                        <CheckCircleIcon class="h-4 w-4" /> Kaydet
                    </button>
                </div>
            </form>
        </div>

        <!-- Bulk actions -->
        <div class="mb-4 flex flex-wrap items-center gap-3 rounded-xl border border-amber-200 bg-amber-50 p-4">
            <ExclamationTriangleIcon class="h-5 w-5 flex-shrink-0 text-amber-600" />
            <div class="flex-1 text-sm text-amber-900">
                <strong>Mevcut zone'lara değişiklik uygula:</strong>
                NS güncellendikten sonra eski zone'lar otomatik yenilenmez. Aşağıdaki butonla
                tüm zone'ların NS kayıtlarını yeni ayarlarla eşleştirin.
            </div>
            <button @click="runDryRun" class="inline-flex items-center gap-1.5 rounded-lg border border-amber-300 bg-white px-3 py-1.5 text-xs font-semibold text-amber-700 hover:bg-amber-100">
                <BeakerIcon class="h-4 w-4" /> Dry Run
            </button>
            <button @click="applyAllConfirm = true" class="inline-flex items-center gap-1.5 rounded-lg bg-amber-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-amber-700">
                <BoltIcon class="h-4 w-4" /> Tüm Zone'lara Uygula
            </button>
        </div>

        <!-- Apply-all modal -->
        <div v-if="applyAllConfirm" 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 text-slate-900">Onay gerekli</h3>
                <p class="text-sm text-slate-600">
                    Tüm <strong>{{ stats.total_zones }}</strong> zone'un NS kayıtları yeniden yazılacak.
                    Drift olan {{ stats.drift }} zone güncellenir, senkron olan {{ stats.in_sync }} zone değişmez.
                </p>
                <p class="mt-3 text-xs text-slate-500">
                    Devam etmek için aşağıya <code class="rounded bg-slate-100 px-1.5 py-0.5 font-mono">TUMUNE UYGULA</code> yazın:
                </p>
                <input v-model="applyAllString" type="text" class="mt-2 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" placeholder="TUMUNE UYGULA" />
                <div class="mt-4 flex justify-end gap-2">
                    <button @click="applyAllConfirm = false; applyAllString = ''" class="rounded-lg border border-slate-300 px-4 py-2 text-sm">İptal</button>
                    <button @click="submitApplyAll" :disabled="applyAllString !== 'TUMUNE UYGULA'" class="rounded-lg bg-amber-600 px-4 py-2 text-sm font-medium text-white hover:bg-amber-700 disabled:opacity-50">Uygula</button>
                </div>
            </div>
        </div>

        <!-- Zones table -->
        <div class="rounded-xl border border-slate-200 bg-white shadow-sm">
            <div class="flex items-center justify-between border-b border-slate-200 px-5 py-3">
                <h3 class="flex items-center gap-2 text-base font-semibold text-slate-900">
                    Zone Listesi & NS Drift Analizi
                </h3>
                <div class="flex items-center gap-2">
                    <input v-model="filterText" type="text" placeholder="Domain ara..." class="rounded-lg border border-slate-300 px-3 py-1.5 text-sm" />
                    <select v-model="filterStatus" class="rounded-lg border border-slate-300 px-3 py-1.5 text-sm">
                        <option value="all">Tümü</option>
                        <option value="in_sync">Senkron</option>
                        <option value="drift">Drift</option>
                        <option value="dnssec">DNSSEC Aktif</option>
                    </select>
                </div>
            </div>
            <table class="min-w-full divide-y divide-slate-100 text-sm">
                <thead class="bg-slate-50 text-xs uppercase tracking-wide text-slate-500">
                    <tr>
                        <th class="px-4 py-2 text-left">Zone</th>
                        <th class="px-4 py-2 text-left">Mevcut NS Kayıtları</th>
                        <th class="px-4 py-2 text-center">Durum</th>
                        <th class="px-4 py-2 text-center">DNSSEC</th>
                        <th class="px-4 py-2 text-center">Serial</th>
                        <th class="px-4 py-2"></th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <tr v-if="filteredZones.length === 0">
                        <td colspan="6" class="px-4 py-6 text-center text-sm text-slate-500">Filtreyle eşleşen zone yok.</td>
                    </tr>
                    <tr v-for="zone in filteredZones" :key="zone.id" :class="zone.in_sync ? '' : 'bg-amber-50/40'">
                        <td class="px-4 py-2 font-mono text-sm text-slate-900">{{ zone.name }}</td>
                        <td class="px-4 py-2">
                            <div v-if="zone.current_ns.length === 0" class="text-xs text-red-600">NS kaydı yok</div>
                            <div v-else class="space-y-0.5">
                                <code v-for="ns in zone.current_ns" :key="ns" class="block rounded bg-slate-100 px-1.5 py-0.5 font-mono text-xs">{{ ns }}</code>
                            </div>
                        </td>
                        <td class="px-4 py-2 text-center">
                            <span v-if="zone.in_sync" class="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-medium text-emerald-700">
                                <CheckCircleIcon class="h-3.5 w-3.5" /> Senkron
                            </span>
                            <span v-else class="inline-flex items-center gap-1 rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-700">
                                <ExclamationTriangleIcon class="h-3.5 w-3.5" /> Drift
                            </span>
                        </td>
                        <td class="px-4 py-2 text-center">
                            <ShieldCheckIcon v-if="zone.dnssec_enabled" class="mx-auto h-4 w-4 text-emerald-600" :title="'DNSSEC aktif'" />
                            <span v-else class="text-xs text-slate-400">—</span>
                        </td>
                        <td class="px-4 py-2 text-center font-mono text-xs text-slate-500">{{ zone.notified_serial }}</td>
                        <td class="px-4 py-2 text-right">
                            <button
                                v-if="!zone.in_sync"
                                @click="resyncZone(zone)"
                                class="inline-flex items-center gap-1 rounded-lg border border-indigo-300 bg-white px-2.5 py-1 text-xs font-medium text-indigo-700 hover:bg-indigo-50"
                                title="Bu zone için NS'leri yenile"
                            >
                                <ArrowPathIcon class="h-3.5 w-3.5" /> Resync
                            </button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </AdminLayout>
</template>
