<script setup>
import { ref, computed } from 'vue'
import { Head, useForm, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    MegaphoneIcon,
    PlusIcon,
    TrashIcon,
    PencilIcon,
    EyeIcon,
    ClockIcon,
    CheckCircleIcon,
    XMarkIcon,
    InformationCircleIcon,
    ExclamationTriangleIcon,
    ShieldExclamationIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    announcements: Object,   // paginated
    stats: Object,
})

// ─── Modals ───────────────────────────────────────────────────────────────────
const showCreateModal = ref(false)
const showEditModal   = ref(false)
const editTarget      = ref(null)

// ─── Forms ────────────────────────────────────────────────────────────────────
const blankForm = () => ({
    title:       '',
    body:        '',
    severity:    'info',
    audience:    'all_customers',
    is_active:   true,
    starts_at:   '',
    ends_at:     '',
    dismissible: true,
})

const createForm = useForm(blankForm())
const editForm   = useForm(blankForm())

const openCreate = () => {
    createForm.reset()
    Object.assign(createForm, blankForm())
    showCreateModal.value = true
}

const openEdit = (row) => {
    editTarget.value = row
    editForm.title       = row.title
    editForm.body        = row.body
    editForm.severity    = row.severity
    editForm.audience    = row.audience
    editForm.is_active   = !!row.is_active
    editForm.starts_at   = row.starts_at ?? ''
    editForm.ends_at     = row.ends_at   ?? ''
    editForm.dismissible = !!row.dismissible
    showEditModal.value  = true
}

const submitCreate = () => {
    createForm.post(route('admin.announcements.store'), {
        preserveScroll: true,
        onSuccess: () => { showCreateModal.value = false },
    })
}

const submitEdit = () => {
    editForm.patch(route('admin.announcements.update', editTarget.value.id), {
        preserveScroll: true,
        onSuccess: () => { showEditModal.value = false },
    })
}

const toggle = (id) => {
    router.post(route('admin.announcements.toggle', id), {}, { preserveScroll: true })
}

const destroy = async (row) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `"${row.title}" duyurusu silinsin mi?`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('admin.announcements.destroy', row.id), { preserveScroll: true })
}

// ─── Display helpers ──────────────────────────────────────────────────────────
const severityBadge = (s) => ({
    info:    'bg-blue-100 text-blue-700',
    success: 'bg-emerald-100 text-emerald-700',
    warning: 'bg-amber-100 text-amber-700',
    danger:  'bg-red-100 text-red-700',
}[s] || 'bg-slate-100 text-slate-600')

const severityLabel = (s) => ({
    info:    'Bilgi',
    success: 'Başarı',
    warning: 'Uyarı',
    danger:  'Tehlike',
}[s] || s)

const audienceLabel = (a) => ({
    all_customers:  'Tüm Müşteriler',
    resellers_only: 'Sadece Bayiler',
    admins_only:    'Sadece Adminler',
    all:            'Herkes',
}[a] || a)

const formatDate = (d) => {
    if (!d) return '—'
    return new Date(d).toLocaleDateString('tr-TR', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })
}

const isExpired = (row) => row.ends_at && new Date(row.ends_at) < new Date()
const isScheduled = (row) => row.starts_at && new Date(row.starts_at) > new Date()
</script>

