<script setup>
import { ref, computed } from 'vue'
import { Head, Link, useForm, router } from '@inertiajs/vue3'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import {
    EnvelopeIcon,
    FunnelIcon,
    ArrowDownTrayIcon,
    MagnifyingGlassIcon,
    CheckCircleIcon,
    ClockIcon,
    XCircleIcon,
    ExclamationTriangleIcon,
    ChartBarIcon,
    EyeIcon,
    ArrowRightCircleIcon,
    PaperAirplaneIcon,
    InformationCircleIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    items:             { type: Array,  default: () => [] },
    pagination:        { type: Object, default: () => ({}) },
    stats:             { type: Object, default: () => ({}) },
    filters:           { type: Object, default: () => ({}) },
    available_domains: { type: Array,  default: () => [] },
    log_status:        { type: Object, default: () => ({ available: false, path: null, message: null }) },
    // detail mode props
    detail_mail_id:    { type: Number, default: null },
    detail_mail_trace: { type: Array,  default: null },
})

// ── filter form ──────────────────────────────────────────────────────────────
const filterForm = useForm({
    status:    props.filters.status    ?? 'all',
    sender:    props.filters.sender    ?? '',
    recipient: props.filters.recipient ?? '',
    domain:    props.filters.domain    ?? '',
    from:      props.filters.from      ?? '',
    to:        props.filters.to        ?? '',
})

const applyFilters = () => {
    router.get(route('customer.email.tracking.index'), filterForm.data(), {
        preserveScroll: true,
        preserveState: true,
    })
}

const resetFilters = () => {
    filterForm.reset()
    router.get(route('customer.email.tracking.index'), {}, { preserveScroll: true })
}

const exportCsv = () => {
    const params = new URLSearchParams(filterForm.data()).toString()
    window.location.href = route('customer.email.tracking.export') + '?' + params
}

// ── detail modal ─────────────────────────────────────────────────────────────
const detailEntry = ref(null)

const openDetail = (entry) => {
    if (props.detail_mail_trace) return // already in detail mode
    detailEntry.value = entry
}

const closeDetail = () => {
    detailEntry.value = null
}

// ── helpers ──────────────────────────────────────────────────────────────────
const formatTs = (iso) => {
    if (!iso) return '—'
    const d = new Date(iso)
    return d.toLocaleString('tr-TR', { dateStyle: 'short', timeStyle: 'short' })
}

const formatBytes = (bytes) => {
    if (bytes < 1024) return bytes + ' B'
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
    return (bytes / 1024 / 1024).toFixed(2) + ' MB'
}

const statusBadgeClass = (status) => ({
    delivered: 'bg-emerald-100 text-emerald-700',
    sent:      'bg-blue-100 text-blue-700',
    deferred:  'bg-amber-100 text-amber-700',
    bounced:   'bg-red-100 text-red-700',
    rejected:  'bg-rose-100 text-rose-800',
}[status] ?? 'bg-slate-100 text-slate-600')

const statusIcon = (status) => ({
    delivered: CheckCircleIcon,
    sent:      PaperAirplaneIcon,
    deferred:  ClockIcon,
    bounced:   ExclamationTriangleIcon,
    rejected:  XCircleIcon,
}[status] ?? InformationCircleIcon)

const statusLabel = (status) => ({
    delivered: 'Teslim Edildi',
    sent:      'Gönderildi',
    deferred:  'Ertelendi',
    bounced:   'Geri Döndü',
    rejected:  'Reddedildi',
}[status] ?? status)

const traceIcon = (event) => ({
    queued:    ClockIcon,
    relayed:   ArrowRightCircleIcon,
    delivered: CheckCircleIcon,
    bounced:   ExclamationTriangleIcon,
    deferred:  ClockIcon,
}[event] ?? InformationCircleIcon)

const traceIconClass = (event) => ({
    queued:    'text-slate-400',
    relayed:   'text-blue-500',
    delivered: 'text-emerald-500',
    bounced:   'text-red-500',
    deferred:  'text-amber-500',
}[event] ?? 'text-slate-400')

