<script setup>
import { computed, ref, watch } from 'vue'
import { useForm } from '@inertiajs/vue3'
import { XMarkIcon, LockClosedIcon, UserIcon, UserGroupIcon, GlobeAltIcon } from '@heroicons/vue/24/outline'

/**
 * cPanel-grade chmod modal:
 *   3x3 matrix: rwx for user/group/public
 *   Octal text input + symbolic preview (rwxr-xr-x)
 *   Recursive checkbox
 *
 * Props:
 *   - show           v-model:show
 *   - paths          array of relative paths
 *   - initial-mode   '0644' or '644'
 *
 * Emits:
 *   - update:show
 *   - applied (on success)
 */
const props = defineProps({
    show: Boolean,
    paths: { type: Array, default: () => [] },
    initialMode: { type: String, default: '0644' },
})

const emit = defineEmits(['update:show', 'applied'])

const form = useForm({
    paths: [],
    mode: '0644',
    recursive: false,
})

// keep form in sync when modal opens with new targets
watch(() => props.show, (visible) => {
    if (!visible) return
    form.paths = [...props.paths]
    form.mode = normalizeMode(props.initialMode)
    form.recursive = false
    form.clearErrors()
})

function normalizeMode(m) {
    const s = String(m || '0644').replace(/^0/, '').padStart(3, '0')
    return s.match(/^[0-7]{3}$/) ? '0' + s : '0644'
}

// matrix state derived from octal
const bits = computed({
    get() {
        const digits = form.mode.replace(/^0/, '').padStart(3, '0').split('').map(Number)
        return {
            user: bitsOf(digits[0]),
            group: bitsOf(digits[1]),
            public: bitsOf(digits[2]),
        }
    },
    set() { /* handled by toggleBit */ },
})

function bitsOf(n) {
    return {
        r: !!(n & 4),
        w: !!(n & 2),
        x: !!(n & 1),
    }
}

function numFrom(b) {
    return (b.r ? 4 : 0) + (b.w ? 2 : 0) + (b.x ? 1 : 0)
}

function toggleBit(level, bit) {
    const b = { ...bits.value }
    b[level] = { ...b[level], [bit]: !b[level][bit] }
    const oct = `${numFrom(b.user)}${numFrom(b.group)}${numFrom(b.public)}`
    form.mode = '0' + oct
}

const symbolic = computed(() => {
    const fmt = (lvl) => `${lvl.r ? 'r' : '-'}${lvl.w ? 'w' : '-'}${lvl.x ? 'x' : '-'}`
    return fmt(bits.value.user) + fmt(bits.value.group) + fmt(bits.value.public)
})

const octalDisplay = computed(() => form.mode.replace(/^0?/, '0').padStart(4, '0').slice(-4))

const submit = () => {
    form.post(route('customer.files.chmod'), {
        preserveScroll: true,
        onSuccess: () => {
            emit('applied')
            emit('update:show', false)
        },
    })
}

// Quick presets
const presets = [
    { label: '0644 (rw-r--r--)', value: '0644', desc: 'Standart dosya' },
    { label: '0755 (rwxr-xr-x)', value: '0755', desc: 'Çalıştırılabilir / klasör' },
    { label: '0600 (rw-------)', value: '0600', desc: 'Gizli dosya (.env)' },
    { label: '0700 (rwx------)', value: '0700', desc: 'Özel klasör' },
    { label: '0777 (rwxrwxrwx)', value: '0777', desc: 'Tam erişim (önerilmez!)' },
]
</script>

