<script setup>
import { ref, computed } from 'vue'
import { Head, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    DevicePhoneMobileIcon,
    CheckCircleIcon,
    XCircleIcon,
    BellAlertIcon,
    BeakerIcon,
    ExclamationTriangleIcon,
    ArrowPathIcon,
    InformationCircleIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    status: { type: Object, required: true },
    recent_devices: { type: Array, default: () => [] },
})

const testing = ref(false)
const testResult = ref(null)
const testError = ref(null)

const apnsReady = computed(() => props.status?.apns?.sdk_installed && props.status?.apns?.configured)
const fcmReady = computed(() => props.status?.fcm?.sdk_installed && props.status?.fcm?.configured)

function fmtDate(iso) {
    if (!iso) return '—'
    return new Date(iso).toLocaleString('tr-TR', { dateStyle: 'short', timeStyle: 'short' })
}

async function sendTestPush() {
    testing.value = true
    testResult.value = null
    testError.value = null
    try {
        const res = await fetch(route('admin.notifications.mobile.test-push'), {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '',
            },
        })
        const data = await res.json()
        testResult.value = data
    } catch (e) {
        testError.value = e?.message || 'Bilinmeyen hata'
    } finally {
        testing.value = false
    }
}

function refresh() {
    router.reload({ only: ['status', 'recent_devices'] })
}
</script>

