<script setup>
import { reactive } from 'vue'
import { Head, Link, useForm } from '@inertiajs/vue3'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import { useConfirm } from '@/composables/useConfirm.js'
import {
    EnvelopeIcon,
    ArrowRightCircleIcon,
    GlobeAltIcon,
    PlusIcon,
    TrashIcon,
    InformationCircleIcon,
    BoltIcon,
    ServerIcon,
    CheckCircleIcon,
    Cog6ToothIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    rows: { type: Array, default: () => [] },
    modes: { type: Array, default: () => ['local', 'remote', 'backup', 'auto'] },
})

const { ask } = useConfirm()

// ── Per-domain forms ──────────────────────────────────────────────────────────
const forms = reactive({})

props.rows.forEach((row) => {
    forms[row.id] = useForm({
        routing_mode: row.routing.routing_mode ?? 'auto',
        primary_mx: row.routing.primary_mx ?? '',
        backup_mx: Array.isArray(row.routing.backup_mx) && row.routing.backup_mx.length
            ? row.routing.backup_mx.map(e => ({ priority: e.priority, hostname: e.hostname }))
            : [],
        remote_smtp_host: row.routing.remote_smtp_host ?? '',
        remote_smtp_port: row.routing.remote_smtp_port ?? 25,
        mx_priority: row.routing.mx_priority ?? 20,
        notes: row.routing.notes ?? '',
    })
})

const save = async (domainId, domainName) => {
    const mode = forms[domainId].routing_mode
    const ok = await ask({
        title: 'Mail Routing Uygula',
        message: `${domainName} için "${modeLabel(mode)}" modu uygulanacak ve Postfix transport_maps güncellenecek. Devam edilsin mi?`,
        variant: 'primary',
        confirmText: 'Uygula',
        cancelText: 'Vazgeç',
    })
    if (!ok) return

    forms[domainId].patch(route('customer.email.routing.update', domainId), {
        preserveScroll: true,
    })
}

// ── Backup MX helpers ─────────────────────────────────────────────────────────
const addBackupMx = (domainId) => {
    forms[domainId].backup_mx.push({ priority: 20, hostname: '' })
}

const removeBackupMx = (domainId, idx) => {
    forms[domainId].backup_mx.splice(idx, 1)
}

// ── Badge helpers ─────────────────────────────────────────────────────────────
const modeBadge = (mode) => ({
    local: 'bg-emerald-100 text-emerald-700 border-emerald-200',
    backup: 'bg-blue-100 text-blue-700 border-blue-200',
    remote: 'bg-amber-100 text-amber-700 border-amber-200',
    auto: 'bg-slate-100 text-slate-700 border-slate-200',
}[mode] ?? 'bg-slate-100 text-slate-700 border-slate-200')

const modeLabel = (mode) => ({
    local: 'Yerel (Local)',
    backup: 'Yedek MX (Backup)',
    remote: 'Uzak (Remote)',
    auto: 'Otomatik (Auto)',
}[mode] ?? mode)

const modeIcon = (mode) => ({
    local: ServerIcon,
    backup: ArrowRightCircleIcon,
    remote: BoltIcon,
    auto: CheckCircleIcon,
}[mode] ?? InformationCircleIcon)

const modeHelp = (mode) => ({
    local: 'Bu sunucu mail kabul eder ve doğrudan posta kutularına teslim eder. Domain MX kayıtları bu sunucuyu işaret eder.',
    remote: 'Mail başka bir SMTP sunucusunda. Bu sunucuya gelen postalar uzak sunucuya yönlendirilir; yerel teslim yapılmaz.',
    backup: 'Bu sunucu yedek MX olarak çalışır. Ana MX (uzak sunucu) erişilemezse buraya gelen postalar kuyruğa alınır ve ana MX kalkınca iletilir.',
    auto: 'Sistem MX kayıtlarına bakarak otomatik karar verir. MX bu sunucuyu işaret ediyorsa local, başka host işaret ediyorsa remote moda geçer. Önerilen.',
}[mode] ?? '')
</script>

