<script setup>
import { ref, computed } from 'vue'
import { Head, Link, useForm } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    Cog6ToothIcon, CheckCircleIcon, InformationCircleIcon,
    ServerStackIcon, UsersIcon, ShieldCheckIcon,
    GlobeAltIcon, CodeBracketIcon, CircleStackIcon, CloudArrowDownIcon,
    EnvelopeIcon, DocumentTextIcon, MagnifyingGlassIcon,
    ArrowRightIcon, SparklesIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    grouped: Object,
    group_labels: Object,
    group_icons: Object,
    group_descriptions: { type: Object, default: () => ({}) },
    related_pages: { type: Object, default: () => ({}) },
})

const icons = {
    ServerStackIcon, UsersIcon, ShieldCheckIcon,
    GlobeAltIcon, CodeBracketIcon, CircleStackIcon, CloudArrowDownIcon,
    EnvelopeIcon, DocumentTextIcon, Cog6ToothIcon,
}

const activeGroup = ref(Object.keys(props.grouped)[0])
const search = ref('')

const buildPayload = () => {
    const all = {}
    for (const group of Object.values(props.grouped)) {
        for (const s of group) {
            all[s.key] = s.value
        }
    }
    return all
}

const form = useForm({ settings: buildPayload() })

const submit = () => form.patch(route('admin.settings.update'), {
    preserveScroll: true,
    preserveState: true,
})

const filteredGroup = computed(() => {
    const items = props.grouped[activeGroup.value] || []
    if (!search.value) return items
    const q = search.value.toLowerCase()
    return items.filter((s) =>
        s.key.toLowerCase().includes(q) ||
        s.label.toLowerCase().includes(q) ||
        (s.description || '').toLowerCase().includes(q),
    )
})

const changedCount = computed(() => {
    let count = 0
    for (const group of Object.values(props.grouped)) {
        for (const s of group) {
            if (form.settings[s.key] !== s.value) count++
        }
    }
    return count
})
</script>

