<script setup>
import { ref, computed } from 'vue'
import { Head, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    EnvelopeIcon,
    EyeIcon,
    PaperAirplaneIcon,
    CheckCircleIcon,
    XCircleIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    templates: { type: Array, default: () => [] },
    flash: { type: Object, default: () => ({}) },
})

// Preview modal
const previewOpen     = ref(false)
const previewKey      = ref('')
const previewLoading  = ref(false)
const previewSrc      = ref('')

function openPreview(key) {
    previewKey.value     = key
    previewLoading.value = true
    previewSrc.value     = route('admin.email-templates.preview', key)
    previewOpen.value    = true
}

function closePreview() {
    previewOpen.value = false
    previewSrc.value  = ''
}

// Test send
const testForm = ref({ to: '', template: '' })
const testOpen     = ref(false)
const testSending  = ref(false)
const testSuccess  = ref('')
const testError    = ref('')

function openTest(key) {
    testForm.value   = { to: '', template: key }
    testOpen.value   = true
    testSuccess.value = ''
    testError.value   = ''
}

function closeTest() {
    testOpen.value = false
}

function sendTest() {
    testSending.value = true
    testSuccess.value = ''
    testError.value   = ''

    router.post(route('admin.email-templates.test'), testForm.value, {
        preserveScroll: true,
        onSuccess: () => {
            testSuccess.value = `Test maili gönderildi: ${testForm.value.to}`
            testSending.value  = false
            testForm.value.to  = ''
        },
        onError: (errors) => {
            testError.value   = errors.to || errors.template || 'Gönderim başarısız.'
            testSending.value = false
        },
    })
}

// Group templates by category
const grouped = computed(() => {
    const groups = {}
    props.templates.forEach(t => {
        const [cat] = t.key.split('.')
        if (!groups[cat]) groups[cat] = []
        groups[cat].push(t)
    })
    return groups
})

const categoryLabels = {
    account:  'Hesap',
    ssl:      'SSL',
    quota:    'Disk Kotası',
    backup:   'Yedekleme',
    auth:     'Kimlik Doğrulama',
    billing:  'Faturalama',
    admin:    'Admin',
    reseller: 'Bayi',
    package:  'Paket',
    test:     'Test',
}
</script>

