<script setup>
import { ref, onBeforeUnmount, onMounted, computed } from 'vue'
import { Head, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    EnvelopeIcon,
    ExclamationTriangleIcon,
    TrashIcon,
    ArrowPathIcon,
    CheckCircleIcon,
    XCircleIcon,
    PauseIcon,
    PlayIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    tab: String,
    filter: String,
    queue: Array,
    logs: Array,
    stats: Object,
    sysapi_error: { type: String, default: null },
    is_real_sysapi: { type: Boolean, default: false },
})

const autoRefresh = ref(true)
let refreshTimer = null

const reloadFromServer = () => {
    router.reload({ preserveScroll: true, preserveState: true, only: ['queue', 'stats', 'sysapi_error', 'logs'] })
}

onMounted(() => {
    refreshTimer = setInterval(() => {
        if (autoRefresh.value) reloadFromServer()
    }, 30000)
})
onBeforeUnmount(() => {
    if (refreshTimer) clearInterval(refreshTimer)
})

const flush = async () => {
    const ok = await ask({
        title: 'Onaylayın',
        message: 'Kuyruktaki tüm deferred mailler yeniden gönderilmek üzere flush edilecek. Devam?',
        variant: 'warning',
        confirmText: 'Onayla',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('admin.mail-queue.flush'), {}, { preserveScroll: true })
}

const deleteMail = async (id) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `Mail ${id} kuyruktan silinsin mi?`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('admin.mail-queue.delete', id), { preserveScroll: true })
}

const holdMail = (id) => {
    router.post(route('admin.mail-queue.hold', id), {}, { preserveScroll: true })
}

const requeueMail = (id) => {
    router.post(route('admin.mail-queue.requeue', id), {}, { preserveScroll: true })
}

const goTab = (t) => router.get(route('admin.mail-queue.index', { tab: t, filter: props.filter }))

const setFilter = (f) => router.get(route('admin.mail-queue.index', { tab: props.tab, filter: f }), {}, { preserveScroll: true, preserveState: true })

const statusColor = (s) => ({
    active: 'bg-blue-100 text-blue-700',
    deferred: 'bg-amber-100 text-amber-700',
    hold: 'bg-purple-100 text-purple-700',
}[s] || 'bg-slate-100 text-slate-700')

const verbColor = (v) => ({
    sent: 'text-emerald-600',
    bounced: 'text-red-600',
    deferred: 'text-amber-600',
    rejected: 'text-red-700',
}[v] || 'text-slate-600')

const formatBytes = (b) => {
    if (!b) return '0 B'
    if (b < 1024) return b + ' B'
    if (b < 1024 * 1024) return (b / 1024).toFixed(1) + ' KB'
    return (b / 1024 / 1024).toFixed(1) + ' MB'
}

const ageOf = (arrival) => arrival || '—'

const queueEmpty = computed(() => !props.queue?.length)
const filters = ['all', 'deferred', 'active', 'hold']
</script>