<template>
    <Head title="Genel Ayarlar" />
    <AdminLayout>
        <template #header>Genel Ayarlar</template>

        <!-- ─── Info banner ─── -->
        <div class="mb-6 rounded-xl border border-indigo-200 dark:border-indigo-800 bg-indigo-50 dark:bg-indigo-950/30 p-4 flex items-start gap-3">
            <InformationCircleIcon class="h-5 w-5 flex-shrink-0 text-indigo-600 dark:text-indigo-400 mt-0.5" />
            <div class="flex-1 text-sm text-indigo-900 dark:text-indigo-100">
                <strong>Bu sayfada</strong> panel marka adı, hesap default'ları, güvenlik politikaları, yedek schedule, KVKK ayarları gibi
                <strong>genel sunucu ayarları</strong> yönetilir. Web sunucusu, mail, PHP, MySQL gibi servis-özel ayarlar
                kendi dedicated sayfalarında — aşağıdan kısayollarla erişin.
            </div>
        </div>

        <!-- ─── İlgili sayfalar grid ─── -->
        <div class="mb-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
            <Link v-for="(page, key) in related_pages" :key="key" :href="route(page.route)"
                  class="group flex items-center gap-3 rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-4 hover:border-indigo-300 dark:hover:border-indigo-700 hover:shadow-md transition-all">
                <div class="rounded-lg bg-gradient-to-br from-indigo-500 to-purple-600 p-2 shrink-0 shadow">
                    <component :is="icons[page.icon] || Cog6ToothIcon" class="h-4 w-4 text-white" />
                </div>
                <div class="min-w-0 flex-1">
                    <p class="text-sm font-semibold text-slate-900 dark:text-slate-100 truncate">{{ page.title }}</p>
                    <p class="text-xs text-slate-500 dark:text-slate-400 truncate">{{ page.description }}</p>
                </div>
                <ArrowRightIcon class="h-4 w-4 text-slate-400 group-hover:text-indigo-600 group-hover:translate-x-0.5 transition shrink-0" />
            </Link>
        </div>

        <!-- ─── 2-kolon layout: sidebar + ana içerik ─── -->
        <div class="grid grid-cols-1 gap-6 lg:grid-cols-4">
            <!-- Group sidebar -->
            <aside class="lg:col-span-1">
                <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 shadow-sm overflow-hidden">
                    <div class="border-b border-slate-200 dark:border-slate-700 p-3">
                        <div class="relative">
                            <MagnifyingGlassIcon class="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" />
                            <input v-model="search" type="text" placeholder="Ayar ara..."
                                   class="w-full rounded-lg border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-900 py-1.5 pl-8 pr-3 text-xs" />
                        </div>
                    </div>
                    <nav class="p-2 space-y-0.5">
                        <button v-for="(items, group) in grouped" :key="group" @click="activeGroup = group"
                                type="button"
                                :class="['w-full flex items-center gap-2 rounded-lg px-3 py-2 text-left text-sm transition',
                                  activeGroup === group
                                    ? 'bg-indigo-50 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-300 font-semibold ring-1 ring-indigo-100 dark:ring-indigo-800'
                                    : 'text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700']">
                            <component :is="icons[group_icons[group]] || Cog6ToothIcon" class="h-4 w-4" />
                            <span class="flex-1">{{ group_labels[group] }}</span>
                            <span class="text-[10px] text-slate-400">{{ items.length }}</span>
                        </button>
                    </nav>
                </div>
            </aside>

            <!-- Settings list -->
            <div class="lg:col-span-3">
                <form @submit.prevent="submit">
                    <div class="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 shadow-sm overflow-hidden">
                        <!-- Group header -->
                        <div class="border-b border-slate-200 dark:border-slate-700 px-5 py-4 flex items-start justify-between">
                            <div>
                                <h3 class="flex items-center gap-2 text-base font-semibold text-slate-900 dark:text-slate-100">
                                    <component :is="icons[group_icons[activeGroup]] || Cog6ToothIcon" class="h-5 w-5 text-indigo-500" />
                                    {{ group_labels[activeGroup] }}
                                </h3>
                                <p v-if="group_descriptions[activeGroup]" class="mt-1 text-xs text-slate-500 dark:text-slate-400">
                                    {{ group_descriptions[activeGroup] }}
                                </p>
                            </div>
                            <span class="text-xs text-slate-500">{{ filteredGroup.length }} ayar</span>
                        </div>

                        <!-- Settings -->
                        <div class="divide-y divide-slate-100 dark:divide-slate-700">
                            <div v-for="s in filteredGroup" :key="s.key" class="grid grid-cols-1 gap-4 px-5 py-4 md:grid-cols-3 items-start">
                                <div>
                                    <div class="font-medium text-sm text-slate-900 dark:text-slate-100">{{ s.label }}</div>
                                    <code class="font-mono text-[10px] text-slate-400">{{ s.key }}</code>
                                    <p v-if="s.description" class="mt-1 text-xs text-slate-500 dark:text-slate-400">{{ s.description }}</p>
                                </div>
                                <div class="md:col-span-2">
                                    <!-- bool -->
                                    <label v-if="s.type === 'bool'" class="inline-flex cursor-pointer items-center gap-2">
                                        <button type="button" @click="form.settings[s.key] = !form.settings[s.key]"
                                                :class="['relative inline-flex h-6 w-11 items-center rounded-full transition', form.settings[s.key] ? 'bg-indigo-600' : 'bg-slate-300 dark:bg-slate-600']">
                                            <span :class="['inline-block h-4 w-4 transform rounded-full bg-white transition', form.settings[s.key] ? 'translate-x-6' : 'translate-x-1']"></span>
                                        </button>
                                        <span class="text-xs text-slate-600 dark:text-slate-300">{{ form.settings[s.key] ? 'Açık' : 'Kapalı' }}</span>
                                    </label>

                                    <!-- select -->
                                    <select v-else-if="s.type === 'select'" v-model="form.settings[s.key]"
                                            class="w-full rounded-lg border border-slate-300 dark:border-slate-600 dark:bg-slate-900 px-3 py-2 text-sm">
                                        <option v-for="(label, val) in s.options" :key="val" :value="val">{{ label }}</option>
                                    </select>

                                    <!-- int -->
                                    <input v-else-if="s.type === 'int'" v-model.number="form.settings[s.key]" type="number"
                                           class="w-32 rounded-lg border border-slate-300 dark:border-slate-600 dark:bg-slate-900 px-3 py-2 font-mono text-sm" />

                                    <!-- string (default) -->
                                    <input v-else v-model="form.settings[s.key]" type="text"
                                           class="w-full rounded-lg border border-slate-300 dark:border-slate-600 dark:bg-slate-900 px-3 py-2 text-sm" />

                                    <span v-if="form.settings[s.key] !== s.value"
                                          class="ml-2 inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wider text-amber-600 dark:text-amber-400">
                                        <SparklesIcon class="h-3 w-3" />
                                        Değişti
                                    </span>
                                </div>
                            </div>

                            <div v-if="filteredGroup.length === 0" class="px-5 py-12 text-center text-sm text-slate-500">
                                Aramayla eşleşen ayar bulunamadı.
                            </div>
                        </div>
                    </div>

                    <!-- Sticky save bar -->
                    <div class="sticky bottom-4 z-10 mt-4 flex justify-between items-center rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-3 shadow-lg">
                        <div class="text-sm">
                            <span v-if="changedCount > 0" class="text-amber-700 dark:text-amber-400 font-medium flex items-center gap-1.5">
                                <SparklesIcon class="h-4 w-4" />
                                {{ changedCount }} ayar değiştirildi
                            </span>
                            <span v-else class="text-slate-500 dark:text-slate-400">Tüm ayarlar güncel</span>
                        </div>
                        <button type="submit" :disabled="form.processing || changedCount === 0"
                                class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-6 py-2 text-sm font-semibold text-white hover:bg-indigo-700 disabled:opacity-50">
                            <CheckCircleIcon class="h-5 w-5" />
                            {{ form.processing ? 'Kaydediliyor...' : 'Değişiklikleri Kaydet' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </AdminLayout>
</template>
