<script setup>
import { Head, Link, router, useForm } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { ArrowLeftIcon, CpuChipIcon, TrashIcon, ExclamationTriangleIcon } from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    package: Object,
    accounts_count: { type: Number, default: 0 },
})

const PHP_VERSION_CHOICES = ['7.4', '8.0', '8.1', '8.2', '8.3']

const form = useForm({
    name:               props.package.name,
    slug:               props.package.slug,
    description:        props.package.description ?? '',
    price_monthly_usd:  props.package.price_monthly_usd ?? null,
    price_yearly_usd:   props.package.price_yearly_usd  ?? null,
    is_active:          props.package.is_active,
    sort_order:         props.package.sort_order ?? 0,
    // Resource limits (cgroups v2)
    cpu_limit_percent:      props.package.cpu_limit_percent      ?? 100,
    memory_limit_mb:        props.package.memory_limit_mb        ?? 1024,
    io_read_mbps:           props.package.io_read_mbps           ?? 50,
    io_write_mbps:          props.package.io_write_mbps          ?? 30,
    entry_processes_limit:  props.package.entry_processes_limit  ?? 20,
    nproc_limit:            props.package.nproc_limit            ?? 100,
    // Hosting limits JSON
    limits: {
        disk_mb:              props.package.limits?.disk_mb              ?? null,
        bandwidth_mb_month:   props.package.limits?.bandwidth_mb_month   ?? null,
        domain_count:         props.package.limits?.domain_count         ?? null,
        addon_domain_count:   props.package.limits?.addon_domain_count   ?? null,
        subdomain_count:      props.package.limits?.subdomain_count      ?? null,
        db_count:             props.package.limits?.db_count             ?? null,
        ftp_account_count:    props.package.limits?.ftp_account_count    ?? null,
        email_account_count:  props.package.limits?.email_account_count  ?? null,
        php_versions:         Array.isArray(props.package.limits?.php_versions) ? [...props.package.limits.php_versions] : ['8.2'],
    },
})

const togglePhpVersion = (v) => {
    const arr = form.limits.php_versions
    const idx = arr.indexOf(v)
    if (idx >= 0) arr.splice(idx, 1)
    else arr.push(v)
}

const submit = () => form.put(route('admin.packages.update', props.package.id))

const destroy = async () => {
    if (props.accounts_count > 0) return
    const ok = await ask({
        title: 'Paketi sil',
        message: `"${props.package.name}" paketini silmek istediğinizden emin misiniz? Bu işlem geri alınamaz.`,
        variant: 'danger',
        confirmText: 'Evet, sil',
        cancelText: 'İptal',
    })
    if (! ok) return
    router.delete(route('admin.packages.destroy', props.package.id))
}
</script>

