<script setup>
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { Head, Link, router, useForm, usePage } from '@inertiajs/vue3'
import { computed, ref } from 'vue'
import {
    ArrowLeftIcon, EnvelopeIcon, ServerStackIcon, KeyIcon, ShieldCheckIcon,
    PauseIcon, PlayIcon, ChartBarSquareIcon, ArrowsRightLeftIcon, MegaphoneIcon,
    GlobeAltIcon, UserCircleIcon, ClipboardDocumentIcon, ClipboardDocumentCheckIcon,
    InformationCircleIcon, CheckCircleIcon, ExclamationTriangleIcon,
    LockClosedIcon, CalendarDaysIcon, ClockIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    mailbox: { type: Object, required: true },
    forwarders: { type: Array, default: () => [] },
    autoresponders: { type: Array, default: () => [] },
    domain_stats: { type: Object, default: null },
    connect_info: { type: Object, required: true },
    is_windows_dev: { type: Boolean, default: false },
})

const page = usePage()
const flashNewPassword = computed(() => page.props.flash?.new_password || null)

const showQuotaModal = ref(false)
const showPasswordResult = ref(false)
const copied = ref({})

const quotaForm = useForm({ quota_mb: props.mailbox.quota_mb || 1024 })

function submitQuota() {
    quotaForm.patch(route('admin.mail.storage.quota', { id: props.mailbox.id }), {
        preserveScroll: true,
        onSuccess: () => { showQuotaModal.value = false },
    })
}

