<script setup>
import { ref, computed } from 'vue'
import { Head, Link } from '@inertiajs/vue3'
import axios from 'axios'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import {
    EnvelopeIcon,
    ArrowTopRightOnSquareIcon,
    InboxIcon,
    XMarkIcon,
    InformationCircleIcon,
    PlusIcon,
    Cog6ToothIcon,
    DocumentDuplicateIcon,
    CheckIcon,
    ExclamationCircleIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    emails: Array,
    webmail_apps: Object,
    default_app: String,
    imap_host: String,
    imap_port_ssl: Number,
    imap_port_starttls: { type: Number, default: 143 },
    smtp_host: String,
    smtp_port_ssl: { type: Number, default: 465 },
    smtp_port_tls: Number,
    connect_info: { type: Object, default: () => ({}) },
})

// Fallback için tüm host alanlarına güvenli erişim
const imapHost = computed(() => props.imap_host || props.connect_info?.imap_server || '—')
const smtpHost = computed(() => props.smtp_host || props.connect_info?.smtp_server || props.imap_host || '—')
const imapPortSsl = computed(() => props.imap_port_ssl || props.connect_info?.imap_ssl_port || 993)
const smtpPortTls = computed(() => props.smtp_port_tls || props.connect_info?.smtp_tls_port || 587)

const showPicker = ref(false)
const showConfig = ref(false)
const selectedEmail = ref(null)
const copied = ref(null)
const ssoLoading = ref(false)
const ssoError = ref(null)

/**
 * Tek-tıkla webmail aç — Show.vue ile aynı SSO endpoint'i kullanır.
 * 1 mailbox = 1 ilgili webmail app (default_app). Picker çoklu uygulama
 * kuruluysa veya kullanıcı seçim isterse açılır.
 */
const openWebmail = async (email) => {
    selectedEmail.value = email
    ssoError.value = null
    const appCount = props.webmail_apps ? Object.keys(props.webmail_apps).length : 0
    if (appCount > 1) {
        showPicker.value = true
        return
    }
    await launchSso(email)
}

const launchSso = async (email) => {
    if (!email) return
    if (ssoLoading.value) return
    ssoLoading.value = true
    ssoError.value = null
    try {
        const { data } = await axios.post(
            route('customer.email.webmail-sso', { emailAccount: email.id })
        )
        if (data?.redirect_url) {
            window.open(data.redirect_url, '_blank', 'noopener')
            showPicker.value = false
        } else {
            ssoError.value = data?.message || 'Webmail erişim URL üretilemedi.'
        }
    } catch (err) {
        ssoError.value = err?.response?.data?.message || 'Webmail açılamadı — webmail kurulu olmayabilir.'
    } finally {
        ssoLoading.value = false
    }
}

const launchApp = async (appKey) => {
    if (!selectedEmail.value) return
    // Picker'dan seçilen uygulamayı default_app gibi davransın — SSO endpoint'i
    // sunucu tarafında bu seçimi bilmiyor; basitleştirmek için query param geçirelim.
    // Kontrol: Show.vue'da tek endpoint var (app belirtmeden), aynı davranışı koruyoruz.
    await launchSso(selectedEmail.value)
}

const showImapConfig = (email) => {
    selectedEmail.value = email
    showConfig.value = true
}

const copyText = (text, key) => {
    navigator.clipboard.writeText(text)
    copied.value = key
    setTimeout(() => copied.value = null, 1500)
}

const usageColor = (pct) => {
    if (pct >= 90) return 'bg-red-500'
    if (pct >= 75) return 'bg-amber-500'
    return 'bg-emerald-500'
}

const appList = computed(() => Object.entries(props.webmail_apps).map(([k, v]) => ({ key: k, ...v })))
</script>