<template>
    <Head :title="`Paket: ${package.name}`" />

    <AdminLayout>
        <template #header>
            <Link :href="route('admin.packages.index')" class="mr-2 inline-flex items-center text-slate-500 hover:text-slate-700">
                <ArrowLeftIcon class="h-5 w-5" />
            </Link>
            Paket Düzenle: {{ package.name }}
        </template>

        <form @submit.prevent="submit" class="mx-auto max-w-3xl space-y-6">
            <!-- Temel Bilgiler -->
            <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
                <h3 class="mb-4 text-base font-semibold text-slate-900">Temel Bilgiler</h3>
                <div class="grid grid-cols-1 gap-5 sm:grid-cols-2">
                    <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-slate-700">İsim <span class="text-red-500">*</span></label>
                        <input
                            v-model="form.name"
                            type="text" maxlength="100"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                        />
                        <p v-if="form.errors.name" class="mt-1 text-xs text-red-600">{{ form.errors.name }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-slate-700">Slug <span class="text-red-500">*</span></label>
                        <input
                            v-model="form.slug"
                            type="text" maxlength="100"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                        />
                        <p v-if="form.errors.slug" class="mt-1 text-xs text-red-600">{{ form.errors.slug }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-slate-700">Sıra</label>
                        <input
                            v-model.number="form.sort_order"
                            type="number" min="0"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                        />
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-slate-700">Açıklama</label>
                        <textarea
                            v-model="form.description"
                            rows="2" maxlength="500"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                        ></textarea>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-slate-700">Aylık Fiyat (USD)</label>
                        <input
                            v-model.number="form.price_monthly_usd"
                            type="number" min="0" step="0.01"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                        />
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-slate-700">Yıllık Fiyat (USD)</label>
                        <input
                            v-model.number="form.price_yearly_usd"
                            type="number" min="0" step="0.01"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                        />
                    </div>

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

            <!-- cgroups v2 Resource Limits -->
            <div class="rounded-xl border border-indigo-200 bg-white p-6 shadow-sm">
                <div class="mb-4 flex items-center gap-2">
                    <CpuChipIcon class="h-5 w-5 text-indigo-600" />
                    <h3 class="text-base font-semibold text-slate-900">Kaynak Limitleri (cgroups v2)</h3>
                </div>
                <p class="mb-4 text-xs text-slate-500">Bu limitler Linux systemd slice üzerinden uygulanır. Her hesabın CPU, RAM ve IO tüketimini sınırlar.</p>

                <div class="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">
                    <div>
                        <label class="block text-sm font-medium text-slate-700">CPU Limit (%)</label>
                        <input
                            v-model.number="form.cpu_limit_percent"
                            type="number" min="10" max="1000"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                        />
                        <p class="mt-0.5 text-xs text-slate-400">100 = 1 çekirdek, 200 = 2 çekirdek</p>
                        <p v-if="form.errors.cpu_limit_percent" class="mt-1 text-xs text-red-600">{{ form.errors.cpu_limit_percent }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-slate-700">Bellek Limiti (MB)</label>
                        <input
                            v-model.number="form.memory_limit_mb"
                            type="number" min="128" max="65536"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                        />
                        <p v-if="form.errors.memory_limit_mb" class="mt-1 text-xs text-red-600">{{ form.errors.memory_limit_mb }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-slate-700">IO Okuma (MB/s)</label>
                        <input
                            v-model.number="form.io_read_mbps"
                            type="number" min="10" max="10000"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                        />
                        <p v-if="form.errors.io_read_mbps" class="mt-1 text-xs text-red-600">{{ form.errors.io_read_mbps }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-slate-700">IO Yazma (MB/s)</label>
                        <input
                            v-model.number="form.io_write_mbps"
                            type="number" min="10" max="10000"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                        />
                        <p v-if="form.errors.io_write_mbps" class="mt-1 text-xs text-red-600">{{ form.errors.io_write_mbps }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-slate-700">Giriş Süreci Limiti (EP)</label>
                        <input
                            v-model.number="form.entry_processes_limit"
                            type="number" min="5" max="500"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                        />
                        <p v-if="form.errors.entry_processes_limit" class="mt-1 text-xs text-red-600">{{ form.errors.entry_processes_limit }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-slate-700">Max Süreç (nProc)</label>
                        <input
                            v-model.number="form.nproc_limit"
                            type="number" min="20" max="2000"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                        />
                        <p v-if="form.errors.nproc_limit" class="mt-1 text-xs text-red-600">{{ form.errors.nproc_limit }}</p>
                    </div>
                </div>
            </div>

            <!-- Hosting Limitleri -->
            <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
                <h3 class="mb-4 text-base font-semibold text-slate-900">Hosting Limitleri</h3>
                <p class="mb-4 text-xs text-slate-500">Boş bırakılan alanlar sınırsız kabul edilir.</p>

                <div class="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">
                    <div>
                        <label class="block text-sm font-medium text-slate-700">Disk Kotası (MB)</label>
                        <input v-model.number="form.limits.disk_mb" type="number" min="0" placeholder="Sınırsız"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500" />
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700">Bant Genişliği/ay (MB)</label>
                        <input v-model.number="form.limits.bandwidth_mb_month" type="number" min="0" placeholder="Sınırsız"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500" />
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700">Domain Sayısı</label>
                        <input v-model.number="form.limits.domain_count" type="number" min="0" placeholder="Sınırsız"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500" />
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700">Ek Domain</label>
                        <input v-model.number="form.limits.addon_domain_count" type="number" min="0" placeholder="Sınırsız"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500" />
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700">Alt Domain</label>
                        <input v-model.number="form.limits.subdomain_count" type="number" min="0" placeholder="Sınırsız"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500" />
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700">MySQL DB</label>
                        <input v-model.number="form.limits.db_count" type="number" min="0" placeholder="Sınırsız"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500" />
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700">FTP Hesap</label>
                        <input v-model.number="form.limits.ftp_account_count" type="number" min="0" placeholder="Sınırsız"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500" />
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700">E-posta Hesap</label>
                        <input v-model.number="form.limits.email_account_count" type="number" min="0" placeholder="Sınırsız"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500" />
                    </div>
                </div>

                <!-- PHP Versiyonları -->
                <div class="mt-6 border-t border-slate-100 pt-5">
                    <label class="block text-sm font-medium text-slate-700">İzin Verilen PHP Versiyonları</label>
                    <p class="mt-0.5 text-xs text-slate-500">Hesap sahibi yalnızca seçili versiyonlar arasında geçiş yapabilir.</p>
                    <div class="mt-3 flex flex-wrap gap-2">
                        <label v-for="v in PHP_VERSION_CHOICES" :key="v"
                               class="inline-flex cursor-pointer items-center gap-2 rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-sm font-mono transition hover:border-indigo-400"
                               :class="form.limits.php_versions.includes(v) ? 'border-indigo-500 bg-indigo-50 text-indigo-700' : 'text-slate-600'">
                            <input type="checkbox"
                                   :checked="form.limits.php_versions.includes(v)"
                                   @change="togglePhpVersion(v)"
                                   class="h-3.5 w-3.5 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500" />
                            PHP {{ v }}
                        </label>
                    </div>
                </div>
            </div>

            <!-- Tehlikeli Bölge: Silme -->
            <div class="rounded-xl border border-red-200 bg-red-50/40 p-6 shadow-sm">
                <h3 class="mb-2 text-base font-semibold text-red-700 flex items-center gap-2">
                    <ExclamationTriangleIcon class="h-5 w-5" /> Tehlikeli Bölge
                </h3>
                <div v-if="accounts_count > 0" class="flex items-start gap-3 rounded-lg border border-amber-300 bg-amber-50 p-3 text-sm text-amber-800">
                    <ExclamationTriangleIcon class="h-5 w-5 shrink-0 text-amber-600" />
                    <div>
                        Bu paket <strong>{{ accounts_count }}</strong> hesap tarafından kullanılıyor.
                        Silmeden önce ilgili hesapları başka bir pakete taşıyın.
                    </div>
                </div>
                <div v-else class="flex flex-wrap items-center justify-between gap-3">
                    <p class="text-sm text-slate-600">Paket hiçbir hesap tarafından kullanılmıyor — güvenle silinebilir.</p>
                    <button type="button" @click="destroy"
                            class="inline-flex items-center gap-2 rounded-lg border border-red-300 bg-white px-4 py-2 text-sm font-medium text-red-700 shadow-sm hover:bg-red-100">
                        <TrashIcon class="h-4 w-4" /> Paketi Sil
                    </button>
                </div>
            </div>

            <!-- Actions -->
            <div class="flex justify-end gap-3">
                <Link
                    :href="route('admin.packages.index')"
                    class="rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
                >
                    İptal
                </Link>
                <button
                    type="submit"
                    :disabled="form.processing"
                    class="rounded-lg bg-indigo-600 px-5 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50"
                >
                    Güncelle
                </button>
            </div>
        </form>
    </AdminLayout>
</template>