<template>
    <Head title="Duyurular" />
    <AdminLayout>
        <template #header>Duyuru Yönetimi</template>

        <!-- Stat cards -->
        <div class="mb-5 grid grid-cols-2 gap-3 sm:grid-cols-4">
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="flex items-center justify-between">
                    <MegaphoneIcon class="h-5 w-5 text-slate-400" />
                </div>
                <div class="mt-2 text-2xl font-bold text-slate-800">{{ stats.total }}</div>
                <p class="text-xs text-slate-500">Toplam Duyuru</p>
            </div>
            <div class="rounded-xl border border-emerald-200 bg-emerald-50 p-4">
                <div class="flex items-center justify-between">
                    <CheckCircleIcon class="h-5 w-5 text-emerald-500" />
                </div>
                <div class="mt-2 text-2xl font-bold text-emerald-700">{{ stats.active }}</div>
                <p class="text-xs text-emerald-700">Aktif</p>
            </div>
            <div class="rounded-xl border border-blue-200 bg-blue-50 p-4">
                <div class="flex items-center justify-between">
                    <ClockIcon class="h-5 w-5 text-blue-500" />
                </div>
                <div class="mt-2 text-2xl font-bold text-blue-700">{{ stats.scheduled }}</div>
                <p class="text-xs text-blue-700">Zamanlanmış</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="flex items-center justify-between">
                    <XMarkIcon class="h-5 w-5 text-slate-400" />
                </div>
                <div class="mt-2 text-2xl font-bold text-slate-500">{{ stats.expired }}</div>
                <p class="text-xs text-slate-500">Süresi Dolmuş</p>
            </div>
        </div>

        <!-- Table header / create button -->
        <div class="mb-4 flex items-center justify-between">
            <h2 class="text-sm font-semibold text-slate-700">Tüm Duyurular</h2>
            <button @click="openCreate"
                class="inline-flex items-center gap-2 rounded-lg bg-rose-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-rose-700">
                <PlusIcon class="h-4 w-4" />
                Yeni Duyuru
            </button>
        </div>

        <!-- Table -->
        <div class="rounded-xl border border-slate-200 bg-white shadow-sm overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="border-b border-slate-100 bg-slate-50 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
                            <th class="px-4 py-3">Başlık / Önem</th>
                            <th class="px-4 py-3">Hedef Kitle</th>
                            <th class="px-4 py-3">Başlangıç</th>
                            <th class="px-4 py-3">Bitiş</th>
                            <th class="px-4 py-3 text-center">Görüntülenme</th>
                            <th class="px-4 py-3 text-center">Aktif</th>
                            <th class="px-4 py-3 text-right">İşlem</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-50">
                        <tr v-if="announcements.data.length === 0">
                            <td colspan="7" class="px-4 py-8 text-center text-sm text-slate-400">
                                Henüz duyuru yok. Yeni duyuru oluşturun.
                            </td>
                        </tr>
                        <tr v-for="ann in announcements.data" :key="ann.id"
                            :class="['hover:bg-slate-50 transition-colors', isExpired(ann) ? 'opacity-60' : '']">
                            <td class="px-4 py-3">
                                <div class="flex flex-wrap items-center gap-2">
                                    <span :class="['rounded-full px-2 py-0.5 text-[11px] font-semibold', severityBadge(ann.severity)]">
                                        {{ severityLabel(ann.severity) }}
                                    </span>
                                    <span v-if="isScheduled(ann)" class="rounded-full bg-blue-100 px-2 py-0.5 text-[11px] font-semibold text-blue-700">
                                        Zamanlanmış
                                    </span>
                                    <span v-if="isExpired(ann)" class="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-semibold text-slate-500">
                                        Süresi Doldu
                                    </span>
                                </div>
                                <div class="mt-1 font-medium text-slate-800 max-w-xs truncate" :title="ann.title">{{ ann.title }}</div>
                            </td>
                            <td class="px-4 py-3 text-slate-600">{{ audienceLabel(ann.audience) }}</td>
                            <td class="px-4 py-3 text-xs text-slate-500">{{ formatDate(ann.starts_at) }}</td>
                            <td class="px-4 py-3 text-xs text-slate-500">{{ formatDate(ann.ends_at) }}</td>
                            <td class="px-4 py-3 text-center text-slate-600">{{ ann.views_count }}</td>
                            <td class="px-4 py-3 text-center">
                                <button @click="toggle(ann.id)"
                                    :class="['relative inline-flex h-5 w-10 flex-shrink-0 rounded-full border-2 border-transparent transition-colors',
                                        ann.is_active ? 'bg-emerald-500' : 'bg-slate-200']">
                                    <span :class="['inline-block h-4 w-4 rounded-full bg-white shadow transition-transform',
                                        ann.is_active ? 'translate-x-5' : 'translate-x-0']" />
                                </button>
                            </td>
                            <td class="px-4 py-3">
                                <div class="flex items-center justify-end gap-1">
                                    <button @click="openEdit(ann)"
                                        class="rounded p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-700 transition-colors"
                                        title="Düzenle">
                                        <PencilIcon class="h-4 w-4" />
                                    </button>
                                    <button @click="destroy(ann)"
                                        class="rounded p-1.5 text-slate-400 hover:bg-red-50 hover:text-red-600 transition-colors"
                                        title="Sil">
                                        <TrashIcon class="h-4 w-4" />
                                    </button>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <div v-if="announcements.last_page > 1"
                class="flex items-center justify-between border-t border-slate-100 px-4 py-3">
                <span class="text-xs text-slate-500">
                    {{ announcements.from }}–{{ announcements.to }} / {{ announcements.total }} duyuru
                </span>
                <div class="flex gap-1">
                    <a v-if="announcements.prev_page_url" :href="announcements.prev_page_url"
                        class="rounded border border-slate-300 px-3 py-1 text-xs text-slate-700 hover:bg-slate-50">
                        ‹ Önceki
                    </a>
                    <a v-if="announcements.next_page_url" :href="announcements.next_page_url"
                        class="rounded border border-slate-300 px-3 py-1 text-xs text-slate-700 hover:bg-slate-50">
                        Sonraki ›
                    </a>
                </div>
            </div>
        </div>

        <!-- ─── Create Modal ─────────────────────────────────────────────────── -->
        <Teleport to="body">
            <div v-if="showCreateModal"
                class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4"
                @click.self="showCreateModal = false">
                <div class="w-full max-w-xl rounded-2xl bg-white shadow-2xl">
                    <div class="flex items-center justify-between border-b border-slate-200 px-6 py-4">
                        <div class="flex items-center gap-2">
                            <PlusIcon class="h-5 w-5 text-rose-500" />
                            <h3 class="font-semibold text-slate-900">Yeni Duyuru</h3>
                        </div>
                        <button @click="showCreateModal = false" class="rounded p-1 text-slate-400 hover:text-slate-700">
                            <XMarkIcon class="h-5 w-5" />
                        </button>
                    </div>
                    <form @submit.prevent="submitCreate" class="space-y-4 p-6">
                        <AnnouncementFormFields :form="createForm" />
                        <div class="flex justify-end gap-3 pt-2">
                            <button type="button" @click="showCreateModal = false"
                                class="rounded-lg border border-slate-300 px-4 py-2 text-sm text-slate-700 hover:bg-slate-50">
                                İptal
                            </button>
                            <button type="submit" :disabled="createForm.processing"
                                class="rounded-lg bg-rose-600 px-5 py-2 text-sm font-semibold text-white hover:bg-rose-700 disabled:opacity-50">
                                {{ createForm.processing ? 'Oluşturuluyor...' : 'Oluştur' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </Teleport>

        <!-- ─── Edit Modal ───────────────────────────────────────────────────── -->
        <Teleport to="body">
            <div v-if="showEditModal"
                class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4"
                @click.self="showEditModal = false">
                <div class="w-full max-w-xl rounded-2xl bg-white shadow-2xl">
                    <div class="flex items-center justify-between border-b border-slate-200 px-6 py-4">
                        <div class="flex items-center gap-2">
                            <PencilIcon class="h-5 w-5 text-slate-500" />
                            <h3 class="font-semibold text-slate-900">Duyuruyu Düzenle</h3>
                        </div>
                        <button @click="showEditModal = false" class="rounded p-1 text-slate-400 hover:text-slate-700">
                            <XMarkIcon class="h-5 w-5" />
                        </button>
                    </div>
                    <form @submit.prevent="submitEdit" class="space-y-4 p-6">
                        <AnnouncementFormFields :form="editForm" />
                        <div class="flex justify-end gap-3 pt-2">
                            <button type="button" @click="showEditModal = false"
                                class="rounded-lg border border-slate-300 px-4 py-2 text-sm text-slate-700 hover:bg-slate-50">
                                İptal
                            </button>
                            <button type="submit" :disabled="editForm.processing"
                                class="rounded-lg bg-rose-600 px-5 py-2 text-sm font-semibold text-white hover:bg-rose-700 disabled:opacity-50">
                                {{ editForm.processing ? 'Kaydediliyor...' : 'Kaydet' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </Teleport>
    </AdminLayout>
</template>

<!-- Inline sub-component to avoid duplicate form markup in both modals -->
<script>
// AnnouncementFormFields is defined inline below as a local component
import { defineComponent } from 'vue'

export default defineComponent({
    components: {
        AnnouncementFormFields: {
            props: { form: Object },
            template: `
                <div class="space-y-4">
                    <div>
                        <label class="block text-xs font-medium text-slate-700 mb-1">Başlık <span class="text-red-500">*</span></label>
                        <input v-model="form.title" type="text" maxlength="200" required
                            class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-rose-500"
                            :class="form.errors.title ? 'border-red-400' : ''" />
                        <p v-if="form.errors.title" class="mt-1 text-xs text-red-600">{{ form.errors.title }}</p>
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-slate-700 mb-1">İçerik <span class="text-red-500">*</span></label>
                        <textarea v-model="form.body" rows="4" required
                            class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-rose-500"
                            :class="form.errors.body ? 'border-red-400' : ''"></textarea>
                        <p v-if="form.errors.body" class="mt-1 text-xs text-red-600">{{ form.errors.body }}</p>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-medium text-slate-700 mb-1">Önem Seviyesi</label>
                            <select v-model="form.severity"
                                class="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-rose-500">
                                <option value="info">Bilgi</option>
                                <option value="success">Başarı</option>
                                <option value="warning">Uyarı</option>
                                <option value="danger">Tehlike</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-slate-700 mb-1">Hedef Kitle</label>
                            <select v-model="form.audience"
                                class="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-rose-500">
                                <option value="all_customers">Tüm Müşteriler</option>
                                <option value="resellers_only">Sadece Bayiler</option>
                                <option value="admins_only">Sadece Adminler</option>
                                <option value="all">Herkes</option>
                            </select>
                        </div>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-medium text-slate-700 mb-1">Başlangıç (opsiyonel)</label>
                            <input v-model="form.starts_at" type="datetime-local"
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-rose-500" />
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-slate-700 mb-1">Bitiş (opsiyonel)</label>
                            <input v-model="form.ends_at" type="datetime-local"
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-rose-500" />
                        </div>
                    </div>
                    <div class="flex items-center gap-6">
                        <label class="flex items-center gap-2 cursor-pointer select-none text-sm text-slate-700">
                            <input v-model="form.is_active" type="checkbox"
                                class="h-4 w-4 rounded border-slate-300 text-rose-600 focus:ring-rose-500" />
                            Hemen Aktif
                        </label>
                        <label class="flex items-center gap-2 cursor-pointer select-none text-sm text-slate-700">
                            <input v-model="form.dismissible" type="checkbox"
                                class="h-4 w-4 rounded border-slate-300 text-rose-600 focus:ring-rose-500" />
                            Kapatılabilir
                        </label>
                    </div>
                </div>
            `,
        },
    },
})
</script>
