<script setup>
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { useForm, Link } from '@inertiajs/vue3'
import { ref, computed, watch } from 'vue'
import { ChevronLeftIcon, PlusIcon, PencilIcon, TrashIcon, XMarkIcon } from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    reseller: Object,
    subPackages: Array,
    packages: Array,
})

const showModal  = ref(false)
const editTarget = ref(null)

const form = useForm({
    parent_package_id:  '',
    name:               '',
    slug:               '',
    limits:             {},
    reseller_price_try: '',
    is_active:          true,
    display_order:      0,
})

const parentPackage = computed(() => props.packages.find(p => p.id === Number(form.parent_package_id)))
const parentLimits  = computed(() => parentPackage.value?.limits || {})
const limitKeys     = computed(() => Object.keys(parentLimits.value))

watch(() => form.parent_package_id, () => {
    if (!editTarget.value) form.limits = { ...parentLimits.value }
})

function openCreate() {
    editTarget.value = null
    form.reset()
    form.limits = {}
    showModal.value = true
}

function openEdit(sp) {
    editTarget.value = sp
    form.parent_package_id  = sp.parent_package_id
    form.name               = sp.name
    form.slug               = sp.slug
    form.limits             = { ...sp.limits }
    form.reseller_price_try = sp.reseller_price_try ?? ''
    form.is_active          = sp.is_active
    form.display_order      = sp.display_order
    showModal.value = true
}

function submit() {
    if (editTarget.value) {
        form.patch(route('admin.resellers.sub-packages.update', [props.reseller.id, editTarget.value.id]), {
            onSuccess: () => { showModal.value = false },
        })
    } else {
        form.post(route('admin.resellers.sub-packages.store', props.reseller.id), {
            onSuccess: () => { showModal.value = false },
        })
    }
}

