<script setup>
import { ref } from 'vue'
import { Head, Link, router, useForm } from '@inertiajs/vue3'
import axios from 'axios'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import { useConfirm } from '@/composables/useConfirm'
import { EnvelopeIcon, PlusIcon, TrashIcon, KeyIcon, XMarkIcon, ArrowRightIcon, InboxIcon, AtSymbolIcon, InformationCircleIcon, FunnelIcon, ChatBubbleLeftRightIcon, ArrowTopRightOnSquareIcon, WrenchScrewdriverIcon, GlobeAltIcon } from '@heroicons/vue/24/outline'
import EmptyState from '@/Components/EmptyState.vue'

const { ask } = useConfirm()

const props = defineProps({
    emails: Array,
    forwarders: Array,
    available_domains: Array,
    limit: Number,
    usage: Number,
})

const activeTab = ref('accounts')
const showEmailForm = ref(false)
const showFwdForm = ref(false)

const emailForm = useForm({
    local: '',
    domain: props.available_domains[0] ?? '',
    password: '',
    quota_mb: 1024,
})

const fwdForm = useForm({
    source: '',
    destinations: '',
    keep_local_copy: false,
})

const submitEmail = () => emailForm.post(route('customer.email.store'), {
    onSuccess: () => { showEmailForm.value = false; emailForm.reset(); emailForm.quota_mb = 1024; emailForm.domain = props.available_domains[0] ?? '' },
})

const submitFwd = () => fwdForm.post(route('customer.email.forwarders.store'), {
    onSuccess: () => { showFwdForm.value = false; fwdForm.reset() },
})