<template>
    <Teleport to="body">
        <div v-if="show"
             class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 p-4"
             @click.self="emit('update:show', false)">
            <div class="w-full max-w-lg rounded-xl bg-white p-6 shadow-2xl dark:bg-slate-800">
                <!-- Header -->
                <div class="mb-4 flex items-start justify-between">
                    <div>
                        <h3 class="flex items-center gap-2 text-lg font-semibold text-slate-900 dark:text-slate-100">
                            <LockClosedIcon class="h-5 w-5 text-indigo-500" />
                            İzinleri Değiştir
                        </h3>
                        <p class="mt-1 text-xs text-slate-500 dark:text-slate-400">
                            {{ paths.length === 1 ? paths[0] : `${paths.length} öğe seçili` }}
                        </p>
                    </div>
                    <button @click="emit('update:show', false)" class="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-700 dark:hover:bg-slate-700">
                        <XMarkIcon class="h-5 w-5" />
                    </button>
                </div>

                <form @submit.prevent="submit" class="space-y-5">
                    <!-- 3×3 matrix -->
                    <div class="overflow-hidden rounded-lg border border-slate-200 dark:border-slate-700">
                        <table class="min-w-full text-center text-sm">
                            <thead class="bg-slate-50 dark:bg-slate-700/50">
                                <tr class="text-xs uppercase text-slate-500 dark:text-slate-400">
                                    <th class="px-3 py-2 text-left">Düzey</th>
                                    <th class="px-3 py-2">Oku (r)</th>
                                    <th class="px-3 py-2">Yaz (w)</th>
                                    <th class="px-3 py-2">Çalıştır (x)</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 dark:divide-slate-700">
                                <tr v-for="(label, level) in { user: 'Sahip', group: 'Grup', public: 'Herkes' }" :key="level">
                                    <td class="px-3 py-2 text-left font-medium text-slate-700 dark:text-slate-200">
                                        <div class="flex items-center gap-2">
                                            <UserIcon v-if="level === 'user'" class="h-4 w-4 text-indigo-500" />
                                            <UserGroupIcon v-else-if="level === 'group'" class="h-4 w-4 text-cyan-500" />
                                            <GlobeAltIcon v-else class="h-4 w-4 text-amber-500" />
                                            {{ label }}
                                        </div>
                                    </td>
                                    <td class="px-3 py-2">
                                        <input type="checkbox" :checked="bits[level].r" @change="toggleBit(level, 'r')"
                                               class="h-4 w-4 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500" />
                                    </td>
                                    <td class="px-3 py-2">
                                        <input type="checkbox" :checked="bits[level].w" @change="toggleBit(level, 'w')"
                                               class="h-4 w-4 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500" />
                                    </td>
                                    <td class="px-3 py-2">
                                        <input type="checkbox" :checked="bits[level].x" @change="toggleBit(level, 'x')"
                                               class="h-4 w-4 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500" />
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- Octal + symbolic -->
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-xs font-medium uppercase text-slate-500 dark:text-slate-400">Oktal</label>
                            <input
                                v-model="form.mode"
                                type="text"
                                maxlength="4"
                                pattern="0?[0-7]{3}"
                                class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-center text-sm dark:border-slate-600 dark:bg-slate-700 dark:text-slate-100"
                            />
                        </div>
                        <div>
                            <label class="block text-xs font-medium uppercase text-slate-500 dark:text-slate-400">Simgesel</label>
                            <div class="mt-1 rounded-lg bg-slate-100 px-3 py-2 text-center font-mono text-sm text-slate-700 dark:bg-slate-700 dark:text-slate-200">
                                {{ symbolic }}
                            </div>
                        </div>
                    </div>

                    <!-- Quick presets -->
                    <div>
                        <label class="mb-1 block text-xs font-medium uppercase text-slate-500 dark:text-slate-400">Hızlı Şablonlar</label>
                        <div class="flex flex-wrap gap-1.5">
                            <button v-for="p in presets" :key="p.value"
                                    type="button"
                                    @click="form.mode = p.value"
                                    :title="p.desc"
                                    class="rounded-md border px-2 py-1 font-mono text-xs transition-colors"
                                    :class="form.mode === p.value
                                        ? 'border-indigo-500 bg-indigo-50 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300'
                                        : 'border-slate-200 bg-white text-slate-700 hover:border-indigo-300 dark:border-slate-600 dark:bg-slate-700 dark:text-slate-200'">
                                {{ p.value }}
                            </button>
                        </div>
                    </div>

                    <!-- Recursive -->
                    <label class="flex items-center gap-2 text-sm text-slate-700 dark:text-slate-200 cursor-pointer">
                        <input type="checkbox" v-model="form.recursive" class="rounded border-slate-300 text-indigo-600" />
                        <span>Özyinelemeli (klasör içeriğine de uygula)</span>
                    </label>

                    <p v-if="form.errors.mode" class="text-xs text-red-600">{{ form.errors.mode }}</p>

                    <!-- Actions -->
                    <div class="flex justify-end gap-2 border-t border-slate-100 pt-4 dark:border-slate-700">
                        <button type="button" @click="emit('update:show', false)"
                                class="rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 dark:border-slate-600 dark:bg-slate-700 dark:text-slate-200 dark:hover:bg-slate-600">
                            İptal
                        </button>
                        <button type="submit" :disabled="form.processing"
                                class="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50">
                            Uygula
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </Teleport>
</template>