async function toggleStatus() {
    const action = props.mailbox.status === 'active' ? 'askıya almak' : 'aktive etmek'
    const ok = await ask({
        title: 'Onaylayın',
        message: `${props.mailbox.email} ${action} istediğinizden emin misiniz?`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('admin.mail.storage.toggle', { id: props.mailbox.id }), {}, { preserveScroll: true })
}

async function resetPassword() {
    const ok = await ask({
        title: 'Onaylayın',
        message: `${props.mailbox.email} için yeni rastgele parola üretilecek. Eski parola geçersiz olacak. Devam?`,
        variant: 'warning',
        confirmText: 'Onayla',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('admin.mail.storage.reset-password', { id: props.mailbox.id }), {}, {
        preserveScroll: true,
        onSuccess: () => { showPasswordResult.value = true },
    })
}

function copy(key, text) {
    navigator.clipboard?.writeText(text).then(() => {
        copied.value = { ...copied.value, [key]: true }
        setTimeout(() => {
            const c = { ...copied.value }
            delete c[key]
            copied.value = c
        }, 1500)
    })
}

const quotaColor = computed(() => {
    const p = props.mailbox.usage_percent
    if (p >= 90) return 'bg-red-500'
    if (p >= 70) return 'bg-amber-500'
    return 'bg-emerald-500'
})

const statusBadge = computed(() => {
    if (props.mailbox.status === 'active') {
        return { color: 'emerald', label: 'Aktif', icon: CheckCircleIcon }
    }
    return { color: 'red', label: 'Askıda', icon: ExclamationTriangleIcon }
})
</script>

<template>
    <Head :title="`${mailbox.email} — Mailbox Detayı`" />
    <AdminLayout>
        <template #header>
            <Link :href="route('admin.mail.storage.index')" class="text-slate-400 hover:text-indigo-600 mr-2">
                <ArrowLeftIcon class="h-5 w-5" />
            </Link>
            <span>Mailbox:</span>
            <code class="font-mono text-base text-indigo-600 dark:text-indigo-400 bg-indigo-50 dark:bg-indigo-900/30 px-2 py-0.5 rounded ml-1">{{ mailbox.email }}</code>
        </template>

        <!-- New password flash -->
        <div v-if="flashNewPassword"
             class="mb-6 rounded-xl border border-amber-300 dark:border-amber-700 bg-amber-50 dark:bg-amber-950/30 p-4">
            <div class="flex items-start gap-3">
                <ExclamationTriangleIcon class="h-5 w-5 text-amber-600 shrink-0 mt-0.5" />
                <div class="flex-1">
                    <p class="text-sm font-semibold text-amber-900 dark:text-amber-200">Yeni Parola Üretildi</p>
                    <p class="mt-0.5 text-xs text-amber-800 dark:text-amber-300">
                        Bu parola sadece bir kere gösterilir. Müşteriye güvenli kanaldan iletin.
                    </p>
                    <div class="mt-3 flex items-center gap-2">
                        <code class="flex-1 font-mono text-base font-bold bg-white dark:bg-slate-800 px-3 py-2 rounded border border-amber-300 dark:border-amber-700">{{ flashNewPassword }}</code>
                        <button @click="copy('pw', flashNewPassword)" type="button"
                                class="rounded-lg bg-amber-600 px-3 py-2 text-xs font-semibold text-white hover:bg-amber-700">
                            <component :is="copied.pw ? ClipboardDocumentCheckIcon : ClipboardDocumentIcon" class="h-4 w-4" />
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- ─── Üst Kart: Mailbox Bilgisi + Aksiyonlar ─── -->
        <div class="rounded-2xl bg-gradient-to-br from-indigo-600 via-purple-600 to-pink-600 p-px shadow-xl">
            <div class="rounded-2xl bg-white dark:bg-slate-900 p-6 lg:p-8">
                <div class="flex items-start justify-between flex-wrap gap-6">
                    <div class="flex items-start gap-4">
                        <div class="rounded-xl bg-gradient-to-br from-indigo-500 to-purple-600 p-3 shadow-lg shadow-indigo-500/30">
                            <EnvelopeIcon class="h-7 w-7 text-white" />
                        </div>
                        <div>
                            <p class="text-xs uppercase tracking-widest font-semibold text-indigo-600 dark:text-indigo-400">
                                E-posta Hesabı
                            </p>
                            <h2 class="mt-1 text-3xl font-bold text-slate-900 dark:text-white font-mono">{{ mailbox.email }}</h2>
                            <div class="mt-2 flex items-center gap-3 flex-wrap text-sm">
                                <span :class="['inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 font-medium',
                                    `bg-${statusBadge.color}-100 text-${statusBadge.color}-700 dark:bg-${statusBadge.color}-900/30 dark:text-${statusBadge.color}-400 ring-1 ring-${statusBadge.color}-200 dark:ring-${statusBadge.color}-800`]">
                                    <component :is="statusBadge.icon" class="h-3.5 w-3.5" />
                                    {{ statusBadge.label }}
                                </span>
                                <span class="text-slate-500 dark:text-slate-400 flex items-center gap-1">
                                    <UserCircleIcon class="h-4 w-4" />
                                    <span class="font-mono">{{ mailbox.account_username }}</span>
                                </span>
                                <span class="text-slate-500 dark:text-slate-400 flex items-center gap-1">
                                    <CalendarDaysIcon class="h-4 w-4" />
                                    {{ mailbox.created_at_human }}
                                </span>
                            </div>
                        </div>
                    </div>

                    <div class="flex flex-wrap gap-2">
                        <button @click="showQuotaModal = true" type="button"
                                class="inline-flex items-center gap-1.5 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-semibold text-white hover:bg-indigo-700">
                            <ChartBarSquareIcon class="h-4 w-4" />
                            Quota Değiştir
                        </button>
                        <button @click="resetPassword" type="button"
                                class="inline-flex items-center gap-1.5 rounded-lg bg-amber-600 px-4 py-2 text-sm font-semibold text-white hover:bg-amber-700">
                            <KeyIcon class="h-4 w-4" />
                            Parola Sıfırla
                        </button>
                        <Link :href="route('admin.mail.storage.activity', { id: mailbox.id })"
                              class="inline-flex items-center gap-1.5 rounded-lg bg-slate-700 px-4 py-2 text-sm font-semibold text-white hover:bg-slate-800">
                            <ClockIcon class="h-4 w-4" />
                            Aktivite Log
                            <span aria-hidden="true">&rarr;</span>
                        </Link>
                        <button @click="toggleStatus" type="button"
                                :class="['inline-flex items-center gap-1.5 rounded-lg px-4 py-2 text-sm font-semibold text-white',
                                    mailbox.status === 'active' ? 'bg-red-600 hover:bg-red-700' : 'bg-emerald-600 hover:bg-emerald-700']">
                            <component :is="mailbox.status === 'active' ? PauseIcon : PlayIcon" class="h-4 w-4" />
                            {{ mailbox.status === 'active' ? 'Askıya Al' : 'Aktive Et' }}
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- ─── 2-kolon: Storage + Connect Info ─── -->
        <div class="mt-6 grid grid-cols-1 lg:grid-cols-2 gap-5">
            <!-- Storage -->
            <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-5">
                <h3 class="text-base font-semibold text-slate-900 dark:text-slate-100 flex items-center gap-2 mb-4">
                    <ServerStackIcon class="h-5 w-5 text-indigo-500" />
                    Depolama Kullanımı
                </h3>
                <div class="space-y-3">
                    <div>
                        <div class="flex items-center justify-between mb-1.5">
                            <span class="text-sm text-slate-500">Kullanım / Quota</span>
                            <span class="text-sm font-semibold text-slate-900 dark:text-slate-100">
                                {{ mailbox.usage_mb }} MB / {{ mailbox.quota_mb }} MB
                            </span>
                        </div>
                        <div class="h-2.5 bg-slate-100 dark:bg-slate-700 rounded-full overflow-hidden">
                            <div :class="['h-full transition-all', quotaColor]"
                                 :style="{ width: Math.min(100, mailbox.usage_percent) + '%' }"></div>
                        </div>
                        <div class="mt-1 flex items-center justify-between text-xs">
                            <span class="text-slate-400">{{ (mailbox.usage_gb || 0).toFixed(3) }} GB</span>
                            <span :class="['font-semibold', mailbox.usage_percent >= 90 ? 'text-red-600' : mailbox.usage_percent >= 70 ? 'text-amber-600' : 'text-emerald-600']">
                                %{{ mailbox.usage_percent }}
                            </span>
                        </div>
                    </div>

                    <div v-if="domain_stats" class="mt-4 rounded-lg bg-slate-50 dark:bg-slate-900 p-3 text-xs">
                        <p class="font-semibold text-slate-700 dark:text-slate-300 mb-1.5 flex items-center gap-1.5">
                            <GlobeAltIcon class="h-3.5 w-3.5" />
                            {{ mailbox.domain }} domain'inde:
                        </p>
                        <p class="text-slate-500">
                            <strong>{{ domain_stats.count }}</strong> hesap ·
                            Toplam <strong>{{ domain_stats.usage_mb }} MB</strong> kullanım /
                            <strong>{{ domain_stats.quota_mb }} MB</strong> quota
                        </p>
                    </div>
                </div>
            </div>

            <!-- Connect Info -->
            <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-5">
                <h3 class="text-base font-semibold text-slate-900 dark:text-slate-100 flex items-center gap-2 mb-4">
                    <LockClosedIcon class="h-5 w-5 text-emerald-500" />
                    Bağlantı Bilgisi
                </h3>
                <div class="space-y-3 text-sm">
                    <div class="grid grid-cols-2 gap-2">
                        <div class="rounded-lg bg-slate-50 dark:bg-slate-900 p-3">
                            <p class="text-xs uppercase tracking-wider text-slate-500 font-semibold mb-1">Gelen (IMAP)</p>
                            <code class="block font-mono text-xs">{{ connect_info.imap_host }}</code>
                            <p class="mt-1 text-xs text-slate-500">
                                <strong>{{ connect_info.imap_port_ssl }}</strong> (SSL/TLS) veya
                                <strong>{{ connect_info.imap_port_starttls }}</strong> (STARTTLS)
                            </p>
                        </div>
                        <div class="rounded-lg bg-slate-50 dark:bg-slate-900 p-3">
                            <p class="text-xs uppercase tracking-wider text-slate-500 font-semibold mb-1">Giden (SMTP)</p>
                            <code class="block font-mono text-xs">{{ connect_info.imap_host }}</code>
                            <p class="mt-1 text-xs text-slate-500">
                                <strong>{{ connect_info.smtp_port_ssl }}</strong> (SSL) veya
                                <strong>{{ connect_info.smtp_port_starttls }}</strong> (STARTTLS)
                            </p>
                        </div>
                    </div>
                    <div class="rounded-lg bg-indigo-50 dark:bg-indigo-950/30 p-3 text-xs">
                        <p class="font-semibold text-indigo-900 dark:text-indigo-200 mb-1.5">Kullanıcı bilgisi:</p>
                        <code class="block font-mono text-indigo-700 dark:text-indigo-300">{{ mailbox.email }}</code>
                        <p class="mt-1 text-indigo-700 dark:text-indigo-300/80">Parola: Müşteriye verilen veya admin tarafından sıfırlanan</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- ─── 2-kolon: Forwarders + Autoresponders ─── -->
        <div class="mt-5 grid grid-cols-1 lg:grid-cols-2 gap-5">
            <!-- Forwarders -->
            <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 overflow-hidden">
                <div class="px-5 py-3 border-b border-slate-100 dark:border-slate-700 flex items-center gap-2">
                    <ArrowsRightLeftIcon class="h-4 w-4 text-sky-500" />
                    <h3 class="text-sm font-semibold text-slate-900 dark:text-slate-100">
                        Yönlendirmeler ({{ forwarders.length }})
                    </h3>
                </div>
                <ul v-if="forwarders.length > 0" class="divide-y divide-slate-100 dark:divide-slate-700">
                    <li v-for="f in forwarders" :key="f.id" class="px-5 py-3 text-xs">
                        <div class="flex items-center gap-2 mb-1">
                            <span class="font-mono text-slate-900 dark:text-slate-100 truncate">{{ f.source }}</span>
                            <span class="text-slate-400">→</span>
                            <span class="font-mono text-slate-700 dark:text-slate-300 truncate flex-1">
                                {{ Array.isArray(f.destinations) ? f.destinations.join(', ') : f.destinations }}
                            </span>
                        </div>
                        <p v-if="f.keep_local_copy" class="text-slate-500 text-[10px]">
                            ✓ Yerel kopyayı da sakla
                        </p>
                    </li>
                </ul>
                <p v-else class="px-5 py-8 text-center text-sm text-slate-400">Yönlendirme yok</p>
            </div>

            <!-- Autoresponders -->
            <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 overflow-hidden">
                <div class="px-5 py-3 border-b border-slate-100 dark:border-slate-700 flex items-center gap-2">
                    <MegaphoneIcon class="h-4 w-4 text-purple-500" />
                    <h3 class="text-sm font-semibold text-slate-900 dark:text-slate-100">
                        Otomatik Yanıtlayıcılar ({{ autoresponders.length }})
                    </h3>
                </div>
                <ul v-if="autoresponders.length > 0" class="divide-y divide-slate-100 dark:divide-slate-700">
                    <li v-for="a in autoresponders" :key="a.id" class="px-5 py-3 text-xs">
                        <div class="flex items-center gap-2 mb-1">
                            <span :class="['inline-flex h-2 w-2 rounded-full', a.active ? 'bg-emerald-500' : 'bg-slate-300']"></span>
                            <span class="font-semibold text-slate-900 dark:text-slate-100 truncate">{{ a.subject }}</span>
                        </div>
                        <p class="text-slate-500 truncate">{{ (a.body || '').substring(0, 80) }}...</p>
                    </li>
                </ul>
                <p v-else class="px-5 py-8 text-center text-sm text-slate-400">Otomatik yanıt yok</p>
            </div>
        </div>

        <!-- ─── Quota Modal ─── -->
        <div v-if="showQuotaModal"
             class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 backdrop-blur-sm p-4">
            <div class="w-full max-w-md rounded-2xl bg-white dark:bg-slate-800 p-6 shadow-2xl">
                <h3 class="text-lg font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2 mb-4">
                    <ChartBarSquareIcon class="h-5 w-5 text-indigo-500" />
                    Quota Değiştir
                </h3>
                <p class="text-sm text-slate-500 dark:text-slate-400 mb-4">
                    <code class="font-mono">{{ mailbox.email }}</code> için yeni quota değeri (MB cinsinden).
                    Mevcut kullanım: <strong>{{ mailbox.usage_mb }} MB</strong>
                </p>
                <form @submit.prevent="submitQuota" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium mb-1">Yeni Quota (MB)</label>
                        <input v-model.number="quotaForm.quota_mb" type="number" min="0" max="1048576" required
                               class="w-full rounded-lg border border-slate-300 dark:border-slate-600 dark:bg-slate-900 px-3 py-2 font-mono" />
                        <p class="mt-1 text-xs text-slate-500">
                            0 = sınırsız. Önerilen: 1024 (1 GB), 2048 (2 GB), 5120 (5 GB)
                        </p>
                    </div>
                    <div class="flex justify-end gap-2 pt-2">
                        <button type="button" @click="showQuotaModal = false"
                                class="rounded-lg border border-slate-300 dark:border-slate-600 px-4 py-2 text-sm">
                            İptal
                        </button>
                        <button type="submit" :disabled="quotaForm.processing"
                                class="rounded-lg bg-indigo-600 px-5 py-2 text-sm font-semibold text-white hover:bg-indigo-700 disabled:opacity-50">
                            <span v-if="quotaForm.processing">Kaydediliyor...</span>
                            <span v-else>Kaydet</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </AdminLayout>
</template>