<template>
    <Head title="Mobile Push (APNs + FCM)" />
    <AdminLayout>
        <template #header>Mobile Push (APNs + FCM)</template>

        <div class="space-y-6">
            <!-- Bilgi banner -->
            <div class="rounded-xl border border-indigo-200 dark:border-indigo-800 bg-gradient-to-br from-indigo-50 to-purple-50 dark:from-indigo-950/30 dark:to-purple-950/30 p-5">
                <div class="flex items-start gap-3">
                    <DevicePhoneMobileIcon class="h-5 w-5 text-indigo-600 dark:text-indigo-400 mt-0.5 shrink-0" />
                    <div>
                        <h3 class="text-base font-bold text-slate-900 dark:text-slate-100">Native Mobile Push Altyapısı</h3>
                        <p class="text-sm text-slate-600 dark:text-slate-300 mt-1">
                            iOS APNs ve Android FCM üzerinden mobil uygulama bildirimleri.
                            Web Push (browser) ile birlikte <strong>UnifiedNotificationService</strong> üzerinden tek noktadan dağıtılabilir.
                            SDK paketleri opsiyonel — kurulu değilken sistem <em>Log fallback</em>'a düşer.
                        </p>
                    </div>
                </div>
            </div>

            <!-- Stats grid -->
            <div class="grid grid-cols-2 md:grid-cols-5 gap-3">
                <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-4">
                    <p class="text-xs uppercase tracking-wider text-slate-500">Toplam Cihaz</p>
                    <p class="text-2xl font-bold text-slate-900 dark:text-slate-100">{{ status.stats?.total ?? 0 }}</p>
                </div>
                <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-4">
                    <p class="text-xs uppercase tracking-wider text-slate-500">Aktif</p>
                    <p class="text-2xl font-bold text-emerald-600 dark:text-emerald-400">{{ status.stats?.enabled ?? 0 }}</p>
                </div>
                <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-4">
                    <p class="text-xs uppercase tracking-wider text-slate-500">iOS</p>
                    <p class="text-2xl font-bold text-slate-900 dark:text-slate-100">{{ status.stats?.ios ?? 0 }}</p>
                </div>
                <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-4">
                    <p class="text-xs uppercase tracking-wider text-slate-500">Android</p>
                    <p class="text-2xl font-bold text-slate-900 dark:text-slate-100">{{ status.stats?.android ?? 0 }}</p>
                </div>
                <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-4">
                    <p class="text-xs uppercase tracking-wider text-slate-500">Devre Dışı</p>
                    <p class="text-2xl font-bold text-rose-600 dark:text-rose-400">{{ status.stats?.disabled ?? 0 }}</p>
                </div>
            </div>

            <!-- APNs + FCM provider config status -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-5">
                    <div class="flex items-center justify-between mb-3">
                        <h4 class="text-base font-bold text-slate-900 dark:text-slate-100">Apple APNs (iOS)</h4>
                        <span v-if="apnsReady" class="inline-flex items-center gap-1 text-emerald-600 text-xs font-medium">
                            <CheckCircleIcon class="h-4 w-4" /> Hazır
                        </span>
                        <span v-else class="inline-flex items-center gap-1 text-amber-600 text-xs font-medium">
                            <ExclamationTriangleIcon class="h-4 w-4" /> Yapılandırılmamış
                        </span>
                    </div>
                    <dl class="space-y-1 text-sm">
                        <div class="flex justify-between">
                            <dt class="text-slate-500">SDK (edamov/pushok)</dt>
                            <dd>
                                <CheckCircleIcon v-if="status.apns?.sdk_installed" class="h-4 w-4 text-emerald-500" />
                                <XCircleIcon v-else class="h-4 w-4 text-slate-400" />
                            </dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-slate-500">Config (.p8 + KEY_ID + TEAM_ID)</dt>
                            <dd>
                                <CheckCircleIcon v-if="status.apns?.configured" class="h-4 w-4 text-emerald-500" />
                                <XCircleIcon v-else class="h-4 w-4 text-slate-400" />
                            </dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-slate-500">Bundle ID</dt>
                            <dd class="font-mono text-xs text-slate-700 dark:text-slate-300">{{ status.apns?.app_bundle_id || '—' }}</dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-slate-500">Ortam</dt>
                            <dd class="text-xs">
                                <span :class="status.apns?.production_mode ? 'text-rose-600' : 'text-amber-600'">
                                    {{ status.apns?.production_mode ? 'Production' : 'Sandbox' }}
                                </span>
                            </dd>
                        </div>
                    </dl>
                    <p v-if="!status.apns?.sdk_installed" class="mt-3 text-xs text-slate-500 bg-slate-50 dark:bg-slate-900/50 rounded p-2">
                        <InformationCircleIcon class="h-3 w-3 inline" />
                        Kurmak için: <code class="font-mono">composer require edamov/pushok</code>
                    </p>
                </div>

                <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-5">
                    <div class="flex items-center justify-between mb-3">
                        <h4 class="text-base font-bold text-slate-900 dark:text-slate-100">Google FCM (Android)</h4>
                        <span v-if="fcmReady" class="inline-flex items-center gap-1 text-emerald-600 text-xs font-medium">
                            <CheckCircleIcon class="h-4 w-4" /> Hazır
                        </span>
                        <span v-else class="inline-flex items-center gap-1 text-amber-600 text-xs font-medium">
                            <ExclamationTriangleIcon class="h-4 w-4" /> Yapılandırılmamış
                        </span>
                    </div>
                    <dl class="space-y-1 text-sm">
                        <div class="flex justify-between">
                            <dt class="text-slate-500">SDK (kreait/firebase-php)</dt>
                            <dd>
                                <CheckCircleIcon v-if="status.fcm?.sdk_installed" class="h-4 w-4 text-emerald-500" />
                                <XCircleIcon v-else class="h-4 w-4 text-slate-400" />
                            </dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-slate-500">Service Account JSON</dt>
                            <dd>
                                <CheckCircleIcon v-if="status.fcm?.configured" class="h-4 w-4 text-emerald-500" />
                                <XCircleIcon v-else class="h-4 w-4 text-slate-400" />
                            </dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-slate-500">Project ID</dt>
                            <dd class="font-mono text-xs text-slate-700 dark:text-slate-300">{{ status.fcm?.project_id || '—' }}</dd>
                        </div>
                    </dl>
                    <p v-if="!status.fcm?.sdk_installed" class="mt-3 text-xs text-slate-500 bg-slate-50 dark:bg-slate-900/50 rounded p-2">
                        <InformationCircleIcon class="h-3 w-3 inline" />
                        Kurmak için: <code class="font-mono">composer require kreait/firebase-php</code>
                    </p>
                </div>
            </div>

            <!-- Test push -->
            <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-5">
                <div class="flex items-start gap-3 mb-3">
                    <BeakerIcon class="h-5 w-5 text-purple-600 dark:text-purple-400 shrink-0 mt-0.5" />
                    <div class="flex-1">
                        <h4 class="text-base font-bold text-slate-900 dark:text-slate-100">Test Bildirimi</h4>
                        <p class="text-sm text-slate-600 dark:text-slate-300 mt-0.5">
                            Sizin hesabınıza bağlı tüm kayıtlı mobile cihazlara test bildirimi gönderir.
                            SDK kurulu değilken bile çalışır — sonuçta <code class="font-mono text-xs">sent: 0</code> görünür ama Laravel log'una yazılır.
                        </p>
                    </div>
                    <button
                        @click="sendTestPush"
                        :disabled="testing"
                        class="inline-flex items-center gap-2 px-3 py-1.5 rounded-md bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 text-white text-sm font-medium transition"
                    >
                        <BellAlertIcon v-if="!testing" class="h-4 w-4" />
                        <ArrowPathIcon v-else class="h-4 w-4 animate-spin" />
                        Test Gönder
                    </button>
                </div>
                <div v-if="testResult" class="mt-3 rounded-lg bg-slate-50 dark:bg-slate-900/50 p-3 font-mono text-xs">
                    <pre class="whitespace-pre-wrap">{{ JSON.stringify(testResult, null, 2) }}</pre>
                </div>
                <div v-if="testError" class="mt-3 rounded-lg bg-rose-50 dark:bg-rose-900/20 text-rose-700 dark:text-rose-300 p-3 text-sm">
                    {{ testError }}
                </div>
            </div>

            <!-- Recent devices -->
            <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800">
                <div class="flex items-center justify-between p-4 border-b border-slate-200 dark:border-slate-700">
                    <h4 class="text-base font-bold text-slate-900 dark:text-slate-100">Son Kayıtlı Cihazlar</h4>
                    <button @click="refresh" class="text-xs text-slate-500 hover:text-indigo-600 inline-flex items-center gap-1">
                        <ArrowPathIcon class="h-3 w-3" /> Yenile
                    </button>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full text-sm">
                        <thead class="bg-slate-50 dark:bg-slate-900/50 text-xs uppercase text-slate-500">
                            <tr>
                                <th class="px-4 py-2 text-left">Cihaz</th>
                                <th class="px-4 py-2 text-left">Platform</th>
                                <th class="px-4 py-2 text-left">User</th>
                                <th class="px-4 py-2 text-left">Sürüm</th>
                                <th class="px-4 py-2 text-left">Son Push</th>
                                <th class="px-4 py-2 text-left">Durum</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-200 dark:divide-slate-700">
                            <tr v-for="d in recent_devices" :key="d.id">
                                <td class="px-4 py-2 text-slate-900 dark:text-slate-100">{{ d.device_name }}</td>
                                <td class="px-4 py-2">
                                    <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium"
                                        :class="d.platform === 'ios' ? 'bg-slate-100 text-slate-700 dark:bg-slate-700 dark:text-slate-300' : 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400'">
                                        {{ d.platform }}
                                    </span>
                                </td>
                                <td class="px-4 py-2 text-slate-500">#{{ d.user_id }}</td>
                                <td class="px-4 py-2 text-xs text-slate-500">
                                    {{ d.app_version || '—' }} / {{ d.os_version || '—' }}
                                </td>
                                <td class="px-4 py-2 text-xs text-slate-500">{{ fmtDate(d.last_sent_at) }}</td>
                                <td class="px-4 py-2">
                                    <span v-if="d.enabled" class="inline-flex items-center gap-1 text-emerald-600 text-xs">
                                        <CheckCircleIcon class="h-3 w-3" /> Aktif
                                    </span>
                                    <span v-else class="inline-flex items-center gap-1 text-rose-600 text-xs" :title="d.last_error">
                                        <XCircleIcon class="h-3 w-3" /> Pasif
                                    </span>
                                </td>
                            </tr>
                            <tr v-if="recent_devices.length === 0">
                                <td colspan="6" class="px-4 py-8 text-center text-slate-400 text-sm">
                                    Henüz kayıtlı cihaz yok. Mobile app entegre edildiğinde buraya düşecek.
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
