<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,
    Cog6ToothIcon,
    BoltIcon,
    GlobeAltIcon,
    ShieldCheckIcon,
    TrashIcon,
    CheckCircleIcon,
    XCircleIcon,
    ArrowLeftIcon,
    InformationCircleIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    plugin: { type: Object, required: true },
})

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

// ─── Active tab ───────────────────────────────────────────────────────────────
const tabs = ['Genel', 'Ayarlar', 'Hook\'lar', 'Route\'lar']
const activeTab = ref('Genel')

// ─── Settings form ────────────────────────────────────────────────────────────
const settingsSchema  = computed(() => props.plugin.manifest?.settings_schema ?? {})
const hasSettings     = computed(() => Object.keys(settingsSchema.value).length > 0)
const settingsForm    = ref({ ...props.plugin.config })
const savingSettings  = ref(false)

const saveSettings = () => {
    savingSettings.value = true
    router.patch(route('admin.plugins.settings.update', props.plugin.slug), settingsForm.value, {
        preserveState: true,
        onFinish: () => { savingSettings.value = false },
    })
}

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

const uninstallPlugin = async () => {
    const ok = await ask({
        title: 'Eklentiyi kaldır',
        message: `'${props.plugin.name}' eklentisi kaldırılacak. Eklentiye ait veriler silinebilir.`,
        variant: 'danger',
        confirmText: 'Kaldır',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('admin.plugins.uninstall', props.plugin.slug), {
        onSuccess: () => router.visit(route('admin.plugins.index')),
    })
}

const permissionColor = (perm) => {
    if (perm.startsWith('dns')) return 'bg-sky-100 text-sky-700 dark:bg-sky-900 dark:text-sky-300'
    if (perm.startsWith('billing')) return 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300'
    if (perm.startsWith('mail')) return 'bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300'
    if (perm.startsWith('http')) return 'bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300'
    return 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300'
}

const inputClass = 'w-full rounded-lg border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-900 text-sm text-slate-800 dark:text-slate-200 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-400 transition'
</script>

<template>
    <AdminLayout>
        <Head :title="plugin.name" />

        <div class="p-6 space-y-6 max-w-4xl mx-auto">

            <!-- Back + actions bar -->
            <div class="flex items-center justify-between flex-wrap gap-3">
                <a :href="route('admin.plugins.index')"
                   class="flex items-center gap-1.5 text-sm text-slate-500 dark:text-slate-400 hover:text-indigo-500 transition">
                    <ArrowLeftIcon class="h-4 w-4" />
                    Pluginler
                </a>
                <div class="flex gap-2">
                    <button @click="togglePlugin"
                            :class="plugin.enabled
                                ? 'border-amber-300 text-amber-600 hover:bg-amber-50 dark:border-amber-700 dark:text-amber-400 dark:hover:bg-amber-900/20'
                                : 'border-green-300 text-green-600 hover:bg-green-50 dark:border-green-700 dark:text-green-400 dark:hover:bg-green-900/20'"
                            class="inline-flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-sm font-medium transition">
                        <CheckCircleIcon v-if="!plugin.enabled" class="h-4 w-4" />
                        <XCircleIcon v-else class="h-4 w-4" />
                        {{ plugin.enabled ? 'Devre Dışı Bırak' : 'Etkinleştir' }}
                    </button>
                    <button @click="uninstallPlugin"
                            class="inline-flex items-center gap-1.5 rounded-lg border border-red-200 dark:border-red-700 px-3 py-1.5 text-sm font-medium text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 transition">
                        <TrashIcon class="h-4 w-4" />
                        Kaldır
                    </button>
                </div>
            </div>

            <!-- Plugin header card -->
            <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-6 flex items-start gap-4">
                <div class="h-14 w-14 rounded-xl bg-slate-100 dark:bg-slate-700 flex items-center justify-center shrink-0">
                    <PuzzlePieceIcon class="h-8 w-8 text-indigo-400" />
                </div>
                <div class="flex-1 min-w-0">
                    <div class="flex items-center gap-2 flex-wrap">
                        <h1 class="text-xl font-bold text-slate-800 dark:text-slate-100">{{ plugin.name }}</h1>
                        <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="text-xs font-medium px-2 py-0.5 rounded-full flex items-center gap-1">
                            <CheckCircleIcon v-if="plugin.enabled" class="h-3 w-3" />
                            <XCircleIcon v-else class="h-3 w-3" />
                            {{ plugin.enabled ? 'Aktif' : 'Pasif' }}
                        </span>
                    </div>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-0.5">
                        v{{ plugin.version }}
                        <span v-if="plugin.author"> · {{ plugin.author }}</span>
                        <span v-if="plugin.manifest?.license"> · {{ plugin.manifest.license }}</span>
                    </p>
                    <p v-if="plugin.description" class="mt-2 text-sm text-slate-600 dark:text-slate-300">
                        {{ plugin.description }}
                    </p>
                </div>
            </div>

            <!-- Flash -->
            <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>

            <!-- Tabs -->
            <div class="border-b border-slate-200 dark:border-slate-700">
                <nav class="flex gap-0 -mb-px">
                    <button v-for="tab in tabs" :key="tab"
                            @click="activeTab = tab"
                            :class="activeTab === tab
                                ? 'border-b-2 border-indigo-500 text-indigo-600 dark:text-indigo-400'
                                : 'text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200'"
                            class="px-4 py-3 text-sm font-medium transition">
                        {{ tab }}
                    </button>
                </nav>
            </div>

            <!-- Tab: Genel ──────────────────────────────────────────────────────── -->
            <div v-if="activeTab === 'Genel'" class="space-y-4">

                <!-- Info table -->
                <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 overflow-hidden">
                    <table class="w-full text-sm">
                        <tbody class="divide-y divide-slate-100 dark:divide-slate-700">
                            <tr v-if="plugin.manifest?.category">
                                <td class="px-4 py-3 text-slate-500 dark:text-slate-400 w-40">Kategori</td>
                                <td class="px-4 py-3 text-slate-800 dark:text-slate-200 font-medium">{{ plugin.manifest.category }}</td>
                            </tr>
                            <tr>
                                <td class="px-4 py-3 text-slate-500 dark:text-slate-400">Versiyon</td>
                                <td class="px-4 py-3 text-slate-800 dark:text-slate-200 font-mono">{{ plugin.version }}</td>
                            </tr>
                            <tr>
                                <td class="px-4 py-3 text-slate-500 dark:text-slate-400">Min. Panel</td>
                                <td class="px-4 py-3 text-slate-800 dark:text-slate-200 font-mono">{{ plugin.manifest?.minimum_panel_version }}</td>
                            </tr>
                            <tr v-if="plugin.manifest?.homepage">
                                <td class="px-4 py-3 text-slate-500 dark:text-slate-400">Ana Sayfa</td>
                                <td class="px-4 py-3">
                                    <a :href="plugin.manifest.homepage" target="_blank" rel="noopener"
                                       class="text-indigo-500 hover:underline">{{ plugin.manifest.homepage }}</a>
                                </td>
                            </tr>
                            <tr v-if="plugin.installed_at">
                                <td class="px-4 py-3 text-slate-500 dark:text-slate-400">Kurulum</td>
                                <td class="px-4 py-3 text-slate-800 dark:text-slate-200">{{ plugin.installed_at }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Permissions -->
                <div v-if="plugin.manifest?.permissions?.length" class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-4 space-y-3">
                    <div class="flex items-center gap-2">
                        <ShieldCheckIcon class="h-5 w-5 text-slate-400" />
                        <h3 class="font-semibold text-slate-700 dark:text-slate-200 text-sm">İzinler</h3>
                    </div>
                    <div class="flex flex-wrap gap-2">
                        <span v-for="perm in plugin.manifest.permissions" :key="perm"
                              :class="permissionColor(perm)"
                              class="font-mono text-xs px-2.5 py-1 rounded-full">{{ perm }}</span>
                    </div>
                </div>

                <!-- Tags -->
                <div v-if="plugin.manifest?.tags?.length" class="flex flex-wrap gap-2">
                    <span v-for="tag in plugin.manifest.tags" :key="tag"
                          class="bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-300 text-xs px-2.5 py-1 rounded-full">
                        #{{ tag }}
                    </span>
                </div>
            </div>

            <!-- Tab: Ayarlar ─────────────────────────────────────────────────────── -->
            <div v-else-if="activeTab === 'Ayarlar'" class="space-y-4">
                <div v-if="!hasSettings"
                     class="flex items-center gap-3 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 px-4 py-4">
                    <InformationCircleIcon class="h-5 w-5 text-slate-400 shrink-0" />
                    <p class="text-sm text-slate-500 dark:text-slate-400">Bu plugin için yapılandırılabilir ayar bulunmuyor.</p>
                </div>

                <form v-else @submit.prevent="saveSettings"
                      class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-6 space-y-5">

                    <div v-for="(field, key) in settingsSchema" :key="key" class="space-y-1.5">
                        <label :for="`setting-${key}`" class="block text-sm font-medium text-slate-700 dark:text-slate-200">
                            {{ field.label }}
                            <span v-if="field.required" class="text-red-500 ml-0.5">*</span>
                        </label>

                        <!-- Boolean toggle -->
                        <div v-if="field.type === 'boolean'" class="flex items-center gap-3">
                            <button type="button"
                                    @click="settingsForm[key] = !settingsForm[key]"
                                    :class="settingsForm[key]
                                        ? 'bg-indigo-600'
                                        : 'bg-slate-200 dark:bg-slate-700'"
                                    class="relative inline-flex h-6 w-11 shrink-0 rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-400 focus:ring-offset-2">
                                <span :class="settingsForm[key] ? 'translate-x-5' : 'translate-x-0.5'"
                                      class="inline-block h-5 w-5 transform rounded-full bg-white shadow transition-transform" />
                            </button>
                            <span class="text-sm text-slate-600 dark:text-slate-400">
                                {{ settingsForm[key] ? 'Açık' : 'Kapalı' }}
                            </span>
                        </div>

                        <!-- Select -->
                        <select v-else-if="field.type === 'select'"
                                :id="`setting-${key}`"
                                v-model="settingsForm[key]"
                                :class="inputClass">
                            <option v-for="opt in field.options" :key="opt" :value="opt">{{ opt }}</option>
                        </select>

                        <!-- Textarea -->
                        <textarea v-else-if="field.type === 'textarea'"
                                  :id="`setting-${key}`"
                                  v-model="settingsForm[key]"
                                  rows="3"
                                  :class="inputClass" />

                        <!-- Password -->
                        <input v-else-if="field.type === 'password'"
                               :id="`setting-${key}`"
                               type="password"
                               v-model="settingsForm[key]"
                               :placeholder="field.placeholder ?? ''"
                               :class="inputClass" />

                        <!-- Number -->
                        <input v-else-if="field.type === 'number'"
                               :id="`setting-${key}`"
                               type="number"
                               v-model.number="settingsForm[key]"
                               :class="inputClass" />

                        <!-- String (default) -->
                        <input v-else
                               :id="`setting-${key}`"
                               type="text"
                               v-model="settingsForm[key]"
                               :placeholder="field.placeholder ?? ''"
                               :class="inputClass" />

                        <p v-if="field.description" class="text-xs text-slate-400 dark:text-slate-500">{{ field.description }}</p>
                    </div>

                    <div class="flex justify-end pt-2">
                        <button type="submit"
                                :disabled="savingSettings"
                                class="rounded-lg bg-indigo-600 hover:bg-indigo-700 disabled:opacity-60 px-5 py-2 text-sm font-medium text-white transition">
                            {{ savingSettings ? 'Kaydediliyor…' : 'Kaydet' }}
                        </button>
                    </div>
                </form>
            </div>

            <!-- Tab: Hook'lar ────────────────────────────────────────────────────── -->
            <div v-else-if="activeTab === 'Hook\'lar'" class="space-y-3">
                <div v-if="!Object.keys(plugin.manifest?.hooks ?? {}).length"
                     class="flex items-center gap-3 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 px-4 py-4">
                    <InformationCircleIcon class="h-5 w-5 text-slate-400 shrink-0" />
                    <p class="text-sm text-slate-500 dark:text-slate-400">Bu plugin hook tanımlamıyor.</p>
                </div>

                <div v-else class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 overflow-hidden">
                    <div class="px-4 py-3 border-b border-slate-100 dark:border-slate-700 flex items-center gap-2">
                        <BoltIcon class="h-4 w-4 text-slate-400" />
                        <span class="text-sm font-semibold text-slate-700 dark:text-slate-200">Kayıtlı Hook'lar</span>
                    </div>
                    <table class="w-full text-sm">
                        <thead class="bg-slate-50 dark:bg-slate-900">
                            <tr>
                                <th class="px-4 py-2 text-left text-xs font-semibold text-slate-500 uppercase">Olay</th>
                                <th class="px-4 py-2 text-left text-xs font-semibold text-slate-500 uppercase">Handler</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 dark:divide-slate-700">
                            <tr v-for="(handler, event) in plugin.manifest.hooks" :key="event">
                                <td class="px-4 py-3 font-mono text-indigo-600 dark:text-indigo-400">{{ event }}</td>
                                <td class="px-4 py-3 font-mono text-slate-600 dark:text-slate-300 text-xs">{{ handler }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Tab: Route'lar ───────────────────────────────────────────────────── -->
            <div v-else-if="activeTab === 'Route\'lar'" class="space-y-3">
                <div v-if="!plugin.manifest?.routes?.length"
                     class="flex items-center gap-3 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 px-4 py-4">
                    <InformationCircleIcon class="h-5 w-5 text-slate-400 shrink-0" />
                    <p class="text-sm text-slate-500 dark:text-slate-400">Bu plugin özel HTTP route tanımlamıyor.</p>
                </div>

                <div v-else class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 overflow-hidden">
                    <div class="px-4 py-3 border-b border-slate-100 dark:border-slate-700 flex items-center gap-2">
                        <GlobeAltIcon class="h-4 w-4 text-slate-400" />
                        <span class="text-sm font-semibold text-slate-700 dark:text-slate-200">HTTP Route'lar</span>
                    </div>
                    <table class="w-full text-sm">
                        <thead class="bg-slate-50 dark:bg-slate-900">
                            <tr>
                                <th class="px-4 py-2 text-left text-xs font-semibold text-slate-500 uppercase">Method</th>
                                <th class="px-4 py-2 text-left text-xs font-semibold text-slate-500 uppercase">Path</th>
                                <th class="px-4 py-2 text-left text-xs font-semibold text-slate-500 uppercase">Handler</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 dark:divide-slate-700">
                            <tr v-for="rt in plugin.manifest.routes" :key="rt.path + rt.method">
                                <td class="px-4 py-3">
                                    <span :class="{
                                        'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300': rt.method === 'GET',
                                        'bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300': rt.method === 'POST',
                                        'bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300': rt.method === 'PATCH' || rt.method === 'PUT',
                                        'bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300': rt.method === 'DELETE',
                                    }" class="font-mono text-xs font-bold px-2 py-0.5 rounded">{{ rt.method }}</span>
                                </td>
                                <td class="px-4 py-3 font-mono text-slate-700 dark:text-slate-200 text-xs">
                                    /admin/plugins/{{ plugin.slug }}{{ rt.path }}
                                </td>
                                <td class="px-4 py-3 font-mono text-slate-500 dark:text-slate-400 text-xs">{{ rt.handler }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </AdminLayout>
</template>
