<script setup>
import { ref, computed } from 'vue'
import { Head, Link, useForm, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    EnvelopeOpenIcon,
    InboxIcon,
    Cog6ToothIcon,
    BoltIcon,
    ArrowPathIcon,
    PlayIcon,
    ArrowDownTrayIcon,
    ArrowUturnLeftIcon,
    UsersIcon,
    ClockIcon,
    NoSymbolIcon,
    InformationCircleIcon,
    ShieldCheckIcon,
    LockClosedIcon,
    FunnelIcon,
    XMarkIcon,
    ServerIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    grouped: Object,
    status: Object,
    sessions: Array,
})

// ── Tabs ─────────────────────────────────────────────────────────────────────
const activeTab = ref('overview')
const tabs = [
    { id: 'overview',       label: 'Genel Bakış',       icon: ServerIcon },
    { id: 'configuration',  label: 'Konfigürasyon',     icon: Cog6ToothIcon },
    { id: 'sessions',       label: 'Aktif Bağlantılar', icon: UsersIcon },
]

// ── Category labels ───────────────────────────────────────────────────────────
const categoryLabels = {
    protocols:      'Protokoller',
    mail_storage:   'Mailbox Saklama',
    authentication: 'Kimlik Doğrulama',
    quota:          'Kota',
    sieve:          'Sieve Filtreleri',
    lmtp:           'LMTP (Postfix → Dovecot)',
    ssl:            'SSL/TLS',
    logging:        'Loglama',
}

// ── Configuration form ────────────────────────────────────────────────────────
const buildInitialSettings = () => {
    const s = {}
    for (const [, rows] of Object.entries(props.grouped)) {
        for (const row of rows) {
            s[row.key] = row.value ?? ''
        }
    }
    return s
}

const configForm = useForm({ settings: buildInitialSettings() })

const submitConfig = () => {
    configForm.patch(route('admin.mail.dovecot.update'), { preserveScroll: true })
}

const resetRowToDefault = (row) => {
    configForm.settings[row.key] = row.default_value ?? ''
}

const resetAllForm = useForm({})
const resetAll = async () => {
    const ok = await ask({
        title: 'Onaylayın',
        message: 'Tüm değerler varsayılana sıfırlanacak. Onaylıyor musunuz?',
        variant: 'warning',
        confirmText: 'Onayla',
        cancelText: 'İptal',
    })
    if (!ok) return
    resetAllForm.post(route('admin.mail.dovecot.reset'), {
        preserveScroll: true,
        onSuccess: () => {
            configForm.settings = buildInitialSettings()
        },
    })
}

// ── Action forms ──────────────────────────────────────────────────────────────
const reloadForm  = useForm({})
const restartForm = useForm({})
const testForm    = useForm({})

const doReload = () => {
    reloadForm.post(route('admin.mail.dovecot.reload'), { preserveScroll: true })
}
const doRestart = async () => {
    const ok = await ask({
        title: 'Onaylayın',
        message: 'Dovecot yeniden başlatılacak. Aktif bağlantılar kesilir. Onaylıyor musunuz?',
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    restartForm.post(route('admin.mail.dovecot.restart'), { preserveScroll: true })
}
const doTest = () => {
    testForm.post(route('admin.mail.dovecot.test'), { preserveScroll: true })
}

// ── Sessions ──────────────────────────────────────────────────────────────────
const sessionSearch = ref('')
const filteredSessions = computed(() => {
    const q = sessionSearch.value.toLowerCase()
    if (!q) return props.sessions
    return props.sessions.filter(
        (s) =>
            s.username.toLowerCase().includes(q) ||
            s.remote_ip.toLowerCase().includes(q) ||
            s.state.toLowerCase().includes(q)
    )
})

const killForm = useForm({})
const killSession = async (sessionId, username) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `"${username}" kullanıcısının oturumu sonlandırılacak. Onaylıyor musunuz?`,
        variant: 'warning',
        confirmText: 'Onayla',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('admin.mail.dovecot.sessions.kill', sessionId), {
        preserveScroll: true,
    })
}

// ── Helpers ───────────────────────────────────────────────────────────────────
const stateBadgeClass = (state) => {
    switch (state) {
        case 'idle':   return 'bg-slate-100 text-slate-700'
        case 'select': return 'bg-blue-100 text-blue-700'
        case 'fetch':  return 'bg-emerald-100 text-emerald-700'
        default:       return 'bg-gray-100 text-gray-700'
    }
}

const formatIdleSeconds = (sec) => {
    if (sec < 60)   return `${sec}s`
    if (sec < 3600) return `${Math.floor(sec / 60)}d`
    return `${Math.floor(sec / 3600)}sa`
}
</script>