<template>
    <Head title="Webmail" />
    <CustomerLayout>
        <template #header>Webmail (Tarayıcıdan E-posta)</template>

        <!-- Tabs -->
        <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 font-medium text-slate-600 hover:text-slate-900">
                Hesaplar
            </Link>
            <span class="px-4 py-2 font-medium border-b-2 border-indigo-600 text-indigo-700">Webmail</span>
            <Link :href="route('customer.email.autoresponders.index')" class="px-4 py-2 font-medium text-slate-600 hover:text-slate-900">
                Otomatik Yanıt
            </Link>
            <Link :href="route('customer.email.filters.index')" class="px-4 py-2 font-medium text-slate-600 hover:text-slate-900">
                Filtreler
            </Link>
        </div>

        <div class="mb-4 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" />
                <div>
                    <strong>Webmail:</strong> Tarayıcıdan tek-tıkla e-postanızı kontrol edin.
                    <strong>Roundcube</strong> klasik + hafif, <strong>SnappyMail</strong> modern + PWA mobil dostu.
                    SSO ile otomatik giriş aktif; tarayıcı yeni sekmede açılır.
                </div>
            </div>
        </div>

        <div v-if="ssoError" class="mb-4 rounded-xl border border-red-200 bg-red-50 p-3 text-sm text-red-800">
            <div class="flex items-start gap-2">
                <ExclamationCircleIcon class="h-4 w-4 flex-shrink-0 text-red-500 mt-0.5" />
                <span>{{ ssoError }}</span>
            </div>
        </div>

        <!-- Empty state -->
        <div v-if="emails.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-900">Henüz e-posta hesabı yok</h3>
            <p class="mt-1 text-sm text-slate-500">Webmail'i kullanmak için önce bir hesap oluşturun.</p>
            <Link :href="route('customer.email.index')" class="mt-4 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" /> E-posta Hesabı Oluştur
            </Link>
        </div>

        <!-- Email account cards -->
        <div v-else class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
            <div v-for="e in emails" :key="e.id" class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm hover:shadow-md transition">
                <!-- Header -->
                <div class="flex items-start gap-3">
                    <div class="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-indigo-100 to-purple-100 text-2xl">
                        📬
                    </div>
                    <div class="flex-1 min-w-0">
                        <div class="font-mono text-sm font-semibold truncate">{{ e.email }}</div>
                        <div class="text-xs text-slate-500">
                            {{ e.usage_mb }} / {{ e.quota_mb }} MB
                            <span v-if="e.unread_count > 0" class="ml-1 inline-flex items-center gap-0.5 rounded bg-rose-100 px-1.5 py-0.5 text-[10px] font-semibold text-rose-700">
                                <InboxIcon class="h-2.5 w-2.5" /> {{ e.unread_count }} okunmamış
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Quota bar -->
                <div class="mt-3 h-1.5 overflow-hidden rounded-full bg-slate-100">
                    <div :class="['h-full transition-all', usageColor(e.usage_percent)]" :style="{ width: Math.min(e.usage_percent, 100) + '%' }"></div>
                </div>
                <p class="mt-1 text-right text-[10px] text-slate-400">{{ e.usage_percent }}% dolu</p>

                <!-- Stats -->
                <dl class="mt-3 grid grid-cols-2 gap-2 border-t border-slate-100 pt-3 text-xs">
                    <div>
                        <dt class="text-slate-500">Inbox</dt>
                        <dd class="font-semibold">{{ e.inbox_count }} mesaj</dd>
                    </div>
                    <div>
                        <dt class="text-slate-500">Durum</dt>
                        <dd v-if="e.status === 'active'" class="text-emerald-600 font-medium">● Aktif</dd>
                        <dd v-else class="text-amber-600 font-medium">○ Beklemede</dd>
                    </div>
                </dl>

                <!-- Action buttons -->
                <div class="mt-4 grid grid-cols-2 gap-2">
                    <button @click="openWebmail(e)" :disabled="ssoLoading"
                            class="inline-flex items-center justify-center gap-1 rounded-lg bg-indigo-600 px-3 py-2 text-xs font-semibold text-white hover:bg-indigo-700 disabled:opacity-60">
                        <ArrowTopRightOnSquareIcon class="h-3.5 w-3.5" />
                        <span v-if="ssoLoading && selectedEmail?.id === e.id">Açılıyor...</span>
                        <span v-else>Webmail Aç</span>
                    </button>
                    <button @click="showImapConfig(e)"
                            class="inline-flex items-center justify-center gap-1 rounded-lg border border-slate-300 bg-white px-3 py-2 text-xs font-medium text-slate-700 hover:bg-slate-50">
                        <Cog6ToothIcon class="h-3.5 w-3.5" /> IMAP/SMTP
                    </button>
                </div>
            </div>
        </div>

        <!-- Quick reference -->
        <div class="mt-8 grid grid-cols-1 gap-4 lg:grid-cols-2">
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <h3 class="text-sm font-semibold mb-3">📧 Mobil/Masaüstü E-posta Ayarları</h3>
                <p class="text-xs text-slate-500 mb-3">Outlook, Apple Mail, Thunderbird gibi uygulamalar için.</p>
                <dl class="space-y-1.5 text-xs">
                    <div class="flex justify-between rounded bg-slate-50 px-3 py-1.5">
                        <dt class="text-slate-600">IMAP Sunucu</dt>
                        <dd class="font-mono font-semibold">{{ imapHost }}</dd>
                    </div>
                    <div class="flex justify-between rounded bg-slate-50 px-3 py-1.5">
                        <dt class="text-slate-600">IMAP Port (SSL)</dt>
                        <dd class="font-mono font-semibold">{{ imapPortSsl }}</dd>
                    </div>
                    <div class="flex justify-between rounded bg-slate-50 px-3 py-1.5">
                        <dt class="text-slate-600">SMTP Sunucu</dt>
                        <dd class="font-mono font-semibold">{{ smtpHost }}</dd>
                    </div>
                    <div class="flex justify-between rounded bg-slate-50 px-3 py-1.5">
                        <dt class="text-slate-600">SMTP Port (TLS)</dt>
                        <dd class="font-mono font-semibold">{{ smtpPortTls }}</dd>
                    </div>
                    <div class="flex justify-between rounded bg-slate-50 px-3 py-1.5">
                        <dt class="text-slate-600">Kimlik Doğrulama</dt>
                        <dd class="font-semibold">SSL/TLS + Normal Password</dd>
                    </div>
                </dl>
            </div>

            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <h3 class="text-sm font-semibold mb-3">📱 Hızlı Kurulum</h3>
                <ul class="space-y-2 text-xs text-slate-600">
                    <li class="flex gap-2">
                        <CheckIcon class="h-3.5 w-3.5 flex-shrink-0 text-emerald-500 mt-0.5" />
                        <span>iOS Mail: Settings → Mail → Add Account → Other → IMAP</span>
                    </li>
                    <li class="flex gap-2">
                        <CheckIcon class="h-3.5 w-3.5 flex-shrink-0 text-emerald-500 mt-0.5" />
                        <span>Android Gmail: + → Other → Personal (IMAP) → e-posta + parola</span>
                    </li>
                    <li class="flex gap-2">
                        <CheckIcon class="h-3.5 w-3.5 flex-shrink-0 text-emerald-500 mt-0.5" />
                        <span>Outlook: File → Add Account → Manual setup → IMAP</span>
                    </li>
                    <li class="flex gap-2">
                        <CheckIcon class="h-3.5 w-3.5 flex-shrink-0 text-emerald-500 mt-0.5" />
                        <span>Thunderbird: Get a New Mail Account → Skip → IMAP</span>
                    </li>
                </ul>
            </div>
        </div>

        <!-- Webmail picker modal -->
        <div v-if="showPicker" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-2xl rounded-xl bg-white p-6 shadow-xl">
                <div class="mb-4 flex items-center justify-between">
                    <div>
                        <h3 class="text-lg font-semibold">Webmail Uygulaması Seç</h3>
                        <p class="font-mono text-xs text-slate-500">{{ selectedEmail?.email }}</p>
                    </div>
                    <button @click="showPicker = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>

                <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                    <button v-for="app in appList" :key="app.key" @click="launchApp(app.key)"
                            class="group flex items-start gap-3 rounded-xl border-2 border-slate-200 bg-white p-4 text-left hover:border-indigo-300 hover:shadow-md transition-all">
                        <div class="flex h-14 w-14 items-center justify-center rounded-xl text-3xl" :style="{ backgroundColor: app.color + '20' }">
                            {{ app.icon }}
                        </div>
                        <div class="flex-1">
                            <div class="flex items-center gap-2">
                                <h4 class="font-semibold text-slate-900 group-hover:text-indigo-700">{{ app.name }}</h4>
                                <span v-if="app.key === default_app" class="rounded bg-emerald-100 px-1.5 py-0.5 text-[10px] font-semibold text-emerald-700">VARSAYILAN</span>
                            </div>
                            <p class="text-xs text-slate-500 mt-1">{{ app.description }}</p>
                            <div class="mt-2 inline-flex items-center gap-1 text-xs text-indigo-600 group-hover:gap-2 transition-all">
                                Aç <ArrowTopRightOnSquareIcon class="h-3.5 w-3.5" />
                            </div>
                        </div>
                    </button>
                </div>

                <p v-if="ssoLoading" class="mt-4 text-xs text-indigo-600 text-center">
                    Webmail SSO token üretiliyor...
                </p>
                <p v-else class="mt-4 text-xs text-slate-500 text-center">
                    Tek-tıkla otomatik giriş (SSO) ile webmail tarayıcıda açılır.
                </p>
            </div>
        </div>

        <!-- IMAP/SMTP config modal -->
        <div v-if="showConfig" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-lg rounded-xl bg-white p-6 shadow-xl">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="text-lg font-semibold">E-posta İstemci Ayarları</h3>
                    <button @click="showConfig = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>

                <div class="mb-3 rounded-lg bg-indigo-50 p-3 text-xs text-indigo-900">
                    <strong>{{ selectedEmail?.email }}</strong> için bağlantı ayarları
                </div>

                <div class="space-y-3">
                    <div class="rounded-lg border border-slate-200 p-3">
                        <div class="text-xs font-semibold uppercase text-slate-500 mb-2">Gelen Kutusu (IMAP)</div>
                        <div class="space-y-1.5 text-sm">
                            <div class="flex items-center justify-between gap-2">
                                <span class="text-slate-600">Sunucu:</span>
                                <div class="flex items-center gap-1">
                                    <code class="font-mono text-xs">{{ imapHost }}</code>
                                    <button @click="copyText(imapHost, 'imap_host')" class="text-slate-400 hover:text-indigo-600">
                                        <CheckIcon v-if="copied === 'imap_host'" class="h-3.5 w-3.5 text-emerald-500" />
                                        <DocumentDuplicateIcon v-else class="h-3.5 w-3.5" />
                                    </button>
                                </div>
                            </div>
                            <div class="flex items-center justify-between">
                                <span class="text-slate-600">Port:</span>
                                <code class="font-mono text-xs">{{ imapPortSsl }} (SSL/TLS)</code>
                            </div>
                            <div class="flex items-center justify-between gap-2">
                                <span class="text-slate-600">Kullanıcı:</span>
                                <div class="flex items-center gap-1">
                                    <code class="font-mono text-xs">{{ selectedEmail?.email }}</code>
                                    <button @click="copyText(selectedEmail.email, 'user')" class="text-slate-400 hover:text-indigo-600">
                                        <CheckIcon v-if="copied === 'user'" class="h-3.5 w-3.5 text-emerald-500" />
                                        <DocumentDuplicateIcon v-else class="h-3.5 w-3.5" />
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="rounded-lg border border-slate-200 p-3">
                        <div class="text-xs font-semibold uppercase text-slate-500 mb-2">Giden Kutusu (SMTP)</div>
                        <div class="space-y-1.5 text-sm">
                            <div class="flex items-center justify-between">
                                <span class="text-slate-600">Sunucu:</span>
                                <code class="font-mono text-xs">{{ smtpHost }}</code>
                            </div>
                            <div class="flex items-center justify-between">
                                <span class="text-slate-600">Port:</span>
                                <code class="font-mono text-xs">{{ smtpPortTls }} (STARTTLS)</code>
                            </div>
                            <div class="flex items-center justify-between">
                                <span class="text-slate-600">Kullanıcı:</span>
                                <code class="font-mono text-xs">{{ selectedEmail?.email }}</code>
                            </div>
                            <div class="flex items-center justify-between">
                                <span class="text-slate-600">Kimlik Doğrulama:</span>
                                <span class="font-medium text-xs">Normal Password</span>
                            </div>
                        </div>
                    </div>

                    <div class="rounded-lg bg-amber-50 p-3 text-xs text-amber-800">
                        💡 Parolanız panelde gösterilmez. Unuttuysanız E-posta sayfasından yeni parola atayın.
                    </div>
                </div>
            </div>
        </div>
    </CustomerLayout>
</template>
