<script setup>
import { ref } from 'vue'
import { Head, Link, router, useForm } from '@inertiajs/vue3'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import { UserGroupIcon, PlusIcon, TrashIcon, XMarkIcon, KeyIcon, InformationCircleIcon } from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({ lists: Array, available_domains: Array })

const showForm = ref(false)

const form = useForm({
    local: '',
    domain: props.available_domains[0] || '',
    description: '',
    access_type: 'private',
    admin_password: '',
})

const submit = () => form.post(route('customer.email.mailing-lists.store'), {
    preserveScroll: true,
    onSuccess: () => { showForm.value = false; form.reset(); form.access_type = 'private'; form.domain = props.available_domains[0] || '' },
})

const remove = async (l) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `'${l.local}@${l.domain}' silinecek? Tüm aboneler kaybolur.`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('customer.email.mailing-lists.destroy', l.id), { preserveScroll: true })
}

const generatePassword = () => {
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    let p = ''
    for (let i = 0; i < 16; i++) p += chars.charAt(Math.floor(Math.random() * chars.length))
    form.admin_password = p
}

const typeBadge = (t) => ({
    public: 'bg-emerald-100 text-emerald-700',
    private: 'bg-slate-100 text-slate-700',
    announce_only: 'bg-blue-100 text-blue-700',
    moderated: 'bg-amber-100 text-amber-700',
}[t] || 'bg-slate-100 text-slate-700')
</script>

<template>
    <Head title="Mailing Lists" />
    <CustomerLayout>
        <template #header>Mailing Lists (E-posta Grupları)</template>

        <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 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">Mailing Lists</span>
            <Link :href="route('customer.email.spam.index')" class="px-4 py-2 text-slate-600 hover:text-slate-900">Spam Filtresi</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>Mailing List:</strong> Birden fazla aboneye tek e-posta adresinden mesaj gönder
                    (örn: <code>haber@firma.com</code>). Liste tanımları kaydedildiğinde sistem yöneticisi
                    mlmmj/postfix tarafına eklediğinde aktif olur.
                </div>
            </div>
        </div>

        <div class="mb-4 flex justify-end">
            <button @click="showForm = true" :disabled="available_domains.length === 0"
                    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 Mailing List
            </button>
        </div>

        <div v-if="lists.length === 0" class="rounded-xl border border-dashed border-slate-300 bg-white p-12 text-center">
            <UserGroupIcon class="mx-auto h-14 w-14 text-slate-300" />
            <h3 class="mt-3 text-lg font-semibold">Henüz mailing list yok</h3>
        </div>

        <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 text-sm">
                <thead class="bg-slate-50 text-xs uppercase text-slate-500">
                    <tr>
                        <th class="px-4 py-2 text-left">Liste Adresi</th>
                        <th class="px-4 py-2 text-left">Açıklama</th>
                        <th class="px-4 py-2 text-left">Tip</th>
                        <th class="px-4 py-2 text-left">Abone</th>
                        <th class="px-4 py-2"></th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <tr v-for="l in lists" :key="l.id" class="hover:bg-slate-50">
                        <td class="px-4 py-2 font-mono text-sm">{{ l.local }}@{{ l.domain }}</td>
                        <td class="px-4 py-2 text-xs text-slate-600">{{ l.description || '—' }}</td>
                        <td class="px-4 py-2"><span :class="['rounded px-2 py-0.5 text-xs font-semibold', typeBadge(l.access_type)]">{{ l.access_type }}</span></td>
                        <td class="px-4 py-2 text-xs">{{ l.subscribers_count }} kişi</td>
                        <td class="px-4 py-2 text-right">
                            <button @click="remove(l)" 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 v-if="showForm" 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 Mailing List</h3>
                    <button @click="showForm = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>
                <form @submit.prevent="submit" class="space-y-4">
                    <div class="grid grid-cols-2 gap-2">
                        <input v-model="form.local" type="text" placeholder="haber" class="rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                        <select v-model="form.domain" class="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>
                    <input v-model="form.description" type="text" placeholder="Açıklama (opsiyonel)" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                    <div>
                        <label class="block text-sm font-medium">Erişim Tipi</label>
                        <select v-model="form.access_type" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                            <option value="private">Private (sadece üyeler yazabilir)</option>
                            <option value="public">Public (herkes yazabilir)</option>
                            <option value="announce_only">Announce-only (sadece admin yazar)</option>
                            <option value="moderated">Moderated (admin onaylar)</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Admin Parolası</label>
                        <div class="mt-1 flex gap-2">
                            <input v-model="form.admin_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 class="flex justify-end gap-2 border-t pt-3">
                        <button type="button" @click="showForm = false" class="rounded-lg border border-slate-300 px-4 py-2 text-sm">İptal</button>
                        <button type="submit" :disabled="form.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>