<template>
    <AdminLayout>
        <Head title="Dovecot Konfigürasyon" />

        <div class="space-y-6">

            <!-- Page header -->
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div class="rounded-xl bg-sky-100 p-2.5">
                        <InboxIcon class="h-6 w-6 text-sky-600" />
                    </div>
                    <div>
                        <h1 class="text-xl font-semibold text-slate-900">Dovecot IMAP/POP3</h1>
                        <p class="text-sm text-slate-500">Mail server — IMAP, POP3, LMTP daemon konfigürasyonu</p>
                    </div>
                </div>
                <span class="rounded-full bg-amber-100 px-2.5 py-0.5 text-xs font-semibold text-amber-700">P2</span>
            </div>

            <!-- Tabs -->
            <div class="border-b border-slate-200">
                <nav class="-mb-px flex gap-6">
                    <button
                        v-for="tab in tabs"
                        :key="tab.id"
                        @click="activeTab = tab.id"
                        :class="[
                            'flex items-center gap-2 border-b-2 pb-3 text-sm font-medium transition-colors',
                            activeTab === tab.id
                                ? 'border-sky-600 text-sky-600'
                                : 'border-transparent text-slate-500 hover:text-slate-700',
                        ]"
                    >
                        <component :is="tab.icon" class="h-4 w-4" />
                        {{ tab.label }}
                    </button>
                </nav>
            </div>

            <!-- ── TAB 1: OVERVIEW ──────────────────────────────────────────── -->
            <template v-if="activeTab === 'overview'">

                <!-- Status card -->
                <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                    <div class="flex items-start justify-between">
                        <div>
                            <p class="text-xs font-medium uppercase tracking-wide text-slate-400">Servis Durumu</p>
                            <p class="mt-1 text-lg font-semibold text-slate-900">{{ status.version }}</p>
                            <p class="text-sm text-slate-500">Uptime: {{ status.uptime }}</p>
                        </div>
                        <span
                            :class="[
                                'rounded-full px-3 py-1 text-xs font-semibold',
                                status.service === 'active'
                                    ? 'bg-emerald-100 text-emerald-700'
                                    : 'bg-red-100 text-red-700',
                            ]"
                        >
                            {{ status.service === 'active' ? 'Aktif' : 'Pasif' }}
                        </span>
                    </div>
                </div>

                <!-- Stat cards -->
                <div class="grid grid-cols-2 gap-4 sm:grid-cols-4">
                    <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                        <p class="text-xs font-medium uppercase tracking-wide text-slate-400">IMAP Bağlantı</p>
                        <p class="mt-2 text-2xl font-bold text-sky-600">{{ status.connected_users_imap }}</p>
                        <p class="mt-1 text-xs text-slate-500">aktif kullanıcı</p>
                    </div>
                    <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                        <p class="text-xs font-medium uppercase tracking-wide text-slate-400">POP3 Bağlantı</p>
                        <p class="mt-2 text-2xl font-bold text-violet-600">{{ status.connected_users_pop3 }}</p>
                        <p class="mt-1 text-xs text-slate-500">aktif kullanıcı</p>
                    </div>
                    <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                        <p class="text-xs font-medium uppercase tracking-wide text-slate-400">Toplam Mailbox</p>
                        <p class="mt-2 text-2xl font-bold text-slate-900">{{ status.total_mailboxes }}</p>
                        <p class="mt-1 text-xs text-slate-500">sunucuda kayıtlı</p>
                    </div>
                    <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                        <p class="text-xs font-medium uppercase tracking-wide text-slate-400">Servis</p>
                        <p class="mt-2 text-2xl font-bold text-emerald-600">{{ status.service === 'active' ? 'Çalışıyor' : 'Durdu' }}</p>
                        <p class="mt-1 text-xs text-slate-500">systemd durumu</p>
                    </div>
                </div>

                <!-- Action buttons -->
                <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                    <h3 class="mb-4 text-sm font-semibold text-slate-700">Servis İşlemleri</h3>
                    <div class="flex flex-wrap gap-3">
                        <button
                            @click="doTest"
                            :disabled="testForm.processing"
                            class="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700 shadow-sm hover:bg-slate-50 disabled:opacity-50"
                        >
                            <ShieldCheckIcon class="h-4 w-4 text-slate-500" />
                            Config Test
                        </button>
                        <button
                            @click="doReload"
                            :disabled="reloadForm.processing"
                            class="inline-flex items-center gap-2 rounded-lg border border-sky-200 bg-sky-50 px-4 py-2 text-sm font-medium text-sky-700 shadow-sm hover:bg-sky-100 disabled:opacity-50"
                        >
                            <ArrowPathIcon class="h-4 w-4" />
                            Reload
                        </button>
                        <button
                            @click="doRestart"
                            :disabled="restartForm.processing"
                            class="inline-flex items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-4 py-2 text-sm font-medium text-amber-700 shadow-sm hover:bg-amber-100 disabled:opacity-50"
                        >
                            <PlayIcon class="h-4 w-4" />
                            Restart
                        </button>
                        <a
                            :href="route('admin.mail.dovecot.export')"
                            class="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700 shadow-sm hover:bg-slate-50"
                        >
                            <ArrowDownTrayIcon class="h-4 w-4 text-slate-500" />
                            Export Config
                        </a>
                    </div>
                    <p class="mt-3 text-xs text-slate-400">
                        Mail servisi kurulduğunda gerçek systemctl komutları çalışır. Şu an mock modda.
                    </p>
                </div>

            </template>

            <!-- ── TAB 2: CONFIGURATION ─────────────────────────────────────── -->
            <template v-if="activeTab === 'configuration'">
                <form @submit.prevent="submitConfig" class="space-y-6">

                    <div
                        v-for="(rows, category) in grouped"
                        :key="category"
                        class="rounded-xl border border-slate-200 bg-white shadow-sm"
                    >
                        <!-- Category header -->
                        <div class="flex items-center gap-2 border-b border-slate-100 px-5 py-3">
                            <Cog6ToothIcon class="h-4 w-4 text-slate-400" />
                            <h3 class="text-sm font-semibold text-slate-700">
                                {{ categoryLabels[category] ?? category }}
                            </h3>
                        </div>

                        <!-- Rows -->
                        <div class="divide-y divide-slate-50">
                            <div
                                v-for="row in rows"
                                :key="row.key"
                                class="grid grid-cols-1 gap-4 px-5 py-4 sm:grid-cols-3"
                            >
                                <!-- Key + description -->
                                <div class="sm:col-span-1">
                                    <label :for="`field-${row.key}`" class="block font-mono text-sm font-medium text-slate-800">
                                        {{ row.key }}
                                    </label>
                                    <p v-if="row.description_tr" class="mt-0.5 text-xs text-slate-500">
                                        {{ row.description_tr }}
                                    </p>
                                    <p class="mt-0.5 text-xs text-slate-400">
                                        Tip: <span class="font-mono">{{ row.data_type }}</span>
                                    </p>
                                </div>

                                <!-- Input -->
                                <div class="sm:col-span-2">
                                    <div class="flex items-center gap-2">

                                        <!-- Toggle (boolean enum yes/no) -->
                                        <template v-if="row.data_type === 'enum' && row.enum_values?.length === 2 && row.enum_values.includes('yes') && row.enum_values.includes('no')">
                                            <button
                                                type="button"
                                                @click="configForm.settings[row.key] = configForm.settings[row.key] === 'yes' ? 'no' : 'yes'"
                                                :class="[
                                                    'relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200',
                                                    configForm.settings[row.key] === 'yes' ? 'bg-sky-600' : 'bg-slate-200',
                                                ]"
                                            >
                                                <span
                                                    :class="[
                                                        'pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200',
                                                        configForm.settings[row.key] === 'yes' ? 'translate-x-5' : 'translate-x-0',
                                                    ]"
                                                />
                                            </button>
                                            <span class="text-sm text-slate-600">
                                                {{ configForm.settings[row.key] === 'yes' ? 'Evet' : 'Hayır' }}
                                            </span>
                                        </template>

                                        <!-- Enum select -->
                                        <template v-else-if="row.data_type === 'enum'">
                                            <select
                                                :id="`field-${row.key}`"
                                                v-model="configForm.settings[row.key]"
                                                class="block w-full rounded-lg border border-slate-200 bg-white px-3 py-2 font-mono text-sm focus:border-sky-500 focus:outline-none focus:ring-1 focus:ring-sky-500"
                                            >
                                                <option v-for="opt in row.enum_values" :key="opt" :value="opt">
                                                    {{ opt === '' ? '(boş)' : opt }}
                                                </option>
                                            </select>
                                        </template>

                                        <!-- Integer input -->
                                        <template v-else-if="row.data_type === 'integer'">
                                            <input
                                                :id="`field-${row.key}`"
                                                v-model="configForm.settings[row.key]"
                                                type="number"
                                                class="block w-full rounded-lg border border-slate-200 px-3 py-2 font-mono text-sm focus:border-sky-500 focus:outline-none focus:ring-1 focus:ring-sky-500"
                                            />
                                        </template>

                                        <!-- String / path input (monospace) -->
                                        <template v-else>
                                            <input
                                                :id="`field-${row.key}`"
                                                v-model="configForm.settings[row.key]"
                                                type="text"
                                                class="block w-full rounded-lg border border-slate-200 px-3 py-2 font-mono text-sm focus:border-sky-500 focus:outline-none focus:ring-1 focus:ring-sky-500"
                                            />
                                        </template>

                                        <!-- Reset to default -->
                                        <button
                                            type="button"
                                            @click="resetRowToDefault(row)"
                                            title="Varsayılana sıfırla"
                                            class="shrink-0 rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600"
                                        >
                                            <ArrowUturnLeftIcon class="h-4 w-4" />
                                        </button>
                                    </div>

                                    <p v-if="row.default_value" class="mt-1 font-mono text-xs text-slate-400">
                                        Varsayılan: {{ row.default_value }}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Footer actions -->
                    <div class="flex items-center justify-between rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                        <button
                            type="button"
                            @click="resetAll"
                            :disabled="resetAllForm.processing"
                            class="inline-flex items-center gap-2 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-600 hover:bg-slate-50 disabled:opacity-50"
                        >
                            <ArrowUturnLeftIcon class="h-4 w-4" />
                            Tümünü Sıfırla
                        </button>
                        <button
                            type="submit"
                            :disabled="configForm.processing"
                            class="inline-flex items-center gap-2 rounded-lg bg-sky-600 px-6 py-2 text-sm font-semibold text-white shadow-sm hover:bg-sky-700 disabled:opacity-50"
                        >
                            <BoltIcon class="h-4 w-4" />
                            Tümünü Kaydet
                        </button>
                    </div>
                </form>
            </template>

            <!-- ── TAB 3: SESSIONS ──────────────────────────────────────────── -->
            <template v-if="activeTab === 'sessions'">

                <!-- Search bar -->
                <div class="flex items-center gap-3 rounded-xl border border-slate-200 bg-white p-3 shadow-sm">
                    <FunnelIcon class="h-4 w-4 text-slate-400" />
                    <input
                        v-model="sessionSearch"
                        type="text"
                        placeholder="Kullanıcı adı, IP veya durum ara..."
                        class="flex-1 bg-transparent text-sm text-slate-700 placeholder-slate-400 focus:outline-none"
                    />
                    <button
                        v-if="sessionSearch"
                        @click="sessionSearch = ''"
                        class="text-slate-400 hover:text-slate-600"
                    >
                        <XMarkIcon class="h-4 w-4" />
                    </button>
                </div>

                <!-- Sessions table -->
                <div class="rounded-xl border border-slate-200 bg-white shadow-sm">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-slate-100">
                            <thead>
                                <tr class="bg-slate-50">
                                    <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">ID</th>
                                    <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Kullanıcı</th>
                                    <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">IP Adresi</th>
                                    <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Bağlantı Zamanı</th>
                                    <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Boş Süre</th>
                                    <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Durum</th>
                                    <th class="px-4 py-3 text-right text-xs font-semibold uppercase tracking-wide text-slate-500">İşlem</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-50">
                                <tr v-if="filteredSessions.length === 0">
                                    <td colspan="7" class="px-4 py-8 text-center text-sm text-slate-400">
                                        Aktif bağlantı bulunamadı.
                                    </td>
                                </tr>
                                <tr
                                    v-for="session in filteredSessions"
                                    :key="session.id"
                                    class="hover:bg-slate-50"
                                >
                                    <td class="px-4 py-3 font-mono text-xs text-slate-500">#{{ session.id }}</td>
                                    <td class="px-4 py-3 font-mono text-sm font-medium text-slate-900">{{ session.username }}</td>
                                    <td class="px-4 py-3 font-mono text-sm text-slate-600">{{ session.remote_ip }}</td>
                                    <td class="px-4 py-3 text-xs text-slate-500">
                                        <span class="flex items-center gap-1">
                                            <ClockIcon class="h-3.5 w-3.5 text-slate-400" />
                                            {{ session.connected_since }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 text-sm text-slate-600">
                                        {{ formatIdleSeconds(session.idle_seconds) }}
                                    </td>
                                    <td class="px-4 py-3">
                                        <span
                                            :class="['rounded-full px-2.5 py-0.5 text-xs font-semibold', stateBadgeClass(session.state)]"
                                        >
                                            {{ session.state }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 text-right">
                                        <button
                                            @click="killSession(session.id, session.username)"
                                            title="Oturumu sonlandır (doveadm kick)"
                                            class="inline-flex items-center gap-1 rounded-lg border border-red-200 bg-red-50 px-2.5 py-1 text-xs font-medium text-red-600 hover:bg-red-100"
                                        >
                                            <NoSymbolIcon class="h-3.5 w-3.5" />
                                            Kick
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="border-t border-slate-100 px-4 py-2.5 text-xs text-slate-400">
                        {{ filteredSessions.length }} aktif bağlantı gösteriliyor
                        <span v-if="sessionSearch"> (filtreli)</span>
                    </div>
                </div>

            </template>

        </div>
    </AdminLayout>
</template>