async function destroy(sp) {
    const ok = await ask({
        title: 'Onaylayın',
        message: `"${sp.name}" alt-paketini silmek istediğinize emin misiniz?`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    useForm({}).delete(route('admin.resellers.sub-packages.destroy', [props.reseller.id, sp.id]))
}
</script>

<template>
    <AdminLayout>
        <template #header>Alt-Paketler — {{ reseller.name }}</template>

        <div class="mb-4 flex items-center justify-between">
            <Link
                :href="route('admin.resellers.show', reseller.id)"
                class="inline-flex items-center gap-1 text-sm text-slate-500 hover:text-slate-700 dark:hover:text-slate-300"
            >
                <ChevronLeftIcon class="h-4 w-4" /> Bayiye Dön
            </Link>
            <button
                @click="openCreate"
                class="flex items-center gap-2 rounded-lg bg-rose-600 px-4 py-2 text-sm font-medium text-white hover:bg-rose-700"
            >
                <PlusIcon class="h-4 w-4" /> Yeni Alt-Paket
            </button>
        </div>

        <div class="rounded-xl border border-slate-200 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
            <div v-if="subPackages.length === 0" class="py-12 text-center text-sm text-slate-400">
                Henüz alt-paket yok.
            </div>
            <table v-else class="w-full text-sm">
                <thead>
                    <tr class="text-left text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 border-b border-slate-200 dark:border-slate-700">
                        <th class="px-5 py-3">Ad</th>
                        <th class="px-5 py-3 hidden sm:table-cell">Üst Paket</th>
                        <th class="px-5 py-3 hidden md:table-cell">Fiyat</th>
                        <th class="px-5 py-3">Durum</th>
                        <th class="px-5 py-3 text-right">İşlem</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                    <tr v-for="sp in subPackages" :key="sp.id" class="hover:bg-slate-50 dark:hover:bg-slate-800/50">
                        <td class="px-5 py-3">
                            <div class="font-medium text-slate-900 dark:text-slate-100">{{ sp.name }}</div>
                            <div class="text-xs font-mono text-slate-400">{{ sp.slug }}</div>
                        </td>
                        <td class="px-5 py-3 hidden sm:table-cell text-slate-600 dark:text-slate-400">{{ sp.parent_package_name }}</td>
                        <td class="px-5 py-3 hidden md:table-cell text-slate-600 dark:text-slate-400">
                            {{ sp.reseller_price_try ? '₺' + sp.reseller_price_try : '—' }}
                        </td>
                        <td class="px-5 py-3">
                            <span :class="['inline-flex rounded-full px-2 py-0.5 text-xs font-medium', sp.is_active ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-500']">
                                {{ sp.is_active ? 'Aktif' : 'Pasif' }}
                            </span>
                        </td>
                        <td class="px-5 py-3 text-right">
                            <button @click="openEdit(sp)" class="mr-2 text-slate-400 hover:text-blue-600">
                                <PencilIcon class="h-4 w-4" />
                            </button>
                            <button @click="destroy(sp)" class="text-slate-400 hover:text-red-600">
                                <TrashIcon class="h-4 w-4" />
                            </button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- Modal -->
        <div v-if="showModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50" @click.self="showModal = false">
            <div class="w-full max-w-lg rounded-xl bg-white shadow-xl dark:bg-slate-900 mx-4 max-h-[90vh] overflow-y-auto">
                <div class="flex items-center justify-between border-b border-slate-200 px-6 py-4 dark:border-slate-700">
                    <h3 class="font-semibold text-slate-900 dark:text-slate-100">
                        {{ editTarget ? 'Alt-Paketi Düzenle' : 'Yeni Alt-Paket' }}
                    </h3>
                    <button @click="showModal = false" class="text-slate-400 hover:text-slate-600">
                        <XMarkIcon class="h-5 w-5" />
                    </button>
                </div>

                <form @submit.prevent="submit" class="p-6 space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Üst Paket</label>
                        <select v-model="form.parent_package_id"
                            class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-800 dark:text-slate-200"
                            :disabled="!!editTarget" required>
                            <option value="">Seçin…</option>
                            <option v-for="pkg in packages" :key="pkg.id" :value="pkg.id">{{ pkg.name }}</option>
                        </select>
                    </div>

                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Ad</label>
                            <input v-model="form.name" type="text" required
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-800 dark:text-slate-200" />
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Slug</label>
                            <input v-model="form.slug" type="text"
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-800 dark:text-slate-200" />
                        </div>
                    </div>

                    <div v-if="limitKeys.length > 0">
                        <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Limitler (≤ üst paket)</label>
                        <div class="space-y-2 rounded-lg border border-slate-200 p-3 dark:border-slate-700">
                            <div v-for="key in limitKeys" :key="key" class="flex items-center gap-3 text-sm">
                                <span class="w-36 text-xs font-mono text-slate-500">{{ key }}</span>
                                <input v-model="form.limits[key]" type="number" min="0" :placeholder="parentLimits[key] ?? '∞'"
                                    class="flex-1 rounded border border-slate-300 px-2 py-1 text-sm dark:border-slate-600 dark:bg-slate-800" />
                                <span class="text-xs text-slate-400 w-16 text-right">max: {{ parentLimits[key] ?? '∞' }}</span>
                            </div>
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Fiyat (TRY)</label>
                            <input v-model="form.reseller_price_try" type="number" step="0.01" min="0"
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-800" />
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Sıra</label>
                            <input v-model="form.display_order" type="number" min="0"
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-800" />
                        </div>
                    </div>

                    <div class="flex items-center gap-2">
                        <input v-model="form.is_active" type="checkbox" id="sp_active" class="h-4 w-4 rounded border-slate-300" />
                        <label for="sp_active" class="text-sm text-slate-700 dark:text-slate-300">Aktif</label>
                    </div>

                    <div class="flex justify-end gap-3 pt-2">
                        <button type="button" @click="showModal = false"
                            class="rounded-lg border border-slate-300 px-4 py-2 text-sm hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800">
                            Vazgeç
                        </button>
                        <button type="submit" :disabled="form.processing"
                            class="rounded-lg bg-rose-600 px-4 py-2 text-sm font-medium text-white hover:bg-rose-700 disabled:opacity-60">
                            {{ editTarget ? 'Güncelle' : 'Oluştur' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </AdminLayout>
</template>
