<script setup>
import { ref, computed } from 'vue'
import { Head, router, usePage } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()
import {
    PuzzlePieceIcon,
    CheckCircleIcon,
    XCircleIcon,
    TrashIcon,
    Cog6ToothIcon,
    ArrowUpCircleIcon,
    ArrowUpTrayIcon,
    ShoppingBagIcon,
} from '@heroicons/vue/24/outline'

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

const page    = usePage()
const flash   = computed(() => page.props.flash ?? {})

// ─── Upload modal ──────────────────────────────────────────────────────────────
const showUploadModal = ref(false)
const uploadFile      = ref(null)
const uploading       = ref(false)

const handleFileChange = (e) => {
    uploadFile.value = e.target.files[0] ?? null
}

const submitUpload = () => {
    if (!uploadFile.value) return
    uploading.value = true
    const form = new FormData()
    form.append('zip', uploadFile.value)
    router.post(route('admin.plugins.upload'), form, {
        forceFormData: true,
        onFinish: () => {
            uploading.value    = false
            showUploadModal.value = false
            uploadFile.value   = null
        },
    })
}

// ─── Actions ──────────────────────────────────────────────────────────────────
const togglePlugin = (slug) => {
    router.post(route('admin.plugins.toggle', slug))
}

const uninstallPlugin = async (slug, name) => {
    const ok = await ask({
        title: 'Eklentiyi kaldır',
        message: `'${name}' eklentisi kaldırılacak. Bu işlem geri alınamaz.`,
        variant: 'danger',
        confirmText: 'Kaldır',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('admin.plugins.uninstall', slug))
}

const categoryLabel = (cat) => {
    const map = {
        dns: 'DNS', billing: 'Fatura', migration: 'Göç',
        integration: 'Entegrasyon', compliance: 'Uyumluluk', cluster: 'Cluster',
    }
    return map[cat] ?? cat ?? '—'
}

const categoryColor = (cat) => {
    const map = {
        dns: 'bg-sky-100 text-sky-700 dark:bg-sky-900 dark:text-sky-300',
        billing: 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300',
        migration: 'bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300',
        integration: 'bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300',
        compliance: 'bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300',
        cluster: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900 dark:text-indigo-300',
    }
    return map[cat] ?? 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300'
}
</script>

<template>
    <AdminLayout>
        <Head title="Eklentiler" />

        <div class="p-6 space-y-6">

            <!-- Header -->
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <PuzzlePieceIcon class="h-7 w-7 text-indigo-500" />
                    <div>
                        <h1 class="text-xl font-bold text-slate-800 dark:text-slate-100">Eklentiler</h1>
                        <p class="text-sm text-slate-500 dark:text-slate-400">Kurulu pluginleri yönetin</p>
                    </div>
                </div>
                <div class="flex gap-2">
                    <a :href="route('admin.plugins.marketplace')"
                       class="inline-flex items-center gap-1.5 rounded-lg border border-slate-300 dark:border-slate-600 px-4 py-2 text-sm font-medium text-slate-700 dark:text-slate-200 hover:bg-slate-50 dark:hover:bg-slate-700 transition">
                        <ShoppingBagIcon class="h-4 w-4" />
                        Marketplace
                    </a>
                    <button @click="showUploadModal = true"
                            class="inline-flex items-center gap-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-700 px-4 py-2 text-sm font-medium text-white transition">
                        <ArrowUpTrayIcon class="h-4 w-4" />
                        Zip'ten Yükle
                    </button>
                </div>
            </div>

            <!-- Flash messages -->
            <div v-if="flash.success"
                 class="rounded-lg bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-700 px-4 py-3 text-green-800 dark:text-green-300 text-sm">
                {{ flash.success }}
            </div>
            <div v-if="flash.error"
                 class="rounded-lg bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-700 px-4 py-3 text-red-800 dark:text-red-300 text-sm">
                {{ flash.error }}
            </div>

            <!-- Empty state -->
            <div v-if="!plugins.length"
                 class="rounded-xl border-2 border-dashed border-slate-200 dark:border-slate-700 py-16 text-center">
                <PuzzlePieceIcon class="mx-auto h-12 w-12 text-slate-300 dark:text-slate-600 mb-4" />
                <h2 class="text-lg font-semibold text-slate-600 dark:text-slate-400">Henüz plugin kurulu değil</h2>
                <p class="mt-1 text-sm text-slate-400 dark:text-slate-500">Marketplace'den plugin keşfedin veya zip dosyası yükleyin.</p>
                <div class="mt-6 flex justify-center gap-3">
                    <a :href="route('admin.plugins.marketplace')"
                       class="rounded-lg bg-indigo-600 hover:bg-indigo-700 px-4 py-2 text-sm font-medium text-white transition">
                        Marketplace'e Git
                    </a>
                    <button @click="showUploadModal = true"
                            class="rounded-lg border border-slate-300 dark:border-slate-600 px-4 py-2 text-sm font-medium text-slate-700 dark:text-slate-200 hover:bg-slate-50 dark:hover:bg-slate-700 transition">
                        Zip Yükle
                    </button>
                </div>
            </div>

            <!-- Plugin grid -->
            <div v-else class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                <div v-for="plugin in plugins" :key="plugin.slug"
                     class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-5 flex flex-col gap-3 shadow-sm hover:shadow-md transition">

                    <!-- Top row -->
                    <div class="flex items-start justify-between gap-2">
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center gap-2 flex-wrap">
                                <h3 class="font-semibold text-slate-800 dark:text-slate-100 truncate">{{ plugin.name }}</h3>
                                <span v-if="plugin.category" :class="categoryColor(plugin.category)"
                                      class="text-xs font-medium px-2 py-0.5 rounded-full">
                                    {{ categoryLabel(plugin.category) }}
                                </span>
                            </div>
                            <p class="text-xs text-slate-400 dark:text-slate-500 mt-0.5">
                                v{{ plugin.version }}
                                <span v-if="plugin.author"> · {{ plugin.author }}</span>
                            </p>
                        </div>
                        <!-- Status badge -->
                        <span :class="plugin.enabled
                            ? 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300'
                            : 'bg-slate-100 text-slate-500 dark:bg-slate-700 dark:text-slate-400'"
                              class="shrink-0 flex items-center gap-1 text-xs font-medium px-2 py-0.5 rounded-full">
                            <CheckCircleIcon v-if="plugin.enabled" class="h-3 w-3" />
                            <XCircleIcon v-else class="h-3 w-3" />
                            {{ plugin.enabled ? 'Aktif' : 'Pasif' }}
                        </span>
                    </div>

                    <!-- Description -->
                    <p class="text-sm text-slate-600 dark:text-slate-300 line-clamp-2 flex-1">
                        {{ plugin.description || '—' }}
                    </p>

                    <!-- Actions -->
                    <div class="flex items-center gap-2 pt-1 border-t border-slate-100 dark:border-slate-700">
                        <a :href="route('admin.plugins.show', plugin.slug)"
                           class="flex-1 text-center rounded-lg border border-slate-200 dark:border-slate-600 px-3 py-1.5 text-xs font-medium text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700 transition inline-flex items-center justify-center gap-1">
                            <Cog6ToothIcon class="h-3.5 w-3.5" />
                            Ayarlar
                        </a>
                        <button @click="togglePlugin(plugin.slug)"
                                :class="plugin.enabled ? 'text-amber-600 hover:bg-amber-50 dark:hover:bg-amber-900/20' : 'text-green-600 hover:bg-green-50 dark:hover:bg-green-900/20'"
                                class="rounded-lg border border-slate-200 dark:border-slate-600 px-3 py-1.5 text-xs font-medium transition inline-flex items-center gap-1">
                            <ArrowUpCircleIcon class="h-3.5 w-3.5" />
                            {{ plugin.enabled ? 'Durdur' : 'Başlat' }}
                        </button>
                        <button @click="uninstallPlugin(plugin.slug, plugin.name)"
                                class="rounded-lg border border-red-200 dark:border-red-800 px-2.5 py-1.5 text-xs font-medium text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 transition">
                            <TrashIcon class="h-3.5 w-3.5" />
                        </button>
                    </div>

                </div>
            </div>

        </div>

        <!-- Upload modal -->
        <Teleport to="body">
            <div v-if="showUploadModal"
                 class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
                <div class="w-full max-w-md rounded-2xl bg-white dark:bg-slate-800 shadow-2xl p-6 space-y-5">
                    <div class="flex items-center justify-between">
                        <h2 class="text-lg font-bold text-slate-800 dark:text-slate-100">Plugin Yükle (.zip)</h2>
                        <button @click="showUploadModal = false"
                                class="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200">✕</button>
                    </div>
                    <p class="text-sm text-slate-500 dark:text-slate-400">
                        Geçerli bir Onoxsoft plugin zip dosyası seçin. Kök dizinde <code class="bg-slate-100 dark:bg-slate-700 px-1 rounded">plugin.json</code> bulunmalıdır.
                    </p>
                    <input type="file" accept=".zip"
                           @change="handleFileChange"
                           class="block w-full text-sm text-slate-600 dark:text-slate-300 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-indigo-50 file:text-indigo-700 dark:file:bg-indigo-900 dark:file:text-indigo-300 hover:file:bg-indigo-100 dark:hover:file:bg-indigo-800 transition" />
                    <div class="flex gap-3 pt-1">
                        <button @click="showUploadModal = false"
                                class="flex-1 rounded-lg border border-slate-300 dark:border-slate-600 py-2 text-sm font-medium text-slate-700 dark:text-slate-200 hover:bg-slate-50 dark:hover:bg-slate-700 transition">
                            İptal
                        </button>
                        <button @click="submitUpload"
                                :disabled="!uploadFile || uploading"
                                class="flex-1 rounded-lg bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed py-2 text-sm font-medium text-white transition">
                            {{ uploading ? 'Yükleniyor…' : 'Kur' }}
                        </button>
                    </div>
                </div>
            </div>
        </Teleport>

    </AdminLayout>
</template>
