<script setup>
import { ref } from 'vue'
import { Head } from '@inertiajs/vue3'
import axios from 'axios'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    ServerStackIcon,
    SignalIcon,
    ArrowsRightLeftIcon,
    PlayIcon,
    GlobeAltIcon,
    ShieldCheckIcon,
    InformationCircleIcon,
} from '@heroicons/vue/24/outline'

defineProps({
    interfaces: Array,
    dns_servers: Array,
    hostname: String,
    firewall_zones: Array,
    listening_ports: Array,
})

const tab = ref('interfaces')

// Dig tool
const digForm = ref({ domain: 'example.com', type: 'A', server: '' })
const digResults = ref(null)
const digLoading = ref(false)

const runDig = async () => {
    digLoading.value = true
    digResults.value = null
    try {
        const { data } = await axios.post(route('admin.network.dig'), digForm.value)
        digResults.value = data
    } catch (e) {
        digResults.value = { error: e.response?.data?.message || 'Hata' }
    } finally {
        digLoading.value = false
    }
}

// Ping
const pingForm = ref({ host: '8.8.8.8', count: 4 })
const pingResults = ref(null)
const pingLoading = ref(false)

const runPing = async () => {
    pingLoading.value = true
    pingResults.value = null
    try {
        const { data } = await axios.post(route('admin.network.ping'), pingForm.value)
        pingResults.value = data
    } catch (e) {
        pingResults.value = { error: 'Ping başarısız' }
    } finally {
        pingLoading.value = false
    }
}

// PTR
const ptrForm = ref({ ip: '8.8.8.8' })
const ptrResult = ref(null)
const runPtr = async () => {
    const { data } = await axios.post(route('admin.network.reverse-dns'), ptrForm.value)
    ptrResult.value = data
}
</script>

