<script setup>
import { ref, computed } from 'vue'
import { Head, useForm, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    PuzzlePieceIcon,
    InformationCircleIcon,
    MagnifyingGlassIcon,
    CheckCircleIcon,
    PlusIcon,
    TrashIcon,
    StarIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    installed_versions: Array,
    selected_version: String,
    extensions: Object,  // { installed: [{name, state}], available: [{name, state}] }
    hints: Object,
})

const search = ref('')
const tab = ref('installed')  // installed | available

const switchVersion = (v) => {
    router.get(route('admin.php-extensions.index'), { version: v }, {
        preserveScroll: true,
        preserveState: false,
    })
}

const filteredInstalled = computed(() => {
    const q = search.value.toLowerCase().trim()
    if (!q) return props.extensions?.installed ?? []
    return (props.extensions?.installed ?? []).filter((e) => e.name.toLowerCase().includes(q))
})

const filteredAvailable = computed(() => {
    const q = search.value.toLowerCase().trim()
    if (!q) return props.extensions?.available ?? []
    return (props.extensions?.available ?? []).filter((e) => e.name.toLowerCase().includes(q))
})

const popularNames = computed(() => Object.keys(props.hints ?? {}))

const popularExts = computed(() => {
    const installedNames = new Set((props.extensions?.installed ?? []).map((e) => e.name))
    return popularNames.value.map((name) => ({
        name,
        hint: props.hints[name],
        installed: installedNames.has(name),
    }))
})

const installForm = useForm({ version: props.selected_version, extension: '' })
const uninstallForm = useForm({ version: props.selected_version, extension: '' })

const doInstall = async (ext) => {
    const ok = await ask({
        title: 'Eklenti Kur',
        message: `${ext} eklentisi PHP ${props.selected_version} için kurulacak. FPM reload edilecek (~5sn downtime).`,
        variant: 'warning',
        confirmText: 'Kur',
        cancelText: 'İptal',
    })
    if (!ok) return

    installForm.version = props.selected_version
    installForm.extension = ext
    installForm.post(route('admin.php-extensions.install'), { preserveScroll: true })
}

const doUninstall = async (ext) => {
    const ok = await ask({
        title: 'Eklenti Kaldır',
        message: `${ext} eklentisi PHP ${props.selected_version}'den kaldırılacak. Bağımlı uygulamalar etkilenebilir.`,
        variant: 'danger',
        confirmText: 'Kaldır',
        cancelText: 'İptal',
    })
    if (!ok) return

    uninstallForm.version = props.selected_version
    uninstallForm.extension = ext
    uninstallForm.post(route('admin.php-extensions.uninstall'), { preserveScroll: true })
}

const versionPill = (v) => v === props.selected_version
    ? 'bg-indigo-600 text-white'
    : 'bg-slate-100 text-slate-700 hover:bg-slate-200'
</script>