<template>
    <Head title="Email Routing" />
    <CustomerLayout>
        <template #header>E-posta Routing (MX Yönetimi)</template>

        <!-- Tab nav -->
        <div class="mb-4 flex flex-wrap gap-1 border-b border-slate-200 text-sm">
            <Link :href="route('customer.email.index')" class="px-4 py-2 text-slate-600 hover:text-slate-900">Hesaplar</Link>
            <Link :href="route('customer.email.mailing-lists.index')" class="px-4 py-2 text-slate-600 hover:text-slate-900">Mailing Lists</Link>
            <Link :href="route('customer.email.spam.index')" class="px-4 py-2 text-slate-600 hover:text-slate-900">Spam Filtresi</Link>
            <Link :href="route('customer.email.deliverability.index')" class="px-4 py-2 text-slate-600 hover:text-slate-900">Deliverability</Link>
            <span class="px-4 py-2 font-medium border-b-2 border-indigo-600 text-indigo-700">Routing</span>
            <Link :href="route('customer.email.importer.index')" class="px-4 py-2 text-slate-600 hover:text-slate-900">Importer</Link>
        </div>

        <!-- Info banner — mode summary -->
        <div class="mb-6 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 mt-0.5" />
                <div class="space-y-1.5">
                    <p><strong>Local</strong> — Bu sunucu mail kabul + teslim eder.</p>
                    <p><strong>Remote</strong> — Mail başka SMTP sunucusunda; uzaktaki sunucuya forward eder.</p>
                    <p><strong>Backup</strong> — Bu sunucu yedek MX'tir; ana MX düştüğünde kuyruğa alır ve iletir.</p>
                    <p><strong>Auto</strong> — MX kayıtlarını okuyup otomatik karar verir (önerilen).</p>
                </div>
            </div>
        </div>

        <!-- Empty state -->
        <div v-if="rows.length === 0" class="rounded-xl border border-dashed border-slate-300 bg-white p-12 text-center">
            <EnvelopeIcon class="mx-auto h-14 w-14 text-slate-300" />
            <h3 class="mt-3 text-lg font-semibold text-slate-600">Henüz alan adı yok</h3>
            <p class="mt-1 text-sm text-slate-400">Main veya addon domainler eklendikten sonra burada görünür.</p>
        </div>

        <!-- Domain cards -->
        <div v-else class="space-y-4">
            <div
                v-for="row in rows"
                :key="row.id"
                class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm"
            >
                <!-- Card header -->
                <div class="mb-4 flex flex-wrap items-center justify-between gap-2">
                    <div class="flex items-center gap-2">
                        <GlobeAltIcon class="h-5 w-5 text-slate-400" />
                        <span class="font-mono font-semibold text-slate-800">{{ row.name }}</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <span
                            v-if="row.routing.last_applied_at"
                            class="text-xs text-slate-400"
                            :title="`Son uygulanma: ${row.routing.last_applied_at}`"
                        >
                            Postfix yazıldı
                        </span>
                        <span :class="['inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-semibold', modeBadge(forms[row.id].routing_mode)]">
                            <component :is="modeIcon(forms[row.id].routing_mode)" class="h-3.5 w-3.5" />
                            {{ modeLabel(forms[row.id].routing_mode) }}
                        </span>
                    </div>
                </div>

                <form @submit.prevent="save(row.id, row.name)" class="space-y-4">
                    <!-- Routing mode radios -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-2">Mail Routing Modu</label>
                        <div class="grid grid-cols-2 gap-2 sm:grid-cols-4">
                            <label
                                v-for="mode in modes"
                                :key="mode"
                                :class="[
                                    'flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2.5 text-sm transition-colors',
                                    forms[row.id].routing_mode === mode
                                        ? 'border-indigo-400 bg-indigo-50 text-indigo-800'
                                        : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50 text-slate-700'
                                ]"
                            >
                                <input
                                    v-model="forms[row.id].routing_mode"
                                    type="radio"
                                    :value="mode"
                                    class="accent-indigo-600"
                                />
                                <component :is="modeIcon(mode)" class="h-4 w-4" />
                                <span class="font-medium capitalize">{{ mode }}</span>
                            </label>
                        </div>
                        <p class="mt-2 text-xs text-slate-500">
                            <InformationCircleIcon class="inline h-3.5 w-3.5 -mt-0.5" />
                            {{ modeHelp(forms[row.id].routing_mode) }}
                        </p>
                    </div>

                    <!-- Remote SMTP — for remote/backup -->
                    <div v-if="['remote', 'backup'].includes(forms[row.id].routing_mode)" class="rounded-lg border border-amber-200 bg-amber-50/50 p-4 space-y-3">
                        <div class="flex items-center gap-2 text-sm font-medium text-amber-900">
                            <Cog6ToothIcon class="h-4 w-4" />
                            Uzak SMTP Sunucu Ayarları
                        </div>

                        <div class="grid grid-cols-1 gap-3 sm:grid-cols-3">
                            <div class="sm:col-span-2">
                                <label class="block text-xs font-medium text-slate-700 mb-1">SMTP Host <span class="text-red-500">*</span></label>
                                <input
                                    v-model="forms[row.id].remote_smtp_host"
                                    type="text"
                                    placeholder="mail.uzaksunucu.com"
                                    class="w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm focus:border-indigo-400 focus:ring-1 focus:ring-indigo-300"
                                />
                                <p v-if="forms[row.id].errors.remote_smtp_host" class="mt-1 text-xs text-red-600">{{ forms[row.id].errors.remote_smtp_host }}</p>
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-slate-700 mb-1">SMTP Port</label>
                                <input
                                    v-model.number="forms[row.id].remote_smtp_port"
                                    type="number"
                                    min="1"
                                    max="65535"
                                    placeholder="25"
                                    class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-400 focus:ring-1 focus:ring-indigo-300"
                                />
                                <p v-if="forms[row.id].errors.remote_smtp_port" class="mt-1 text-xs text-red-600">{{ forms[row.id].errors.remote_smtp_port }}</p>
                            </div>
                        </div>

                        <!-- Backup-only — MX priority -->
                        <div v-if="forms[row.id].routing_mode === 'backup'">
                            <label class="block text-xs font-medium text-slate-700 mb-1">Bu Sunucunun MX Önceliği <span class="text-red-500">*</span></label>
                            <input
                                v-model.number="forms[row.id].mx_priority"
                                type="number"
                                min="0"
                                max="65535"
                                placeholder="20"
                                class="w-32 rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-400 focus:ring-1 focus:ring-indigo-300"
                            />
                            <p class="mt-1 text-xs text-slate-500">Ana MX'in önceliğinden büyük olmalı (örn. ana 10 ise bu 20).</p>
                            <p v-if="forms[row.id].errors.mx_priority" class="mt-1 text-xs text-red-600">{{ forms[row.id].errors.mx_priority }}</p>
                        </div>
                    </div>

                    <!-- Primary MX — only for local -->
                    <div v-if="forms[row.id].routing_mode === 'local'">
                        <label class="block text-sm font-medium text-slate-700 mb-1">Ana MX Sunucu <span class="text-slate-400 font-normal">(opsiyonel — boş bırakılırsa otomatik mail.{{ row.name }})</span></label>
                        <input
                            v-model="forms[row.id].primary_mx"
                            type="text"
                            :placeholder="`mail.${row.name}`"
                            class="w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm focus:border-indigo-400 focus:ring-1 focus:ring-indigo-300"
                        />
                        <p v-if="forms[row.id].errors.primary_mx" class="mt-1 text-xs text-red-600">{{ forms[row.id].errors.primary_mx }}</p>
                    </div>

                    <!-- Extra backup MX entries -->
                    <div v-if="forms[row.id].routing_mode === 'backup'">
                        <div class="mb-2 flex items-center justify-between">
                            <label class="block text-sm font-medium text-slate-700">Ek Yedek MX Kayıtları <span class="text-slate-400 font-normal">(opsiyonel)</span></label>
                            <button
                                type="button"
                                @click="addBackupMx(row.id)"
                                class="inline-flex items-center gap-1 rounded-lg border border-slate-300 bg-white px-2.5 py-1 text-xs font-medium text-slate-700 hover:bg-slate-50"
                            >
                                <PlusIcon class="h-3.5 w-3.5" /> Ekle
                            </button>
                        </div>

                        <div v-if="forms[row.id].backup_mx.length === 0" class="rounded-lg border border-dashed border-slate-200 bg-slate-50 p-3 text-center text-xs text-slate-400">
                            Henüz ek yedek MX kaydı yok.
                        </div>

                        <div v-else class="space-y-2">
                            <div
                                v-for="(entry, idx) in forms[row.id].backup_mx"
                                :key="idx"
                                class="flex items-center gap-2"
                            >
                                <div class="w-24">
                                    <input
                                        v-model.number="entry.priority"
                                        type="number"
                                        min="0"
                                        max="65535"
                                        placeholder="30"
                                        class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm text-center focus:border-indigo-400 focus:ring-1 focus:ring-indigo-300"
                                    />
                                    <p class="mt-0.5 text-center text-[10px] text-slate-400">Öncelik</p>
                                </div>
                                <div class="flex-1">
                                    <input
                                        v-model="entry.hostname"
                                        type="text"
                                        placeholder="backup-mail.example.com"
                                        class="w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm focus:border-indigo-400 focus:ring-1 focus:ring-indigo-300"
                                    />
                                </div>
                                <button
                                    type="button"
                                    @click="removeBackupMx(row.id, idx)"
                                    class="rounded-lg p-2 text-red-400 hover:bg-red-50 hover:text-red-600"
                                >
                                    <TrashIcon class="h-4 w-4" />
                                </button>
                            </div>
                        </div>
                        <p v-if="forms[row.id].errors.backup_mx" class="mt-1 text-xs text-red-600">{{ forms[row.id].errors.backup_mx }}</p>
                    </div>

                    <!-- Notes -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Notlar <span class="text-slate-400 font-normal">(opsiyonel)</span></label>
                        <textarea
                            v-model="forms[row.id].notes"
                            rows="2"
                            maxlength="500"
                            placeholder="Bu domain için ek açıklama…"
                            class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm resize-none focus:border-indigo-400 focus:ring-1 focus:ring-indigo-300"
                        />
                        <p v-if="forms[row.id].errors.notes" class="mt-1 text-xs text-red-600">{{ forms[row.id].errors.notes }}</p>
                    </div>

                    <!-- Save button -->
                    <div class="flex items-center justify-between border-t border-slate-100 pt-3">
                        <p class="text-xs text-slate-400">
                            Uygulandığında Postfix transport_maps yazılır ve DNS MX kayıtları senkronize edilir.
                        </p>
                        <button
                            type="submit"
                            :disabled="forms[row.id].processing"
                            class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-5 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50"
                        >
                            <CheckCircleIcon class="h-4 w-4" />
                            {{ forms[row.id].processing ? 'Uygulanıyor…' : 'Uygula' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </CustomerLayout>
</template>