<template>
    <Head title="Ağ Araçları" />
    <AdminLayout>
        <template #header>Ağ Araçları (Network Tools)</template>

        <!-- Hostname banner -->
        <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 items-center">
                <ServerStackIcon class="h-5 w-5 text-indigo-600" />
                <div>
                    Sunucu hostname: <code class="rounded bg-white px-2 py-0.5 font-mono font-bold">{{ hostname }}</code>
                    · DNS resolver: <span v-for="(s, i) in dns_servers" :key="s" class="font-mono">{{ s }}<span v-if="i < dns_servers.length-1">, </span></span>
                </div>
            </div>
        </div>

        <!-- Tabs -->
        <div class="mb-4 flex flex-wrap gap-1 border-b border-slate-200">
            <button v-for="t in [
                { v: 'interfaces', label: 'Arayüzler', icon: SignalIcon },
                { v: 'ports', label: 'Dinlenen Portlar', icon: ArrowsRightLeftIcon },
                { v: 'firewall', label: 'Güvenlik Duvarı', icon: ShieldCheckIcon },
                { v: 'tools', label: 'DNS Araçları', icon: GlobeAltIcon },
            ]" :key="t.v" @click="tab = t.v"
                    :class="['px-4 py-2 text-sm font-medium border-b-2', tab === t.v ? 'border-indigo-600 text-indigo-700' : 'border-transparent text-slate-600 hover:text-slate-900']">
                <component :is="t.icon" class="inline h-4 w-4 mr-1" /> {{ t.label }}
            </button>
        </div>

        <!-- Interfaces -->
        <div v-if="tab === 'interfaces'" class="space-y-3">
            <div v-for="iface in interfaces" :key="iface.name"
                 class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div class="flex items-start justify-between flex-wrap gap-3">
                    <div class="flex items-center gap-3">
                        <SignalIcon :class="['h-6 w-6', iface.state === 'up' ? 'text-emerald-500' : 'text-slate-400']" />
                        <div>
                            <div class="font-mono text-lg font-bold">{{ iface.name }}</div>
                            <div class="font-mono text-xs text-slate-500">{{ iface.mac }}</div>
                        </div>
                    </div>
                    <span :class="['rounded px-2 py-0.5 text-xs font-semibold', iface.state === 'up' ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-500']">
                        {{ iface.state }}
                    </span>
                </div>
                <dl class="mt-4 grid grid-cols-2 gap-3 text-xs">
                    <div>
                        <dt class="text-slate-500">IPv4</dt>
                        <dd class="font-mono">{{ iface.ipv4 }}</dd>
                    </div>
                    <div v-if="iface.ipv6">
                        <dt class="text-slate-500">IPv6</dt>
                        <dd class="font-mono break-all">{{ iface.ipv6 }}</dd>
                    </div>
                    <div v-if="iface.netmask">
                        <dt class="text-slate-500">Netmask</dt>
                        <dd class="font-mono">{{ iface.netmask }}</dd>
                    </div>
                    <div v-if="iface.gateway">
                        <dt class="text-slate-500">Gateway</dt>
                        <dd class="font-mono">{{ iface.gateway }}</dd>
                    </div>
                    <div>
                        <dt class="text-slate-500">RX</dt>
                        <dd class="font-mono">↓ {{ iface.rx_mb }} MB</dd>
                    </div>
                    <div>
                        <dt class="text-slate-500">TX</dt>
                        <dd class="font-mono">↑ {{ iface.tx_mb }} MB</dd>
                    </div>
                </dl>
            </div>
        </div>

        <!-- Listening ports -->
        <div v-if="tab === 'ports'" class="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm">
            <table class="min-w-full divide-y divide-slate-200 text-sm">
                <thead class="bg-slate-50 text-xs uppercase text-slate-500">
                    <tr>
                        <th class="px-4 py-2 text-left">Port</th>
                        <th class="px-4 py-2 text-left">Protocol</th>
                        <th class="px-4 py-2 text-left">Servis</th>
                        <th class="px-4 py-2 text-left">PID</th>
                        <th class="px-4 py-2 text-left">Bind Address</th>
                        <th class="px-4 py-2 text-left">Not</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <tr v-for="p in listening_ports" :key="p.port + '-' + p.proto" class="hover:bg-slate-50">
                        <td class="px-4 py-2 font-mono font-bold">{{ p.port }}</td>
                        <td class="px-4 py-2 font-mono text-xs">{{ p.proto }}</td>
                        <td class="px-4 py-2 font-medium">{{ p.service }}</td>
                        <td class="px-4 py-2 font-mono text-xs">{{ p.pid || '—' }}</td>
                        <td class="px-4 py-2 font-mono text-xs" :class="p.address === '0.0.0.0' ? 'text-amber-700' : 'text-slate-500'">
                            {{ p.address }}
                            <span v-if="p.address === '0.0.0.0'" class="text-[10px] ml-1">(public)</span>
                        </td>
                        <td class="px-4 py-2 text-xs text-slate-500">{{ p.note || '' }}</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- Firewall -->
        <div v-if="tab === 'firewall'" class="space-y-3">
            <div v-for="z in firewall_zones" :key="z.zone" class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div class="flex items-center gap-3">
                    <ShieldCheckIcon class="h-6 w-6 text-purple-500" />
                    <div>
                        <h3 class="font-semibold capitalize">{{ z.zone }}</h3>
                        <p class="text-xs text-slate-500">firewalld zone</p>
                    </div>
                    <span v-if="z.default" class="ml-auto rounded bg-emerald-100 px-2 py-0.5 text-xs font-semibold text-emerald-700">DEFAULT</span>
                </div>
                <dl class="mt-4 space-y-2 text-xs">
                    <div>
                        <dt class="text-slate-500 font-medium">Arayüzler</dt>
                        <dd class="mt-1 flex flex-wrap gap-1">
                            <span v-for="i in z.interfaces" :key="i" class="rounded bg-slate-100 px-2 py-0.5 font-mono">{{ i }}</span>
                        </dd>
                    </div>
                    <div>
                        <dt class="text-slate-500 font-medium">İzin Verilen Servisler</dt>
                        <dd class="mt-1 flex flex-wrap gap-1">
                            <span v-for="s in z.services" :key="s" class="rounded bg-emerald-100 px-2 py-0.5 text-emerald-700 font-medium">{{ s }}</span>
                        </dd>
                    </div>
                    <div v-if="z.ports.length">
                        <dt class="text-slate-500 font-medium">Açık Portlar</dt>
                        <dd class="mt-1 flex flex-wrap gap-1">
                            <span v-for="p in z.ports" :key="p" class="rounded bg-blue-100 px-2 py-0.5 font-mono">{{ p }}</span>
                        </dd>
                    </div>
                </dl>
            </div>
        </div>

        <!-- DNS Tools -->
        <div v-if="tab === 'tools'" class="grid grid-cols-1 gap-6 lg:grid-cols-3">
            <!-- Dig -->
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <h3 class="font-semibold mb-3">DNS Lookup (dig)</h3>
                <form @submit.prevent="runDig" class="space-y-3">
                    <div>
                        <label class="block text-xs text-slate-500">Domain</label>
                        <input v-model="digForm.domain" type="text" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                    </div>
                    <div>
                        <label class="block text-xs text-slate-500">Record Type</label>
                        <select v-model="digForm.type" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                            <option v-for="t in ['A', 'AAAA', 'MX', 'TXT', 'CNAME', 'NS', 'SOA']" :key="t">{{ t }}</option>
                        </select>
                    </div>
                    <button type="submit" :disabled="digLoading"
                            class="w-full inline-flex items-center justify-center gap-1 rounded-lg bg-indigo-600 px-3 py-2 text-sm text-white hover:bg-indigo-700 disabled:opacity-50">
                        <PlayIcon class="h-4 w-4" /> {{ digLoading ? 'Sorgulanıyor...' : 'Sorgula' }}
                    </button>
                </form>
                <div v-if="digResults" class="mt-4 rounded-lg bg-slate-900 p-3 font-mono text-xs text-slate-200">
                    <div v-if="digResults.error" class="text-red-400">{{ digResults.error }}</div>
                    <div v-else>
                        <div class="mb-2 text-slate-500">; {{ digResults.response_time_ms }}ms · {{ digResults.results.length }} record</div>
                        <div v-for="(r, i) in digResults.results" :key="i" class="break-all">
                            {{ r.name }} {{ r.ttl }} {{ r.class }} {{ r.type }} <span class="text-emerald-400">{{ r.value }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Ping -->
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <h3 class="font-semibold mb-3">Ping</h3>
                <form @submit.prevent="runPing" class="space-y-3">
                    <div>
                        <label class="block text-xs text-slate-500">Host</label>
                        <input v-model="pingForm.host" type="text" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                    </div>
                    <div>
                        <label class="block text-xs text-slate-500">Sayı</label>
                        <input v-model.number="pingForm.count" type="number" min="1" max="10" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                    </div>
                    <button type="submit" :disabled="pingLoading"
                            class="w-full inline-flex items-center justify-center gap-1 rounded-lg bg-indigo-600 px-3 py-2 text-sm text-white hover:bg-indigo-700 disabled:opacity-50">
                        <PlayIcon class="h-4 w-4" /> {{ pingLoading ? 'Pingleniyor...' : 'Pingle' }}
                    </button>
                </form>
                <div v-if="pingResults" class="mt-4 rounded-lg bg-slate-900 p-3 font-mono text-xs text-slate-200">
                    <div v-if="pingResults.error" class="text-red-400">{{ pingResults.error }}</div>
                    <div v-else>
                        <div v-for="r in pingResults.results" :key="r.seq">
                            64 bytes from {{ pingResults.host }}: icmp_seq={{ r.seq }} ttl={{ r.ttl }} time=<span class="text-emerald-400">{{ r.time_ms }}</span>ms
                        </div>
                        <div class="mt-2 text-slate-500">avg = {{ pingResults.avg_ms?.toFixed(2) }} ms · loss = {{ pingResults.packet_loss }}%</div>
                    </div>
                </div>
            </div>

            <!-- PTR -->
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <h3 class="font-semibold mb-3">Reverse DNS (PTR)</h3>
                <form @submit.prevent="runPtr" class="space-y-3">
                    <div>
                        <label class="block text-xs text-slate-500">IP Adresi</label>
                        <input v-model="ptrForm.ip" type="text" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                    </div>
                    <button type="submit"
                            class="w-full inline-flex items-center justify-center gap-1 rounded-lg bg-indigo-600 px-3 py-2 text-sm text-white hover:bg-indigo-700">
                        <PlayIcon class="h-4 w-4" /> Lookup
                    </button>
                </form>
                <div v-if="ptrResult" class="mt-4 rounded-lg bg-slate-900 p-3 font-mono text-xs text-slate-200">
                    <div class="text-slate-500">; {{ ptrResult.response_time_ms }}ms</div>
                    <div>{{ ptrResult.ip }} → <span class="text-emerald-400">{{ ptrResult.ptr }}</span></div>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