<template>
    <Head title="E-posta Şablonları" />
    <AdminLayout>
        <div class="space-y-6">
            <!-- Header -->
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-2xl font-bold text-slate-900 dark:text-white">E-posta Şablonları</h1>
                    <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
                        {{ props.templates.length }} sistem e-postası · Önizle ve test gönder
                    </p>
                </div>
                <div class="flex items-center gap-2">
                    <EnvelopeIcon class="h-6 w-6 text-slate-400" />
                </div>
            </div>

            <!-- Flash -->
            <div v-if="flash?.success" class="flex items-center gap-2 rounded-lg bg-green-50 border border-green-200 px-4 py-3 text-sm text-green-700 dark:bg-green-900/20 dark:border-green-800 dark:text-green-400">
                <CheckCircleIcon class="h-4 w-4 flex-shrink-0" />
                {{ flash.success }}
            </div>

            <!-- Template groups -->
            <div v-for="(items, cat) in grouped" :key="cat" class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 overflow-hidden">
                <div class="px-5 py-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/60">
                    <h2 class="text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">
                        {{ categoryLabels[cat] ?? cat }}
                    </h2>
                </div>
                <div class="divide-y divide-slate-100 dark:divide-slate-700">
                    <div
                        v-for="tpl in items"
                        :key="tpl.key"
                        class="flex items-center gap-4 px-5 py-4 hover:bg-slate-50 dark:hover:bg-slate-700/40 transition-colors"
                    >
                        <div class="flex-1 min-w-0">
                            <p class="font-medium text-sm text-slate-900 dark:text-white truncate">{{ tpl.name }}</p>
                            <p class="text-xs text-slate-500 dark:text-slate-400 mt-0.5">{{ tpl.description }}</p>
                        </div>
                        <code class="hidden sm:block text-[11px] text-slate-400 dark:text-slate-500 bg-slate-100 dark:bg-slate-700 px-2 py-0.5 rounded font-mono">
                            {{ tpl.key }}
                        </code>
                        <div class="flex items-center gap-2 flex-shrink-0">
                            <button
                                @click="openPreview(tpl.key)"
                                class="flex items-center gap-1 rounded-lg px-3 py-1.5 text-xs font-medium text-slate-700 dark:text-slate-300 bg-slate-100 dark:bg-slate-700 hover:bg-slate-200 dark:hover:bg-slate-600 transition-colors"
                            >
                                <EyeIcon class="h-3.5 w-3.5" />
                                Önizle
                            </button>
                            <button
                                @click="openTest(tpl.key)"
                                class="flex items-center gap-1 rounded-lg px-3 py-1.5 text-xs font-medium text-white bg-rose-600 hover:bg-rose-700 transition-colors"
                            >
                                <PaperAirplaneIcon class="h-3.5 w-3.5" />
                                Test Gönder
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Preview Modal -->
        <Teleport to="body">
            <div v-if="previewOpen" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" @click.self="closePreview">
                <div class="bg-white dark:bg-slate-800 rounded-xl shadow-2xl w-full max-w-2xl h-[85vh] flex flex-col overflow-hidden">
                    <div class="flex items-center justify-between px-5 py-3 border-b border-slate-200 dark:border-slate-700">
                        <h3 class="font-semibold text-slate-900 dark:text-white text-sm">
                            E-posta Önizleme — <code class="text-rose-500">{{ previewKey }}</code>
                        </h3>
                        <button @click="closePreview" class="text-slate-400 hover:text-slate-700 dark:hover:text-slate-200">
                            <XCircleIcon class="h-5 w-5" />
                        </button>
                    </div>
                    <div class="flex-1 overflow-hidden bg-slate-100">
                        <iframe
                            v-if="previewSrc"
                            :src="previewSrc"
                            class="w-full h-full border-0"
                            @load="previewLoading = false"
                        />
                        <div v-if="previewLoading" class="flex items-center justify-center h-full">
                            <div class="animate-spin h-6 w-6 border-2 border-rose-500 border-t-transparent rounded-full"></div>
                        </div>
                    </div>
                </div>
            </div>
        </Teleport>

        <!-- Test Send Modal -->
        <Teleport to="body">
            <div v-if="testOpen" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" @click.self="closeTest">
                <div class="bg-white dark:bg-slate-800 rounded-xl shadow-2xl w-full max-w-md">
                    <div class="flex items-center justify-between px-5 py-4 border-b border-slate-200 dark:border-slate-700">
                        <h3 class="font-semibold text-slate-900 dark:text-white">Test E-postası Gönder</h3>
                        <button @click="closeTest" class="text-slate-400 hover:text-slate-700 dark:hover:text-slate-200">
                            <XCircleIcon class="h-5 w-5" />
                        </button>
                    </div>
                    <div class="px-5 py-4 space-y-4">
                        <div>
                            <p class="text-xs text-slate-500 dark:text-slate-400 mb-1">Şablon</p>
                            <code class="text-sm text-rose-500">{{ testForm.template }}</code>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                                Alıcı E-posta
                            </label>
                            <input
                                v-model="testForm.to"
                                type="email"
                                placeholder="ornek@domain.com"
                                class="w-full rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-700 px-3 py-2 text-sm text-slate-900 dark:text-white placeholder-slate-400 focus:border-rose-500 focus:ring-1 focus:ring-rose-500 outline-none"
                                @keyup.enter="sendTest"
                            />
                        </div>

                        <div v-if="testSuccess" class="flex items-center gap-2 text-sm text-green-600 dark:text-green-400">
                            <CheckCircleIcon class="h-4 w-4 flex-shrink-0" />
                            {{ testSuccess }}
                        </div>
                        <div v-if="testError" class="flex items-center gap-2 text-sm text-red-600 dark:text-red-400">
                            <XCircleIcon class="h-4 w-4 flex-shrink-0" />
                            {{ testError }}
                        </div>
                    </div>
                    <div class="flex justify-end gap-3 px-5 py-4 border-t border-slate-200 dark:border-slate-700">
                        <button
                            @click="closeTest"
                            class="rounded-lg px-4 py-2 text-sm font-medium text-slate-700 dark:text-slate-300 bg-slate-100 dark:bg-slate-700 hover:bg-slate-200 dark:hover:bg-slate-600 transition-colors"
                        >
                            İptal
                        </button>
                        <button
                            @click="sendTest"
                            :disabled="!testForm.to || testSending"
                            class="flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white bg-rose-600 hover:bg-rose-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                        >
                            <div v-if="testSending" class="animate-spin h-4 w-4 border-2 border-white border-t-transparent rounded-full" />
                            <PaperAirplaneIcon v-else class="h-4 w-4" />
                            {{ testSending ? 'Gönderiliyor...' : 'Gönder' }}
                        </button>
                    </div>
                </div>
            </div>
        </Teleport>
    </AdminLayout>
</template>