<template>
    <Head title="Mail Queue Manager" />
    <AdminLayout>
        <template #header>Mail Queue Manager</template>

        <div v-if="sysapi_error" class="mb-4 rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-900">
            <div class="flex gap-3">
                <ExclamationTriangleIcon class="h-5 w-5 flex-shrink-0 text-red-600" />
                <div>
                    <strong>postqueue çalıştırılamadı:</strong>
                    <code class="text-xs">{{ sysapi_error }}</code>
                </div>
            </div>
        </div>

        <!-- Stats -->
        <div class="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-7">
            <div class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm">
                <EnvelopeIcon class="h-5 w-5 text-indigo-500" />
                <div class="mt-1 text-xl font-bold">{{ stats.queue_size }}</div>
                <p class="text-xs text-slate-500">Kuyrukta</p>
            </div>
            <div class="rounded-xl border border-blue-200 bg-blue-50 p-3">
                <ArrowPathIcon class="h-5 w-5 text-blue-600" />
                <div class="mt-1 text-xl font-bold text-blue-700">{{ stats.queue_active }}</div>
                <p class="text-xs text-blue-700">Aktif</p>
            </div>
            <div class="rounded-xl border border-amber-200 bg-amber-50 p-3">
                <PauseIcon class="h-5 w-5 text-amber-600" />
                <div class="mt-1 text-xl font-bold text-amber-700">{{ stats.queue_deferred }}</div>
                <p class="text-xs text-amber-700">Deferred</p>
            </div>
            <div class="rounded-xl border border-purple-200 bg-purple-50 p-3">
                <PauseIcon class="h-5 w-5 text-purple-600" />
                <div class="mt-1 text-xl font-bold text-purple-700">{{ stats.queue_hold }}</div>
                <p class="text-xs text-purple-700">Hold</p>
            </div>
            <div class="rounded-xl border border-emerald-200 bg-emerald-50 p-3">
                <CheckCircleIcon class="h-5 w-5 text-emerald-600" />
                <div class="mt-1 text-xl font-bold text-emerald-700">{{ stats.sent_today }}</div>
                <p class="text-xs text-emerald-700">Bugün Giden</p>
            </div>
            <div class="rounded-xl border border-red-200 bg-red-50 p-3">
                <XCircleIcon class="h-5 w-5 text-red-600" />
                <div class="mt-1 text-xl font-bold text-red-700">{{ stats.bounced_today }}</div>
                <p class="text-xs text-red-700">Bounce</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm">
                <XCircleIcon class="h-5 w-5 text-slate-500" />
                <div class="mt-1 text-xl font-bold">{{ stats.rejected_today }}</div>
                <p class="text-xs text-slate-500">Reddedilen</p>
            </div>
        </div>

        <!-- Tabs + filter + actions -->
        <div class="mb-4 flex flex-wrap justify-between items-center gap-2">
            <div class="flex gap-1 border-b border-slate-200">
                <button @click="goTab('queue')" :class="['px-4 py-2 text-sm font-medium border-b-2', tab === 'queue' ? 'border-indigo-600 text-indigo-700' : 'border-transparent text-slate-600']">
                    Kuyruk
                </button>
                <button @click="goTab('logs')" :class="['px-4 py-2 text-sm font-medium border-b-2', tab === 'logs' ? 'border-indigo-600 text-indigo-700' : 'border-transparent text-slate-600']">
                    Log Geçmişi
                </button>
            </div>
            <div class="flex flex-wrap items-center gap-2">
                <div v-if="tab === 'queue'" class="inline-flex rounded-lg border border-slate-200 bg-white text-xs">
                    <button v-for="f in filters" :key="f" @click="setFilter(f)" :class="['px-3 py-1.5 capitalize', filter === f ? 'bg-indigo-50 text-indigo-700 font-semibold' : 'text-slate-600 hover:bg-slate-50']">
                        {{ f === 'all' ? 'Tümü' : f }}
                    </button>
                </div>
                <label class="inline-flex items-center gap-1 text-xs text-slate-600">
                    <input v-model="autoRefresh" type="checkbox" class="h-3.5 w-3.5 rounded" />
                    Oto yenile (30sn)
                </label>
                <button v-if="tab === 'queue'" @click="reloadFromServer" class="inline-flex items-center gap-1 rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50">
                    <ArrowPathIcon class="h-3.5 w-3.5" /> Yenile
                </button>
                <button v-if="tab === 'queue'" @click="flush" class="inline-flex items-center gap-1 rounded-lg border border-amber-300 bg-amber-50 px-3 py-1.5 text-xs font-medium text-amber-700 hover:bg-amber-100">
                    <ArrowPathIcon class="h-3.5 w-3.5" /> Kuyruğu Flush Et
                </button>
            </div>
        </div>

        <!-- Queue -->
        <div v-if="tab === 'queue'" 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-3 py-2 text-left">Queue ID</th>
                        <th class="px-3 py-2 text-left">Gönderen</th>
                        <th class="px-3 py-2 text-left">Alıcı</th>
                        <th class="px-3 py-2 text-left">Boyut</th>
                        <th class="px-3 py-2 text-left">Durum</th>
                        <th class="px-3 py-2 text-left">Sebep</th>
                        <th class="px-3 py-2 text-left">Geliş</th>
                        <th class="px-3 py-2 text-right">İşlemler</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <tr v-for="m in queue" :key="m.queue_id" class="hover:bg-slate-50">
                        <td class="px-3 py-2 font-mono text-xs">{{ m.queue_id }}</td>
                        <td class="px-3 py-2 font-mono text-xs">{{ m.sender }}</td>
                        <td class="px-3 py-2 font-mono text-xs">{{ m.recipient }}</td>
                        <td class="px-3 py-2 text-xs font-mono">{{ formatBytes(m.size) }}</td>
                        <td class="px-3 py-2">
                            <span :class="['rounded px-2 py-0.5 text-xs font-semibold', statusColor(m.status)]">{{ m.status }}</span>
                        </td>
                        <td class="px-3 py-2 text-xs text-slate-500">{{ m.reason || '—' }}</td>
                        <td class="px-3 py-2 text-xs text-slate-500">{{ ageOf(m.arrived) }}</td>
                        <td class="px-3 py-2 text-right">
                            <div class="inline-flex gap-1">
                                <button v-if="m.status !== 'hold'" @click="holdMail(m.queue_id)" title="Hold" class="rounded p-1 text-purple-500 hover:bg-purple-50">
                                    <PauseIcon class="h-4 w-4" />
                                </button>
                                <button v-if="m.status === 'hold' || m.status === 'deferred'" @click="requeueMail(m.queue_id)" title="Yeniden kuyruğa al" class="rounded p-1 text-blue-500 hover:bg-blue-50">
                                    <PlayIcon class="h-4 w-4" />
                                </button>
                                <button @click="deleteMail(m.queue_id)" title="Sil" class="rounded p-1 text-red-500 hover:bg-red-50">
                                    <TrashIcon class="h-4 w-4" />
                                </button>
                            </div>
                        </td>
                    </tr>
                    <tr v-if="queueEmpty">
                        <td colspan="8" class="px-3 py-12 text-center text-sm text-slate-500">
                            Kuyrukta bekleyen mail yok.
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- Logs -->
        <div v-if="tab === 'logs'" 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-3 py-2 text-left">Zaman</th>
                        <th class="px-3 py-2 text-left">Eylem</th>
                        <th class="px-3 py-2 text-left">Gönderen</th>
                        <th class="px-3 py-2 text-left">Alıcı</th>
                        <th class="px-3 py-2 text-left">Konu</th>
                        <th class="px-3 py-2 text-left">Boyut</th>
                        <th class="px-3 py-2 text-left">Süre</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <tr v-for="l in logs" :key="l.id" class="hover:bg-slate-50">
                        <td class="px-3 py-2 font-mono text-xs">{{ l.time }}</td>
                        <td class="px-3 py-2">
                            <span :class="['text-xs font-semibold uppercase', verbColor(l.verb)]">{{ l.verb }}</span>
                        </td>
                        <td class="px-3 py-2 font-mono text-xs">{{ l.from }}</td>
                        <td class="px-3 py-2 font-mono text-xs">{{ l.to }}</td>
                        <td class="px-3 py-2 text-xs">{{ l.subject }}</td>
                        <td class="px-3 py-2 text-xs font-mono">{{ formatBytes(l.size) }}</td>
                        <td class="px-3 py-2 text-xs text-slate-500">{{ l.duration_ms }}ms</td>
                    </tr>
                    <tr v-if="!logs?.length">
                        <td colspan="7" class="px-3 py-12 text-center text-sm text-slate-500">
                            Henüz log kaydı yok. Postfix milter mail_logs tablosuna yazmaya başlayınca görünür.
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </AdminLayout>
</template>