const removeEmail = async (e) => {
    const ok = await ask({
        title: 'E-posta hesabını sil',
        message: `'${e.email}' hesabı ve tüm posta kutusu kalıcı olarak silinecek.`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('customer.email.destroy', e.id))
}

// Webmail oto-giriş — token üret, yeni sekmede aç
const webmailLoading = ref({})
const openWebmail = async (e) => {
    if (webmailLoading.value[e.id]) return
    webmailLoading.value[e.id] = true
    try {
        const { data } = await axios.post(route('customer.email.webmail-sso', { emailAccount: e.id }))
        if (data?.redirect_url) {
            window.open(data.redirect_url, '_blank', 'noopener')
        } else {
            // Webmail kurulu değil — admin ise install hint'a yönlendir
            const msg = data?.message || 'Webmail kurulu değil veya URL üretilemedi.'
            if (data?.install_hint_url) {
                const go = await ask({
                    title: 'Webmail bulunamadı',
                    message: msg + '\n\nMail Stack → Webmail kurulum sayfasına gidelim mi?',
                    variant: 'info',
                    confirmText: 'Kuruluma Git',
                    cancelText: 'İptal',
                })
                if (go) window.location.href = data.install_hint_url
                else window.$toast?.error?.(msg) || alert(msg)
            } else {
                window.$toast?.error?.(msg) || alert(msg)
            }
        }
    } catch (err) {
        const data = err?.response?.data
        const msg = data?.message || 'Webmail açılamadı.'
        if (data?.install_hint_url) {
            const go = await ask({
                title: 'Webmail kurulu değil',
                message: msg + '\n\nKurulum sayfasına gidelim mi?',
                variant: 'info',
                confirmText: 'Kuruluma Git',
                cancelText: 'İptal',
            })
            if (go) window.location.href = data.install_hint_url
            else window.$toast?.error?.(msg) || alert(msg)
        } else {
            window.$toast?.error?.(msg) || alert(msg)
        }
    } finally {
        webmailLoading.value[e.id] = false
    }
}

const removeFwd = async (f) => {
    const ok = await ask({
        title: 'Yönlendirmeyi sil',
        message: `'${f.source}' yönlendirmesi silinecek.`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('customer.email.forwarders.destroy', f.id))
}

const generatePassword = () => {
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#'
    let pwd = ''
    for (let i = 0; i < 16; i++) pwd += chars.charAt(Math.floor(Math.random() * chars.length))
    emailForm.password = pwd
}
</script>

<template>
    <Head title="E-postalarım" />

    <CustomerLayout>
        <template #header>E-posta Yönetimi</template>

        <!-- E-posta hesabı oluşturulduğunda anında SMTP/IMAP/Webmail erişimi aktif -->
        <div class="mb-4 rounded-xl border border-emerald-200 dark:border-emerald-800 bg-gradient-to-br from-emerald-50 to-teal-50 dark:from-emerald-950/30 dark:to-teal-950/30 p-4 text-sm text-emerald-900 dark:text-emerald-200">
            <div class="flex gap-3">
                <InformationCircleIcon class="h-5 w-5 flex-shrink-0 text-emerald-600 dark:text-emerald-400" />
                <div class="flex-1">
                    <strong>Tam Mail Stack aktif:</strong> Hesap oluşturur oluşturmaz
                    <span class="font-mono bg-white/60 dark:bg-slate-800/60 px-1.5 py-0.5 rounded text-xs">IMAP/SMTP</span>
                    ile mail client'larınızdan,
                    <span class="font-mono bg-white/60 dark:bg-slate-800/60 px-1.5 py-0.5 rounded text-xs">/webmail</span>
                    ile tarayıcıdan erişebilirsiniz. DKIM/SPF/DMARC otomatik yapılandırılır.
                </div>
            </div>
        </div>

        <!-- Tabs -->
        <div class="mb-4 flex flex-wrap gap-1 border-b border-slate-200">
            <button @click="activeTab = 'accounts'" :class="['px-4 py-2 text-sm font-medium border-b-2', activeTab === 'accounts' ? 'border-indigo-600 text-indigo-700' : 'border-transparent text-slate-600 hover:text-slate-900']">
                <InboxIcon class="inline h-4 w-4 mr-1" /> Hesaplar ({{ emails.length }})
            </button>
            <button @click="activeTab = 'forwarders'" :class="['px-4 py-2 text-sm font-medium border-b-2', activeTab === 'forwarders' ? 'border-indigo-600 text-indigo-700' : 'border-transparent text-slate-600 hover:text-slate-900']">
                <ArrowRightIcon class="inline h-4 w-4 mr-1" /> Yönlendirmeler ({{ forwarders.length }})
            </button>
            <Link :href="route('customer.email.webmail.index')" class="px-4 py-2 text-sm font-medium border-b-2 border-transparent text-rose-700 hover:text-rose-900">
                <ArrowTopRightOnSquareIcon class="inline h-4 w-4 mr-1" /> Webmail
            </Link>
            <Link :href="route('customer.email.autoresponders.index')" class="px-4 py-2 text-sm font-medium border-b-2 border-transparent text-slate-600 hover:text-slate-900">
                <ChatBubbleLeftRightIcon class="inline h-4 w-4 mr-1" /> Otomatik Yanıt
            </Link>
            <Link :href="route('customer.email.filters.index')" class="px-4 py-2 text-sm font-medium border-b-2 border-transparent text-slate-600 hover:text-slate-900">
                <FunnelIcon class="inline h-4 w-4 mr-1" /> Filtreler
            </Link>
            <Link :href="route('customer.email.setup')" class="px-4 py-2 text-sm font-medium border-b-2 border-transparent text-emerald-700 hover:text-emerald-900">
                <WrenchScrewdriverIcon class="inline h-4 w-4 mr-1" /> Kurulum Sihirbazı
            </Link>
        </div>

        <!-- Accounts tab -->
        <div v-if="activeTab === 'accounts'">
            <div class="mb-4 flex items-center justify-between">
                <p class="text-sm text-slate-600">
                    {{ usage }} hesap / {{ limit === 0 || limit === null ? '∞' : limit }} limit
                </p>
                <button @click="showEmailForm = true" :disabled="!available_domains.length" class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50">
                    <PlusIcon class="h-4 w-4" /> Yeni E-posta Hesabı
                </button>
            </div>

            <div v-if="!available_domains.length" class="rounded-xl border border-dashed border-slate-300 bg-white p-8 text-center text-sm text-slate-500">
                Önce bir alan adı eklemelisiniz.
            </div>
            <EmptyState
                v-else-if="emails.length === 0"
                :icon="EnvelopeIcon"
                title="Henüz e-posta hesabı yok"
                description="Domain'iniz altında info@, sales@ gibi adresler oluşturun."
            />
            <div v-else class="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm">
                <table class="min-w-full divide-y divide-slate-200">
                    <thead class="bg-slate-50">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-slate-500">E-posta</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-slate-500">Kota</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-slate-500">Kullanım</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-slate-500">Otoresponder</th>
                            <th class="px-4 py-3"></th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                        <tr v-for="e in emails" :key="e.id"
                            @click="$inertia.visit(route('customer.email.show', { emailAccount: e.id }))"
                            class="hover:bg-slate-50 cursor-pointer">
                            <td class="px-4 py-2 font-mono text-sm font-semibold text-indigo-700">{{ e.email }} →</td>
                            <td class="px-4 py-2 text-sm">{{ e.quota_mb === -1 ? 'sınırsız' : e.quota_mb + ' MB' }}</td>
                            <td class="px-4 py-2">
                                <div v-if="e.usage_percent !== null" class="flex items-center gap-2">
                                    <div class="h-1.5 w-20 overflow-hidden rounded-full bg-slate-200">
                                        <div class="h-full bg-emerald-500" :style="{ width: Math.min(e.usage_percent, 100) + '%' }"></div>
                                    </div>
                                    <span class="text-xs text-slate-600">%{{ e.usage_percent }}</span>
                                </div>
                                <span v-else class="text-xs text-slate-400">—</span>
                            </td>
                            <td class="px-4 py-2 text-xs text-slate-500">{{ e.autoresponders_count }}</td>
                            <td class="px-4 py-2 text-right" @click.stop>
                                <button @click="openWebmail(e)"
                                        :disabled="webmailLoading[e.id]"
                                        class="inline-flex items-center gap-1 rounded-lg border border-emerald-300 bg-emerald-50 px-2 py-1 text-xs font-medium text-emerald-700 hover:bg-emerald-100 disabled:opacity-50 mr-1"
                                        title="Webmail'e tek tıkla giriş (Roundcube)">
                                    <GlobeAltIcon class="h-3.5 w-3.5" />
                                    {{ webmailLoading[e.id] ? '...' : 'Webmail Aç' }}
                                </button>
                                <Link :href="route('customer.email.show', { emailAccount: e.id })"
                                      class="inline-flex items-center gap-1 rounded-lg border border-indigo-300 bg-indigo-50 px-2 py-1 text-xs font-medium text-indigo-700 hover:bg-indigo-100 mr-1">
                                    Detay →
                                </Link>
                                <button @click="removeEmail(e)" class="rounded p-1.5 text-red-500 hover:bg-red-50" title="Sil">
                                    <TrashIcon class="h-4 w-4" />
                                </button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Forwarders tab -->
        <div v-if="activeTab === 'forwarders'">
            <div class="mb-4 flex justify-end">
                <button @click="showFwdForm = true" class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">
                    <PlusIcon class="h-4 w-4" /> Yeni Yönlendirme
                </button>
            </div>

            <EmptyState
                v-if="forwarders.length === 0"
                :icon="ArrowRightIcon"
                title="Henüz yönlendirme yok"
                description="contact@... ⇒ size@example.com şeklinde aktarımlar."
            />
            <div v-else class="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm">
                <table class="min-w-full divide-y divide-slate-200">
                    <thead class="bg-slate-50">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-slate-500">Kaynak</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-slate-500">Hedef(ler)</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-slate-500">Yerel Kopya</th>
                            <th class="px-4 py-3"></th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                        <tr v-for="f in forwarders" :key="f.id">
                            <td class="px-4 py-2 font-mono text-sm">{{ f.source }}</td>
                            <td class="px-4 py-2 font-mono text-xs text-slate-700">{{ f.destinations }}</td>
                            <td class="px-4 py-2 text-xs">{{ f.keep_local_copy ? 'Evet' : 'Hayır' }}</td>
                            <td class="px-4 py-2 text-right">
                                <button @click="removeFwd(f)" class="rounded p-1.5 text-red-500 hover:bg-red-50">
                                    <TrashIcon class="h-4 w-4" />
                                </button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Email modal -->
        <div v-if="showEmailForm" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="text-lg font-semibold">Yeni E-posta Hesabı</h3>
                    <button @click="showEmailForm = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>
                <form @submit.prevent="submitEmail" class="space-y-4">
                    <div class="flex gap-2 items-end">
                        <div class="flex-1">
                            <label class="block text-sm font-medium">Local-part</label>
                            <input v-model="emailForm.local" type="text" placeholder="info" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                        </div>
                        <span class="pb-2 text-slate-400">@</span>
                        <div class="flex-1">
                            <label class="block text-sm font-medium">Domain</label>
                            <select v-model="emailForm.domain" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                                <option v-for="d in available_domains" :key="d" :value="d">{{ d }}</option>
                            </select>
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Parola</label>
                        <div class="mt-1 flex gap-2">
                            <input v-model="emailForm.password" type="text" class="flex-1 rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                            <button type="button" @click="generatePassword" class="rounded-lg border border-slate-300 bg-white px-3 hover:bg-slate-50">
                                <KeyIcon class="h-4 w-4" />
                            </button>
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Kota (MB)</label>
                        <input v-model.number="emailForm.quota_mb" type="number" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                        <p class="mt-1 text-xs text-slate-500">-1 = sınırsız</p>
                    </div>
                    <div class="flex justify-end gap-2">
                        <button type="button" @click="showEmailForm = false" class="rounded-lg border border-slate-300 px-4 py-2 text-sm">İptal</button>
                        <button type="submit" :disabled="emailForm.processing" class="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">Oluştur</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Forwarder modal -->
        <div v-if="showFwdForm" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="text-lg font-semibold">Yeni E-posta Yönlendirmesi</h3>
                    <button @click="showFwdForm = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>
                <form @submit.prevent="submitFwd" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium">Kaynak (alan adınızdan)</label>
                        <input v-model="fwdForm.source" type="email" placeholder="info@domain.com" 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-sm font-medium">Hedef (virgülle ayırın)</label>
                        <textarea v-model="fwdForm.destinations" rows="2" placeholder="ben@gmail.com, ekip@workspace.com" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm"></textarea>
                    </div>
                    <label class="flex items-center gap-2 text-sm">
                        <input v-model="fwdForm.keep_local_copy" type="checkbox" class="rounded" />
                        Yerel kopya da tut (mailbox'a da kaydet)
                    </label>
                    <div class="flex justify-end gap-2">
                        <button type="button" @click="showFwdForm = false" class="rounded-lg border border-slate-300 px-4 py-2 text-sm">İptal</button>
                        <button type="submit" :disabled="fwdForm.processing" class="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">Oluştur</button>
                    </div>
                </form>
            </div>
        </div>
    </CustomerLayout>
</template>