const statCards = computed(() => [
    { label: 'Teslim Edildi', key: 'delivered', color: 'emerald', icon: CheckCircleIcon },
    { label: 'Gönderildi',    key: 'sent',       color: 'blue',    icon: PaperAirplaneIcon },
    { label: 'Ertelendi',     key: 'deferred',   color: 'amber',   icon: ClockIcon },
    { label: 'Geri Döndü',    key: 'bounced',    color: 'red',     icon: ExclamationTriangleIcon },
    { label: 'Reddedildi',    key: 'rejected',   color: 'rose',    icon: XCircleIcon },
])

const statColorClass = (color) => ({
    emerald: 'bg-emerald-50 text-emerald-700 border-emerald-200',
    blue:    'bg-blue-50 text-blue-700 border-blue-200',
    amber:   'bg-amber-50 text-amber-700 border-amber-200',
    red:     'bg-red-50 text-red-700 border-red-200',
    rose:    'bg-rose-50 text-rose-700 border-rose-200',
}[color] ?? 'bg-slate-50 text-slate-700 border-slate-200')

const changePage = (p) => {
    router.get(route('customer.email.tracking.index'), { ...filterForm.data(), page: p }, { preserveScroll: true })
}

// Server'dan gerçek trace gelmediyse null döner — UI empty state gösterir.
// Eski versiyon sahte 3 satırlık timeline üretiyordu, kullanıcıyı yanıltıyordu.
const activeTrace = computed(() => {
    if (props.detail_mail_trace && props.detail_mail_trace.length > 0) {
        return props.detail_mail_trace
    }
    return null
})

const traceUnavailable = computed(() => {
    // Detay modal açık ama trace yok → "henüz hazır değil" göster
    return detailEntry.value !== null && (! props.detail_mail_trace || props.detail_mail_trace.length === 0)
})

const activeDetailId = computed(() => props.detail_mail_id ?? detailEntry.value?.id)
const showDetailModal = computed(() => detailEntry.value !== null || props.detail_mail_trace !== null)
</script>

