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

const { ask } = useConfirm()
import {
    ShoppingBagIcon,
    MagnifyingGlassIcon,
    ArrowDownTrayIcon,
    StarIcon,
    CheckBadgeIcon,
    BeakerIcon,
    ExclamationTriangleIcon,
    PuzzlePieceIcon,
    AdjustmentsHorizontalIcon,
} from '@heroicons/vue/24/outline'
import { CheckBadgeIcon as CheckBadgeSolid } from '@heroicons/vue/24/solid'

const props = defineProps({
    plugins:    { type: Array,  default: () => [] },
    categories: { type: Object, default: () => ({}) },
    filters:    { type: Object, default: () => ({}) },
    isMock:     { type: Boolean, default: false },
})

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

// Filters
const searchQuery    = ref(props.filters.search ?? '')
const activeCategory = ref(props.filters.category ?? '')
const sortBy         = ref(props.filters.sort ?? 'popular')

const applyFilters = () => {
    router.get(route('admin.plugins.marketplace'), {
        search:   searchQuery.value || undefined,
        category: activeCategory.value || undefined,
        sort:     sortBy.value !== 'popular' ? sortBy.value : undefined,
    }, { preserveState: true, replace: true })
}

let searchTimer = null
watch(searchQuery, () => {
    clearTimeout(searchTimer)
    searchTimer = setTimeout(applyFilters, 350)
})
watch(sortBy, applyFilters)

// Install
const installing = ref(null)
const installPlugin = async (slug, e) => {
    e?.stopPropagation()
    e?.preventDefault()
    const ok = await ask({
        title: 'Eklentiyi kur',
        message: `'${slug}' eklentisi marketplace'den indirilip kurulacak.`,
        variant: 'info',
        confirmText: 'Kur',
        cancelText: 'İptal',
    })
    if (!ok) return
    installing.value = slug
    router.post(route('admin.plugins.marketplace.install', slug), {}, {
        onFinish: () => { installing.value = null },
    })
}