<template>
    <Head title="PHP Eklentileri" />
    <AdminLayout>
        <template #header>PHP Eklentileri</template>

        <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>Per-version eklenti yönetimi:</strong>
                    Her PHP versiyonu için ayrı eklenti seti. <code class="rounded bg-white px-1">dnf install php83-php-imagick</code>
                    veya <code class="rounded bg-white px-1">apt install php8.3-redis</code> komutlarının UI muadili.
                    Kurulum sonrası ilgili php-fpm otomatik reload edilir.
                </div>
            </div>
        </div>

        <!-- Version selector -->
        <div class="mb-5">
            <div class="text-xs font-semibold text-slate-500 mb-2 uppercase tracking-wide">PHP Versiyonu</div>
            <div class="flex flex-wrap gap-1.5">
                <button v-for="v in installed_versions" :key="v"
                        @click="switchVersion(v)"
                        :class="['rounded-lg px-3 py-1.5 text-xs font-mono font-bold transition', versionPill(v)]">
                    PHP {{ v }}
                </button>
            </div>
        </div>

        <!-- Popular extensions section -->
        <div class="mb-6 rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
            <h3 class="text-sm font-semibold flex items-center gap-2 mb-3">
                <StarIcon class="h-4 w-4 text-amber-500" />
                Popüler Eklentiler (PHP {{ selected_version }})
            </h3>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
                <div v-for="ext in popularExts" :key="ext.name"
                     class="flex items-center justify-between gap-2 rounded-lg border p-3"
                     :class="ext.installed ? 'border-emerald-200 bg-emerald-50/30' : 'border-slate-200 bg-white'">
                    <div class="min-w-0 flex-1">
                        <div class="flex items-center gap-1.5">
                            <CheckCircleIcon v-if="ext.installed" class="h-3.5 w-3.5 flex-shrink-0 text-emerald-500" />
                            <span class="font-mono text-sm font-semibold">{{ ext.name }}</span>
                        </div>
                        <p class="text-xs text-slate-500 mt-0.5">{{ ext.hint }}</p>
                    </div>
                    <button v-if="!ext.installed"
                            @click="doInstall(ext.name)"
                            class="inline-flex items-center gap-1 rounded-md bg-emerald-600 px-2.5 py-1 text-xs font-medium text-white hover:bg-emerald-700">
                        <PlusIcon class="h-3 w-3" /> Kur
                    </button>
                    <button v-else
                            @click="doUninstall(ext.name)"
                            class="inline-flex items-center gap-1 rounded-md border border-red-200 bg-white px-2.5 py-1 text-xs font-medium text-red-700 hover:bg-red-50">
                        <TrashIcon class="h-3 w-3" /> Kaldır
                    </button>
                </div>
            </div>
        </div>

        <!-- All extensions grid -->
        <div class="rounded-xl border border-slate-200 bg-white shadow-sm">
            <div class="flex flex-wrap items-center justify-between gap-3 border-b border-slate-200 px-5 py-3">
                <div class="flex items-center gap-2">
                    <button @click="tab = 'installed'"
                            :class="['rounded-md px-3 py-1.5 text-xs font-semibold',
                                tab === 'installed' ? 'bg-emerald-600 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200']">
                        Kurulu ({{ extensions?.installed?.length ?? 0 }})
                    </button>
                    <button @click="tab = 'available'"
                            :class="['rounded-md px-3 py-1.5 text-xs font-semibold',
                                tab === 'available' ? 'bg-indigo-600 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200']">
                        Kurulabilir ({{ extensions?.available?.length ?? 0 }})
                    </button>
                </div>
                <div class="relative flex-1 sm:max-w-xs">
                    <MagnifyingGlassIcon class="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                    <input v-model="search" type="text" placeholder="Eklenti adı..."
                           class="w-full rounded-lg border border-slate-300 bg-white py-1.5 pl-9 pr-3 text-sm" />
                </div>
            </div>

            <!-- Installed list -->
            <div v-if="tab === 'installed'" class="p-3">
                <div v-if="filteredInstalled.length === 0" class="px-2 py-8 text-center text-sm text-slate-500">
                    Eşleşen kurulu eklenti yok.
                </div>
                <div v-else class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-2">
                    <div v-for="ext in filteredInstalled" :key="ext.name"
                         class="flex items-center justify-between gap-1 rounded-lg border border-emerald-200 bg-emerald-50/40 px-3 py-2">
                        <span class="font-mono text-xs font-semibold truncate">{{ ext.name }}</span>
                        <button @click="doUninstall(ext.name)"
                                class="text-red-500 hover:text-red-700"
                                :title="`${ext.name} kaldır`">
                            <TrashIcon class="h-3.5 w-3.5" />
                        </button>
                    </div>
                </div>
            </div>

            <!-- Available list -->
            <div v-else class="p-3">
                <div v-if="filteredAvailable.length === 0" class="px-2 py-8 text-center text-sm text-slate-500">
                    Eşleşen kurulabilir eklenti yok.
                </div>
                <div v-else class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-2">
                    <div v-for="ext in filteredAvailable" :key="ext.name"
                         class="flex items-center justify-between gap-1 rounded-lg border border-slate-200 bg-white px-3 py-2">
                        <span class="font-mono text-xs font-semibold truncate">{{ ext.name }}</span>
                        <button @click="doInstall(ext.name)"
                                class="text-emerald-600 hover:text-emerald-800"
                                :title="`${ext.name} kur`">
                            <PlusIcon class="h-3.5 w-3.5" />
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