<template>
    <Head title="Track Delivery" />
    <CustomerLayout>
        <template #header>
            <span class="flex items-center gap-2">
                <EnvelopeIcon class="h-5 w-5 text-indigo-500" />
                Track Delivery — Mail Takibi
            </span>
        </template>

        <!-- Tab nav -->
        <div class="mb-4 flex flex-wrap gap-1 border-b border-slate-200 text-sm overflow-x-auto">
            <Link :href="route('customer.email.index')"                    class="px-4 py-2 text-slate-600 hover:text-slate-900 whitespace-nowrap">Hesaplar</Link>
            <Link :href="route('customer.email.autoresponders.index')"     class="px-4 py-2 text-slate-600 hover:text-slate-900 whitespace-nowrap">Otomatik Yanıt</Link>
            <Link :href="route('customer.email.filters.index')"            class="px-4 py-2 text-slate-600 hover:text-slate-900 whitespace-nowrap">Filtreler</Link>
            <Link :href="route('customer.email.mailing-lists.index')"      class="px-4 py-2 text-slate-600 hover:text-slate-900 whitespace-nowrap">Mailing Lists</Link>
            <Link :href="route('customer.email.spam.index')"               class="px-4 py-2 text-slate-600 hover:text-slate-900 whitespace-nowrap">Spam Filtresi</Link>
            <Link :href="route('customer.email.webmail.index')"            class="px-4 py-2 text-slate-600 hover:text-slate-900 whitespace-nowrap">Webmail</Link>
            <Link :href="route('customer.email.deliverability.index')"     class="px-4 py-2 text-slate-600 hover:text-slate-900 whitespace-nowrap">Deliverability</Link>
            <Link :href="route('customer.email.routing.index')"            class="px-4 py-2 text-slate-600 hover:text-slate-900 whitespace-nowrap">Routing</Link>
            <Link :href="route('customer.email.importer.index')"           class="px-4 py-2 text-slate-600 hover:text-slate-900 whitespace-nowrap">Importer</Link>
            <span class="px-4 py-2 font-medium border-b-2 border-indigo-600 text-indigo-700 whitespace-nowrap">Track Delivery</span>
            <Link :href="route('customer.email.boxtrapper.index')"         class="px-4 py-2 text-slate-600 hover:text-slate-900 whitespace-nowrap flex items-center gap-1">
                BoxTrapper
                <span class="rounded-full bg-amber-100 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-amber-700">P2</span>
            </Link>
        </div>

        <div v-if="log_status && !log_status.available" class="mb-4 rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
            <div class="flex gap-3">
                <InformationCircleIcon class="h-5 w-5 flex-shrink-0 text-amber-600" />
                <div>
                    <div class="font-semibold mb-1">Mail log bu sunucuda yok</div>
                    <div>{{ log_status.message }}</div>
                </div>
            </div>
        </div>

        <!-- Stats -->
        <div class="mb-5 grid grid-cols-2 gap-3 sm:grid-cols-5">
            <div
                v-for="card in statCards"
                :key="card.key"
                :class="['flex flex-col items-center justify-center rounded-xl border p-3 text-center shadow-sm', statColorClass(card.color)]"
            >
                <component :is="card.icon" class="mb-1 h-5 w-5" />
                <div class="text-2xl font-bold">{{ stats[card.key] ?? 0 }}</div>
                <div class="mt-0.5 text-xs font-medium">{{ card.label }}</div>
            </div>
        </div>

        <!-- Filter bar -->
        <div class="mb-4 rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
            <div class="flex items-center gap-2 mb-3">
                <FunnelIcon class="h-4 w-4 text-slate-400" />
                <span class="text-sm font-semibold text-slate-700">Filtrele</span>
            </div>
            <div class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
                <!-- Status -->
                <div>
                    <label class="block text-xs font-medium text-slate-600 mb-1">Durum</label>
                    <select v-model="filterForm.status" 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">
                        <option value="all">Tümü</option>
                        <option value="delivered">Teslim Edildi</option>
                        <option value="sent">Gönderildi</option>
                        <option value="deferred">Ertelendi</option>
                        <option value="bounced">Geri Döndü</option>
                        <option value="rejected">Reddedildi</option>
                    </select>
                </div>

                <!-- Domain filter -->
                <div>
                    <label class="block text-xs font-medium text-slate-600 mb-1">Domain</label>
                    <select v-model="filterForm.domain" 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">
                        <option value="">Tüm Domainler</option>
                        <option v-for="d in available_domains" :key="d" :value="d">{{ d }}</option>
                    </select>
                </div>

                <!-- From date -->
                <div>
                    <label class="block text-xs font-medium text-slate-600 mb-1">Başlangıç Tarihi</label>
                    <input v-model="filterForm.from" type="date" 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" />
                </div>

                <!-- To date -->
                <div>
                    <label class="block text-xs font-medium text-slate-600 mb-1">Bitiş Tarihi</label>
                    <input v-model="filterForm.to" type="date" 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" />
                </div>

                <!-- Sender -->
                <div>
                    <label class="block text-xs font-medium text-slate-600 mb-1">Gönderici</label>
                    <div class="relative">
                        <MagnifyingGlassIcon class="absolute left-2.5 top-2.5 h-4 w-4 text-slate-400" />
                        <input v-model="filterForm.sender" type="text" placeholder="info@domain.com" class="w-full rounded-lg border border-slate-300 pl-8 pr-3 py-2 text-sm focus:border-indigo-400 focus:ring-1 focus:ring-indigo-300" />
                    </div>
                </div>

                <!-- Recipient -->
                <div>
                    <label class="block text-xs font-medium text-slate-600 mb-1">Alıcı</label>
                    <div class="relative">
                        <MagnifyingGlassIcon class="absolute left-2.5 top-2.5 h-4 w-4 text-slate-400" />
                        <input v-model="filterForm.recipient" type="text" placeholder="user@gmail.com" class="w-full rounded-lg border border-slate-300 pl-8 pr-3 py-2 text-sm focus:border-indigo-400 focus:ring-1 focus:ring-indigo-300" />
                    </div>
                </div>

                <!-- Actions -->
                <div class="flex items-end gap-2 sm:col-span-2">
                    <button @click="applyFilters" class="flex-1 inline-flex items-center justify-center gap-1.5 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">
                        <FunnelIcon class="h-4 w-4" />
                        Uygula
                    </button>
                    <button @click="resetFilters" class="flex-1 rounded-lg border border-slate-300 px-4 py-2 text-sm text-slate-600 hover:bg-slate-50">
                        Sıfırla
                    </button>
                    <button @click="exportCsv" class="inline-flex items-center gap-1.5 rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm text-slate-700 hover:bg-slate-50">
                        <ArrowDownTrayIcon class="h-4 w-4" />
                        CSV
                    </button>
                </div>
            </div>
        </div>

        <!-- Empty state -->
        <div v-if="available_domains.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 domain yok</h3>
            <p class="mt-1 text-sm text-slate-400">Mail takibi için en az bir domain gerekmektedir.</p>
        </div>

        <!-- Table -->
        <div v-else class="rounded-xl border border-slate-200 bg-white shadow-sm overflow-hidden">
            <div v-if="items.length === 0" class="p-12 text-center text-slate-400 text-sm">
                Filtre kriterlerine uygun kayıt bulunamadı.
            </div>

            <div v-else class="overflow-x-auto">
                <table class="min-w-full divide-y divide-slate-200 text-sm">
                    <thead class="bg-slate-50 text-xs text-slate-500 uppercase tracking-wider">
                        <tr>
                            <th class="px-4 py-3 text-left">Tarih/Saat</th>
                            <th class="px-4 py-3 text-left">Gönderici</th>
                            <th class="px-2 py-3"></th>
                            <th class="px-4 py-3 text-left">Alıcı</th>
                            <th class="px-4 py-3 text-left">Konu</th>
                            <th class="px-4 py-3 text-left">Boyut</th>
                            <th class="px-4 py-3 text-left">Durum</th>
                            <th class="px-4 py-3 text-left">İşlem</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                        <tr
                            v-for="entry in items"
                            :key="entry.id"
                            class="hover:bg-slate-50 transition-colors"
                        >
                            <td class="px-4 py-3 text-xs text-slate-500 whitespace-nowrap">
                                {{ formatTs(entry.timestamp) }}
                            </td>
                            <td class="px-4 py-3 font-mono text-xs text-slate-700 whitespace-nowrap">
                                {{ entry.sender }}
                            </td>
                            <td class="px-2 py-3 text-slate-300">
                                <ArrowRightCircleIcon class="h-4 w-4" />
                            </td>
                            <td class="px-4 py-3 font-mono text-xs text-slate-700 whitespace-nowrap">
                                {{ entry.recipient }}
                            </td>
                            <td class="px-4 py-3 text-xs text-slate-600 max-w-[180px] truncate" :title="entry.subject">
                                {{ entry.subject }}
                            </td>
                            <td class="px-4 py-3 text-xs text-slate-500 whitespace-nowrap">
                                {{ formatBytes(entry.size_bytes) }}
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <span :class="['inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-xs font-medium', statusBadgeClass(entry.status)]">
                                    <component :is="statusIcon(entry.status)" class="h-3.5 w-3.5" />
                                    {{ statusLabel(entry.status) }}
                                </span>
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <button
                                    @click="openDetail(entry)"
                                    class="inline-flex items-center gap-1 rounded-lg border border-slate-200 bg-white px-2.5 py-1 text-xs text-slate-600 hover:bg-slate-50"
                                >
                                    <EyeIcon class="h-3.5 w-3.5" />
                                    Detay
                                </button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <div v-if="pagination.last_page > 1" class="flex items-center justify-between border-t border-slate-200 px-4 py-3">
                <span class="text-xs text-slate-500">
                    Toplam {{ pagination.total }} kayıt — Sayfa {{ pagination.current_page }} / {{ pagination.last_page }}
                </span>
                <div class="flex gap-1">
                    <button
                        :disabled="pagination.current_page <= 1"
                        @click="changePage(pagination.current_page - 1)"
                        class="rounded-lg border border-slate-300 px-3 py-1.5 text-xs disabled:opacity-40 hover:bg-slate-50"
                    >
                        &lsaquo; Önceki
                    </button>
                    <button
                        :disabled="pagination.current_page >= pagination.last_page"
                        @click="changePage(pagination.current_page + 1)"
                        class="rounded-lg border border-slate-300 px-3 py-1.5 text-xs disabled:opacity-40 hover:bg-slate-50"
                    >
                        Sonraki &rsaquo;
                    </button>
                </div>
            </div>
        </div>

        <!-- Detail Modal -->
        <Teleport to="body">
            <div v-if="showDetailModal" class="fixed inset-0 z-50 flex items-center justify-center p-4">
                <div class="absolute inset-0 bg-black/40" @click="closeDetail" />
                <div class="relative z-10 w-full max-w-lg rounded-2xl border border-slate-200 bg-white shadow-2xl">
                    <div class="flex items-center justify-between border-b border-slate-200 p-4">
                        <h3 class="flex items-center gap-2 font-semibold text-slate-800">
                            <ChartBarIcon class="h-5 w-5 text-indigo-500" />
                            Mail #{{ activeDetailId }} — Teslim Takibi
                        </h3>
                        <button @click="closeDetail" class="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100">
                            <XCircleIcon class="h-5 w-5" />
                        </button>
                    </div>

                    <div v-if="detailEntry" class="border-b border-slate-100 px-4 py-3 text-xs text-slate-600 space-y-1">
                        <div><span class="font-medium">Gönderici:</span> <code class="font-mono">{{ detailEntry.sender }}</code></div>
                        <div><span class="font-medium">Alıcı:</span> <code class="font-mono">{{ detailEntry.recipient }}</code></div>
                        <div><span class="font-medium">Konu:</span> {{ detailEntry.subject }}</div>
                        <div><span class="font-medium">Boyut:</span> {{ formatBytes(detailEntry.size_bytes) }}</div>
                    </div>

                    <div class="p-4">
                        <h4 class="mb-3 text-xs font-semibold uppercase tracking-wider text-slate-500">Teslimat Zaman Çizelgesi</h4>
                        <ol v-if="activeTrace" class="relative border-l border-slate-200 ml-3 space-y-5">
                            <li v-for="(step, idx) in activeTrace" :key="idx" class="ml-5">
                                <div class="absolute -left-2 flex h-4 w-4 items-center justify-center rounded-full bg-white ring-2 ring-slate-200">
                                    <component :is="traceIcon(step.event)" :class="['h-3 w-3', traceIconClass(step.event)]" />
                                </div>
                                <p class="text-sm font-medium text-slate-700">{{ step.message }}</p>
                                <p class="text-xs text-slate-400">{{ formatTs(step.time) }} — {{ step.host }}</p>
                            </li>
                        </ol>
                        <div v-else class="rounded-lg border border-amber-200 bg-amber-50 p-4 text-center">
                            <p class="text-sm font-medium text-amber-900">Detaylı teslimat zaman çizelgesi mevcut değil</p>
                            <p class="mt-1 text-xs text-amber-700">
                                Postfix audit log'undan event-by-event trace henüz çekilmemiş.
                                Mail listesindeki <strong>{{ detailEntry?.status }}</strong> durumu hâlâ geçerli;
                                detaylı queued → relayed → delivered adımları için mail logs sayfasına bakın.
                            </p>
                        </div>
                    </div>

                    <div class="border-t border-slate-200 px-4 py-3 flex justify-end">
                        <button @click="closeDetail" class="rounded-lg bg-slate-100 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-200">
                            Kapat
                        </button>
                    </div>
                </div>
            </div>
        </Teleport>
    </CustomerLayout>
</template>