// Helpers
const formatDownloads = (n) => n >= 1000 ? (n / 1000).toFixed(1) + 'k' : String(n)
const isBeta = (v) => v && (v.includes('beta') || v.includes('alpha'))

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="Plugin Marketplace" />

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

            <!-- Header -->
            <div class="flex items-center justify-between flex-wrap gap-3">
                <div class="flex items-center gap-3">
                    <ShoppingBagIcon class="h-7 w-7 text-indigo-500" />
                    <div>
                        <h1 class="text-xl font-bold text-slate-800 dark:text-slate-100">Plugin Marketplace</h1>
                        <p class="text-sm text-slate-500 dark:text-slate-400">Onoxsoft için eklentileri keşfedin ve kurun</p>
                    </div>
                </div>
                <a :href="route('admin.plugins.installed')"
                   class="text-sm text-indigo-600 dark:text-indigo-400 hover:underline">
                    ← Kurulu Pluginler
                </a>
            </div>

            <!-- Mock warning -->
            <div v-if="isMock"
                 class="flex items-start gap-3 rounded-lg border border-amber-200 dark:border-amber-700 bg-amber-50 dark:bg-amber-900/20 px-4 py-3">
                <BeakerIcon class="h-5 w-5 text-amber-500 shrink-0 mt-0.5" />
                <p class="text-sm text-amber-800 dark:text-amber-300">
                    <strong>Geliştirme modu:</strong> Sahte marketplace verileri gösteriliyor. Gerçek kurulum için <code class="bg-amber-100 dark:bg-amber-800 px-1 rounded">PLUGIN_MARKETPLACE_ENABLED=true</code> ayarlayın.
                </p>
            </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>

            <!-- Search + Sort + Filters -->
            <div class="flex flex-wrap gap-3 items-center">
                <div class="relative flex-1 min-w-[220px] max-w-sm">
                    <MagnifyingGlassIcon class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                    <input v-model="searchQuery" type="search" placeholder="Plugin ara…"
                           class="w-full pl-9 pr-4 py-2 rounded-lg border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-800 text-sm text-slate-800 dark:text-slate-200 focus:outline-none focus:ring-2 focus:ring-indigo-400 transition" />
                </div>

                <div class="flex items-center gap-2">
                    <AdjustmentsHorizontalIcon class="h-4 w-4 text-slate-400" />
                    <select v-model="sortBy"
                            class="rounded-lg border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-800 text-sm text-slate-800 dark:text-slate-200 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-400">
                        <option value="popular">Popüler</option>
                        <option value="newest">En Yeni</option>
                        <option value="rating">En Yüksek Puan</option>
                        <option value="name">İsim</option>
                    </select>
                </div>

                <div class="flex flex-wrap gap-2">
                    <button v-for="(label, key) in categories" :key="key"
                            @click="activeCategory = key; applyFilters()"
                            :class="activeCategory === key
                                ? 'bg-indigo-600 text-white border-indigo-600'
                                : 'border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700'"
                            class="px-3 py-1.5 rounded-full border text-xs font-medium transition">
                        {{ label }}
                    </button>
                </div>
            </div>

            <!-- Plugin cards -->
            <div v-if="plugins.length" class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                <a v-for="plugin in plugins" :key="plugin.slug"
                   :href="route('admin.plugins.marketplace.show', 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 hover:border-indigo-300 dark:hover:border-indigo-700 transition cursor-pointer">

                    <div class="flex items-start gap-3">
                        <div class="h-10 w-10 rounded-lg bg-slate-100 dark:bg-slate-700 flex items-center justify-center shrink-0 overflow-hidden">
                            <img v-if="plugin.icon_url" :src="plugin.icon_url" :alt="plugin.name"
                                 class="h-8 w-8 object-contain"
                                 @error="$event.target.style.display='none'" />
                            <PuzzlePieceIcon v-else class="h-5 w-5 text-slate-400" />
                        </div>
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center gap-1.5 flex-wrap">
                                <h3 class="font-semibold text-slate-800 dark:text-slate-100 truncate">{{ plugin.name }}</h3>
                                <BeakerIcon v-if="isBeta(plugin.version)" class="h-3.5 w-3.5 text-amber-500 shrink-0" title="Beta" />
                            </div>
                            <div class="flex items-center gap-2 mt-0.5 flex-wrap">
                                <span :class="categoryColor(plugin.category)"
                                      class="text-xs font-medium px-2 py-0.5 rounded-full">
                                    {{ categories[plugin.category] ?? plugin.category }}
                                </span>
                                <span class="text-xs text-slate-400">v{{ plugin.version }}</span>
                                <span v-if="plugin.price > 0" class="text-xs text-indigo-600 dark:text-indigo-400 font-medium">${{ plugin.price }}/ay</span>
                            </div>
                        </div>
                    </div>

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

                    <div class="flex items-center gap-4 text-xs text-slate-400 dark:text-slate-500">
                        <span class="flex items-center gap-1">
                            <ArrowDownTrayIcon class="h-3.5 w-3.5" />
                            {{ formatDownloads(plugin.downloads ?? 0) }}
                        </span>
                        <span class="flex items-center gap-1">
                            <StarIcon class="h-3.5 w-3.5 text-amber-400" />
                            {{ plugin.rating ? plugin.rating.toFixed(1) : '—' }}
                        </span>
                        <span v-if="plugin.author?.name ?? plugin.author" class="truncate">
                            {{ plugin.author?.name ?? plugin.author }}
                        </span>
                    </div>

                    <div class="pt-1 border-t border-slate-100 dark:border-slate-700">
                        <div v-if="plugin.installed" class="flex items-center justify-between gap-2">
                            <span class="flex items-center gap-1 text-xs text-green-600 dark:text-green-400 font-medium">
                                <CheckBadgeSolid class="h-4 w-4" />
                                Kurulu (v{{ plugin.installed_version }})
                            </span>
                            <span class="text-xs text-slate-400">Detay →</span>
                        </div>
                        <button v-else
                                @click="installPlugin(plugin.slug, $event)"
                                :disabled="installing === plugin.slug"
                                class="w-full rounded-lg bg-indigo-600 hover:bg-indigo-700 disabled:opacity-60 disabled:cursor-not-allowed py-2 text-sm font-medium text-white transition flex items-center justify-center gap-1.5">
                            <ArrowDownTrayIcon class="h-4 w-4" />
                            {{ installing === plugin.slug ? 'Kuruluyor…' : 'Kur' }}
                        </button>
                    </div>
                </a>
            </div>

            <!-- Empty -->
            <div v-else class="text-center py-16 text-slate-400 dark:text-slate-500">
                <ExclamationTriangleIcon class="mx-auto h-10 w-10 mb-3" />
                <p class="text-sm">Arama kriterlerine uygun plugin bulunamadı.</p>
            </div>

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