<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { Head, useForm, router, usePage } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Shield, ShieldAlert, Plus, Trash2, Save, Check, AlertCircle, Lock, Edit3, Search, Key } from 'lucide-vue-next';

interface Role {
    id: number;
    name: string;
    permissions: string[];
    is_system: boolean;
}

interface Permission {
    id: number;
    name: string;
    category: string;
    is_system?: boolean;
}

const props = defineProps<{
    roles: Role[];
    permissions: Permission[];
}>();

// Navigation Tabs
const currentTab = ref<'roles' | 'permissions'>('roles');

// Permissions Search & Filter
const permissionSearch = ref('');

const filteredPermissions = computed(() => {
    const search = permissionSearch.value.toLowerCase().trim();
    if (!search) return props.permissions;
    return props.permissions.filter(p => 
        p.name.toLowerCase().includes(search) || 
        p.category.toLowerCase().includes(search)
    );
});

// Helper: Get roles containing a permission
const getRolesForPermission = (permissionName: string) => {
    return props.roles.filter(role => role.permissions.includes(permissionName));
};

// Selected role state
const activeRoleId = ref<number>(props.roles[0]?.id || 0);

const activeRole = computed(() => {
    return props.roles.find(r => r.id === activeRoleId.value) || null;
});

// Permission groupings
const permissionsByCategory = computed(() => {
    const groups: Record<string, Permission[]> = {};
    props.permissions.forEach(p => {
        if (!groups[p.category]) {
            groups[p.category] = [];
        }
        groups[p.category].push(p);
    });
    return groups;
});

// Edit states for Roles
const isCreatingRole = ref(false);
const isDeletingRole = ref(false);

const newRoleForm = useForm({
    name: '',
});

const editPermissionsForm = useForm({
    name: '',
    permissions: [] as string[],
});

// Edit states for Permissions
const isCreatingPermission = ref(false);
const isEditingPermission = ref(false);
const isDeletingPermission = ref(false);
const permissionToEdit = ref<Permission | null>(null);
const permissionToDelete = ref<Permission | null>(null);

const newPermissionForm = useForm({
    name: '',
});

const editPermissionForm = useForm({
    name: '',
});

const page = usePage<any>();

// Initialize form when active role changes
watch(activeRole, (newRole) => {
    if (newRole) {
        editPermissionsForm.name = newRole.name;
        editPermissionsForm.permissions = [...newRole.permissions];
        editPermissionsForm.clearErrors();
    }
}, { immediate: true });

const selectRole = (id: number) => {
    activeRoleId.value = id;
};

const createRole = () => {
    newRoleForm.post(route('rbac.store'), {
        onSuccess: () => {
            isCreatingRole.value = false;
            newRoleForm.reset();
            // Select the newly created role
            if (props.roles.length > 0) {
                const latestRole = props.roles[props.roles.length - 1];
                if (latestRole) {
                    activeRoleId.value = latestRole.id;
                }
            }
        },
    });
};

const saveRoleSettings = () => {
    if (!activeRole.value) return;
    editPermissionsForm.put(route('rbac.update', activeRole.value.id), {
        onSuccess: () => {
            editPermissionsForm.defaults();
        },
    });
};

const deleteRole = () => {
    if (!activeRole.value) return;
    router.delete(route('rbac.destroy', activeRole.value.id), {
        onSuccess: () => {
            isDeletingRole.value = false;
            if (props.roles.length > 0) {
                activeRoleId.value = props.roles[0].id;
            }
        },
    });
};

const togglePermission = (permissionName: string) => {
    if (activeRole.value?.name === 'Super Admin') return; // Read-only for Super Admin
    
    const idx = editPermissionsForm.permissions.indexOf(permissionName);
    if (idx > -1) {
        editPermissionsForm.permissions.splice(idx, 1);
    } else {
        editPermissionsForm.permissions.push(permissionName);
    }
};

const isPermissionSelected = (permissionName: string) => {
    if (activeRole.value?.name === 'Super Admin') return true; // Super Admin has all permissions visually checkmarked
    return editPermissionsForm.permissions.includes(permissionName);
};

// Permission CRUD Actions
const createPermission = () => {
    newPermissionForm.post(route('rbac.permissions.store'), {
        onSuccess: () => {
            isCreatingPermission.value = false;
            newPermissionForm.reset();
        },
    });
};

const openEditPermissionModal = (permission: Permission) => {
    permissionToEdit.value = permission;
    editPermissionForm.name = permission.name;
    editPermissionForm.clearErrors();
    isEditingPermission.value = true;
};

const updatePermission = () => {
    if (!permissionToEdit.value) return;
    editPermissionForm.put(route('rbac.permissions.update', permissionToEdit.value.id), {
        onSuccess: () => {
            isEditingPermission.value = false;
            permissionToEdit.value = null;
            editPermissionForm.reset();
        },
    });
};

const openDeletePermissionModal = (permission: Permission) => {
    permissionToDelete.value = permission;
    isDeletingPermission.value = true;
};

const deletePermission = () => {
    if (!permissionToDelete.value) return;
    router.delete(route('rbac.permissions.destroy', permissionToDelete.value.id), {
        onSuccess: () => {
            isDeletingPermission.value = false;
            permissionToDelete.value = null;
        },
    });
};
</script>

<template>
    <Head title="Roles & Permissions" />

    <AdminLayout>
        <div class="space-y-6">
            <!-- Header Section -->
            <div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                <div>
                    <h1 class="text-2xl font-bold tracking-tight text-slate-900 dark:text-slate-50">Roles & Permissions</h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Configure security access control levels, user groups, and capability guards.
                    </p>
                </div>
            </div>

            <!-- Toast Messages -->
            <div v-if="page.props.flash?.success" class="bg-emerald-50 dark:bg-emerald-950/30 border border-emerald-200 dark:border-emerald-900/50 text-emerald-800 dark:text-emerald-400 rounded-xl p-4 text-sm flex items-center gap-3">
                <Check class="h-5 w-5 text-emerald-600 dark:text-emerald-400 shrink-0" />
                <span>{{ page.props.flash?.success }}</span>
            </div>
            <div v-if="page.props.flash?.error" class="bg-rose-50 dark:bg-rose-950/30 border border-rose-200 dark:border-rose-900/50 text-rose-800 dark:text-rose-400 rounded-xl p-4 text-sm flex items-center gap-3">
                <AlertCircle class="h-5 w-5 text-rose-600 dark:text-rose-400 shrink-0" />
                <span>{{ page.props.flash?.error }}</span>
            </div>

            <!-- Navigation Tabs -->
            <div class="flex border-b border-slate-200 dark:border-slate-800">
                <button
                    @click="currentTab = 'roles'"
                    :class="[
                        'px-4 py-2.5 text-sm font-medium border-b-2 transition-all cursor-pointer focus:outline-none',
                        currentTab === 'roles'
                            ? 'border-red-600 text-red-650 dark:border-red-400 dark:text-red-450 font-semibold'
                            : 'border-transparent text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200'
                    ]"
                >
                    Role Permissions Matrix
                </button>
                <button
                    @click="currentTab = 'permissions'"
                    :class="[
                        'px-4 py-2.5 text-sm font-medium border-b-2 transition-all cursor-pointer focus:outline-none',
                        currentTab === 'permissions'
                            ? 'border-red-600 text-red-650 dark:border-red-400 dark:text-red-450 font-semibold'
                            : 'border-transparent text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200'
                    ]"
                >
                    Permissions Manager
                </button>
            </div>

            <!-- Grid Layout (Roles Tab) -->
            <div v-if="currentTab === 'roles'" class="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start animate-in fade-in duration-200">
                
                <!-- Left Pane: Roles Selector (4 Cols) -->
                <div class="lg:col-span-4 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl p-4 shadow-sm space-y-4">
                    <div class="flex items-center justify-between">
                        <h3 class="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">Security Roles</h3>
                        <button
                            @click="isCreatingRole = true"
                            class="inline-flex items-center gap-1 text-xs font-semibold text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300"
                        >
                            <Plus class="h-3.5 w-3.5" />
                            Add Role
                        </button>
                    </div>

                    <!-- Add Role inline form -->
                    <div v-if="isCreatingRole" class="border border-slate-200 dark:border-slate-800 rounded-lg p-3 bg-slate-50 dark:bg-slate-900/40 animate-in slide-in-from-top-2 duration-200">
                        <form @submit.prevent="createRole" class="space-y-3">
                            <div class="space-y-1">
                                <label for="role-name-input" class="block text-[10px] font-semibold uppercase text-slate-400">Role Name</label>
                                <input
                                    id="role-name-input"
                                    v-model="newRoleForm.name"
                                    type="text"
                                    required
                                    placeholder="e.g. Moderator"
                                    class="w-full px-3 py-1.5 text-xs bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-lg text-slate-950 dark:text-slate-50 placeholder-slate-400 focus:outline-none focus:ring-1 focus:ring-red-500 transition-all"
                                />
                                <span v-if="newRoleForm.errors.name" class="text-[10px] text-red-600 dark:text-red-400 font-medium block">{{ newRoleForm.errors.name }}</span>
                            </div>
                            <div class="flex items-center justify-end gap-2 text-xs">
                                <button
                                    type="button"
                                    @click="isCreatingRole = false"
                                    class="px-2.5 py-1 text-slate-500 hover:text-slate-700 dark:hover:text-slate-300"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    :disabled="newRoleForm.processing"
                                    class="px-2.5 py-1 text-white bg-red-600 hover:bg-red-700 rounded-md font-semibold disabled:opacity-50"
                                >
                                    Create
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- Roles List -->
                    <div class="space-y-1 max-h-[60vh] overflow-y-auto">
                        <button
                            v-for="role in roles"
                            :key="role.id"
                            @click="selectRole(role.id)"
                            :class="[
                                'w-full text-left px-3 py-2.5 rounded-lg flex items-center justify-between border transition-all duration-200',
                                activeRoleId === role.id
                                    ? 'bg-red-50/70 border-red-200 dark:bg-red-950/20 dark:border-red-900/40 text-red-900 dark:text-red-200 font-semibold'
                                    : 'bg-transparent border-transparent hover:bg-slate-50 dark:hover:bg-slate-900/50 text-slate-700 dark:text-slate-350'
                            ]"
                        >
                            <span class="text-sm capitalize flex items-center gap-2">
                                <Shield class="h-4 w-4 shrink-0 text-slate-400" :class="{'text-red-500': activeRoleId === role.id}" />
                                {{ role.name }}
                            </span>
                            <span 
                                v-if="role.is_system"
                                class="text-[9px] font-semibold px-1.5 py-0.5 rounded bg-slate-100 text-slate-500 border border-slate-200/55 dark:bg-slate-900 dark:text-slate-400 dark:border-slate-800"
                            >
                                SYSTEM
                            </span>
                        </button>
                    </div>
                </div>

                <!-- Right Pane: Role Configuration (8 Cols) -->
                <div v-if="activeRole" class="lg:col-span-8 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl p-6 shadow-sm space-y-6">
                    
                    <!-- Role Details Header -->
                    <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between border-b border-slate-200 dark:border-slate-800 pb-4">
                        <div class="space-y-1">
                            <div class="flex items-center gap-2">
                                <h2 class="text-lg font-bold text-slate-900 dark:text-slate-50 capitalize">{{ activeRole.name }} Role</h2>
                                <Lock v-if="activeRole.is_system" class="h-4 w-4 text-slate-400" title="System protected role" />
                            </div>
                            <p class="text-xs text-slate-400 dark:text-slate-500">
                                Set capabilities and permission gates for users belonging to this security level.
                            </p>
                        </div>
                        <div v-if="!activeRole.is_system" class="flex items-center gap-2">
                            <button
                                @click="isDeletingRole = true"
                                class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold border border-red-200 dark:border-red-950 bg-red-50 dark:bg-red-950/20 text-red-600 dark:text-red-400 hover:bg-red-100 dark:hover:bg-red-950/40 transition-colors"
                            >
                                <Trash2 class="h-3.5 w-3.5" />
                                Delete Role
                            </button>
                        </div>
                    </div>

                    <!-- Warnings & Alerts -->
                    <div 
                        v-if="activeRole.name === 'Super Admin'" 
                        class="bg-slate-900 dark:bg-slate-50 text-slate-200 dark:text-slate-900 rounded-xl p-4 border border-slate-800 dark:border-slate-200 text-xs flex gap-3 leading-relaxed"
                    >
                        <ShieldAlert class="h-5 w-5 text-red-500 dark:text-red-600 shrink-0" />
                        <div>
                            <span class="font-bold block mb-0.5">Super Admin Gate Bypass Enabled</span>
                            The Super Admin role inherently bypasses all authorization gate checks. System permissions are fully enabled and cannot be revoked to prevent lockout.
                        </div>
                    </div>

                    <!-- Role Renaming (For custom roles only) -->
                    <div v-if="!activeRole.is_system" class="space-y-2 max-w-sm">
                        <label for="edit-role-name" class="block text-xs font-semibold uppercase text-slate-400">Rename Role</label>
                        <div class="flex items-center gap-2">
                            <div class="relative flex-1">
                                <Edit3 class="absolute left-3 top-2.5 h-4 w-4 text-slate-400" />
                                <input
                                    id="edit-role-name"
                                    v-model="editPermissionsForm.name"
                                    type="text"
                                    required
                                    class="w-full pl-9 pr-4 py-2 text-sm bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-slate-950 dark:text-slate-50 focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent transition-all"
                                />
                            </div>
                        </div>
                        <span v-if="editPermissionsForm.errors.name" class="text-xs text-red-600 dark:text-red-400 font-medium">{{ editPermissionsForm.errors.name }}</span>
                    </div>

                    <!-- Permissions Selection Grid -->
                    <div class="space-y-6">
                        <h3 class="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">Configure Permissions</h3>
                        
                        <div class="space-y-6">
                            <div 
                                v-for="(perms, category) in permissionsByCategory" 
                                :key="category"
                                class="space-y-3"
                            >
                                <span class="text-xs font-bold text-slate-700 dark:text-slate-355 block border-b border-slate-100 dark:border-slate-900 pb-1.5 capitalize font-semibold">
                                    {{ category }} Permissions
                                </span>
                                
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                    <div 
                                        v-for="perm in perms" 
                                        :key="perm.id"
                                        @click="togglePermission(perm.name)"
                                        :class="[
                                            'border rounded-xl p-3.5 flex items-center justify-between select-none transition-all duration-200',
                                            activeRole.name === 'Super Admin' ? 'cursor-not-allowed opacity-80' : 'cursor-pointer',
                                            isPermissionSelected(perm.name)
                                                ? 'bg-red-50/30 border-red-200 dark:bg-red-950/10 dark:border-red-900/30'
                                                : 'bg-white dark:bg-slate-950 border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-900/50'
                                        ]"
                                    >
                                        <div class="space-y-0.5">
                                            <span class="text-sm font-semibold text-slate-900 dark:text-slate-100 capitalize">
                                                {{ perm.name.replace('-', ' ') }}
                                            </span>
                                            <span class="text-[10px] text-slate-400 dark:text-slate-500 block font-mono">
                                                {{ perm.name }}
                                            </span>
                                        </div>
 
                                        <!-- Toggle Indicator Checkbox -->
                                        <div 
                                            :class="[
                                                'h-5 w-5 rounded border flex items-center justify-center transition-all',
                                                isPermissionSelected(perm.name)
                                                    ? 'bg-red-500 border-red-500 text-white'
                                                    : 'border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900'
                                            ]"
                                        >
                                            <Check v-if="isPermissionSelected(perm.name)" class="h-3.5 w-3.5 stroke-[3]" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Save Actions -->
                    <div v-if="activeRole.name !== 'Super Admin'" class="flex justify-end pt-4 border-t border-slate-200 dark:border-slate-800">
                        <button
                            @click="saveRoleSettings"
                            :disabled="editPermissionsForm.processing"
                            class="inline-flex items-center gap-2 px-4 py-2 text-sm font-semibold text-white bg-red-600 hover:bg-red-700 rounded-lg shadow-sm transition-all focus:outline-none focus:ring-2 focus:ring-red-500 disabled:opacity-50"
                        >
                            <Save class="h-4 w-4" />
                            <span v-if="editPermissionsForm.processing">Saving settings...</span>
                            <span v-else>Save Role settings</span>
                        </button>
                    </div>

                </div>
            </div>

        <!-- Permissions Manager Tab View -->
        <div v-else-if="currentTab === 'permissions'" class="space-y-6 animate-in fade-in duration-200">
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl p-6 shadow-sm space-y-6">
                
                <!-- Search and Action Bar -->
                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div class="relative max-w-md w-full">
                        <span class="absolute left-3 top-2.5 text-slate-400">
                            <Search class="h-4.5 w-4.5" />
                        </span>
                        <input
                            v-model="permissionSearch"
                            type="text"
                            placeholder="Search permissions by name or category..."
                            class="w-full pl-9 pr-4 py-2 text-sm bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-slate-950 dark:text-slate-50 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all"
                        />
                    </div>
                    <button
                        @click="isCreatingPermission = true"
                        class="inline-flex items-center justify-center gap-2 px-4 py-2 text-sm font-semibold text-white bg-red-600 hover:bg-red-700 rounded-lg shadow-sm transition-all focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 cursor-pointer whitespace-nowrap"
                    >
                        <Plus class="h-4 w-4" />
                        Add Permission
                    </button>
                </div>

                <!-- Permissions Table -->
                <div class="border border-slate-200 dark:border-slate-800 rounded-xl overflow-hidden bg-white dark:bg-slate-950">
                    <div class="overflow-x-auto">
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="bg-slate-50 dark:bg-slate-900/60 text-xs font-semibold uppercase tracking-wider text-slate-500 border-b border-slate-200 dark:border-slate-800">
                                    <th class="px-6 py-3.5">Permission Name</th>
                                    <th class="px-6 py-3.5">Category</th>
                                    <th class="px-6 py-3.5">Assigned Roles</th>
                                    <th class="px-6 py-3.5">Type</th>
                                    <th class="px-6 py-3.5 text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 dark:divide-slate-900 text-sm">
                                <tr v-if="filteredPermissions.length === 0">
                                    <td colspan="5" class="px-6 py-10 text-center text-slate-500 dark:text-slate-400 italic">
                                        No permissions found.
                                    </td>
                                </tr>
                                <tr 
                                    v-for="perm in filteredPermissions" 
                                    :key="perm.id"
                                    class="hover:bg-slate-50/50 dark:hover:bg-slate-900/20 transition-colors"
                                >
                                    <!-- Name -->
                                    <td class="px-6 py-4 font-semibold text-slate-900 dark:text-slate-100">
                                        <div class="flex items-center gap-2">
                                            <Key class="h-4 w-4 text-slate-400 shrink-0" />
                                            <span>{{ perm.name }}</span>
                                        </div>
                                    </td>
                                    
                                    <!-- Category -->
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-slate-100 dark:bg-slate-900 text-slate-600 dark:text-slate-400 border border-slate-200/40 dark:border-slate-800">
                                            {{ perm.category }}
                                        </span>
                                    </td>
                                    
                                    <!-- Assigned Roles -->
                                    <td class="px-6 py-4">
                                        <div class="flex flex-wrap gap-1.5">
                                            <span v-if="getRolesForPermission(perm.name).length === 0" class="text-xs text-slate-400 italic">None</span>
                                            <span 
                                                v-for="role in getRolesForPermission(perm.name)" 
                                                :key="role.id"
                                                :class="[
                                                    'inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-semibold border',
                                                    role.name === 'Super Admin' || role.name === 'Admin'
                                                        ? 'bg-red-50 text-red-700 border-red-100 dark:bg-red-950/20 dark:text-red-400 dark:border-red-900/40'
                                                        : 'bg-slate-100 text-slate-700 border-slate-200 dark:bg-slate-900 dark:text-slate-350 dark:border-slate-800'
                                                ]"
                                            >
                                                {{ role.name }}
                                            </span>
                                        </div>
                                    </td>
                                    
                                    <!-- Type -->
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span 
                                            v-if="perm.is_system"
                                            class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold bg-slate-100 text-slate-500 border border-slate-200/50 dark:bg-slate-900 dark:text-slate-400 dark:border-slate-800"
                                        >
                                            System Core
                                        </span>
                                        <span 
                                            v-else
                                            class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold bg-emerald-50 text-emerald-700 border border-emerald-100 dark:bg-emerald-950/20 dark:text-emerald-450 dark:border-emerald-900/40"
                                        >
                                            Custom
                                        </span>
                                    </td>
                                    
                                    <!-- Actions -->
                                    <td class="px-6 py-4 whitespace-nowrap text-right">
                                        <div class="flex items-center justify-end gap-2">
                                            <template v-if="perm.is_system">
                                                <Lock class="h-4 w-4 text-slate-400" title="System permissions are locked" />
                                            </template>
                                            <template v-else>
                                                <button
                                                    @click="openEditPermissionModal(perm)"
                                                    class="p-1 rounded-lg text-slate-505 hover:bg-slate-100 dark:hover:bg-slate-900 hover:text-slate-900 dark:hover:text-slate-200 transition-colors cursor-pointer"
                                                    title="Rename Permission"
                                                >
                                                    <Edit3 class="h-3.5 w-3.5" />
                                                </button>
                                                <button
                                                    @click="openDeletePermissionModal(perm)"
                                                    class="p-1 rounded-lg text-slate-400 hover:bg-red-50 dark:hover:bg-red-950/20 hover:text-red-650 transition-colors cursor-pointer"
                                                    title="Delete Permission"
                                                >
                                                    <Trash2 class="h-3.5 w-3.5" />
                                                </button>
                                            </template>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        </div>

        <!-- Delete Role Confirmation Modal -->
        <div 
            v-if="isDeletingRole" 
            class="fixed inset-0 z-50 flex items-center justify-center p-4 animate-fade-in"
        >
            <div 
                @click="isDeletingRole = false"
                class="fixed inset-0 bg-slate-950/60 backdrop-blur-sm"
            />
            
            <div class="relative bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-2xl w-full max-w-md overflow-hidden flex flex-col animate-in zoom-in-95 duration-200">
                <div class="p-6 text-center space-y-4">
                    <div class="mx-auto h-12 w-12 rounded-full bg-red-50 dark:bg-red-905/30 flex items-center justify-center border border-red-100 dark:border-red-900/50 text-red-600 dark:text-red-400">
                        <Trash2 class="h-6 w-6" />
                    </div>
                    <div class="space-y-1">
                        <h3 class="text-base font-bold text-slate-900 dark:text-slate-50">Delete Security Role</h3>
                        <p class="text-sm text-slate-500 dark:text-slate-400 leading-normal">
                            Are you sure you want to delete the security role <span class="font-semibold text-slate-900 dark:text-slate-50 capitalize">{{ activeRole?.name }}</span>? Users currently assigned to this role will lose its permissions.
                        </p>
                    </div>
                </div>

                <div class="px-6 py-4 border-t border-slate-200 dark:border-slate-800 flex justify-end gap-3 bg-slate-50/50 dark:bg-slate-900/50">
                    <button
                        type="button"
                        @click="isDeletingRole = false"
                        class="px-4 py-2 text-sm font-medium text-slate-700 dark:text-slate-350 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-lg hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors"
                    >
                        Cancel
                    </button>
                    <button
                        type="button"
                        @click="deleteRole"
                        class="px-4 py-2 text-sm font-semibold text-white bg-red-600 hover:bg-red-700 rounded-lg shadow-sm transition-all focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
                    >
                        Yes, Delete Role
                    </button>
                </div>
            </div>
        </div>

        <!-- Create Permission Modal -->
        <div 
            v-if="isCreatingPermission" 
            class="fixed inset-0 z-50 flex items-center justify-center p-4 animate-fade-in"
        >
            <div 
                @click="isCreatingPermission = false"
                class="fixed inset-0 bg-slate-950/60 backdrop-blur-sm"
            />
            
            <div class="relative bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-2xl w-full max-w-md overflow-hidden flex flex-col animate-in zoom-in-95 duration-200">
                <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between bg-slate-50/50 dark:bg-slate-900/50">
                    <h3 class="text-base font-semibold text-slate-900 dark:text-slate-50">Add Security Permission</h3>
                    <button 
                        @click="isCreatingPermission = false"
                        class="rounded-lg p-1 text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-900 hover:text-slate-650 cursor-pointer text-xl"
                    >
                        &times;
                    </button>
                </div>

                <form @submit.prevent="createPermission" class="space-y-4 p-6">
                    <div class="space-y-1.5">
                        <label for="perm-name" class="block text-xs font-semibold uppercase tracking-wider text-slate-500">Permission Name</label>
                        <input
                            id="perm-name"
                            v-model="newPermissionForm.name"
                            type="text"
                            required
                            placeholder="e.g. view analytics"
                            class="w-full px-3 py-2 text-sm bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-slate-950 dark:text-slate-50 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all"
                        />
                        <span v-if="newPermissionForm.errors.name" class="text-xs text-red-600 dark:text-red-400 font-medium block mt-1">{{ newPermissionForm.errors.name }}</span>
                    </div>

                    <div class="flex justify-end gap-3 pt-4 border-t border-slate-100 dark:border-slate-900">
                        <button
                            type="button"
                            @click="isCreatingPermission = false"
                            class="px-4 py-2 text-sm font-medium text-slate-700 dark:text-slate-300 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-lg hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors focus:outline-none cursor-pointer"
                        >
                            Cancel
                        </button>
                        <button
                            type="submit"
                            :disabled="newPermissionForm.processing"
                            class="px-4 py-2 text-sm font-semibold text-white bg-red-600 hover:bg-red-700 rounded-lg shadow-sm transition-all focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:ring-offset-2 disabled:opacity-50 cursor-pointer"
                        >
                            Create
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Edit Permission Modal -->
        <div 
            v-if="isEditingPermission" 
            class="fixed inset-0 z-50 flex items-center justify-center p-4 animate-fade-in"
        >
            <div 
                @click="isEditingPermission = false"
                class="fixed inset-0 bg-slate-950/60 backdrop-blur-sm"
            />
            
            <div class="relative bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-2xl w-full max-w-md overflow-hidden flex flex-col animate-in zoom-in-95 duration-200">
                <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between bg-slate-50/50 dark:bg-slate-900/50">
                    <h3 class="text-base font-semibold text-slate-900 dark:text-slate-50">Rename Permission</h3>
                    <button 
                        @click="isEditingPermission = false"
                        class="rounded-lg p-1 text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-900 hover:text-slate-650 cursor-pointer text-xl"
                    >
                        &times;
                    </button>
                </div>

                <form @submit.prevent="updatePermission" class="space-y-4 p-6">
                    <div class="space-y-1.5">
                        <label for="edit-perm-name" class="block text-xs font-semibold uppercase tracking-wider text-slate-500">Permission Name</label>
                        <input
                            id="edit-perm-name"
                            v-model="editPermissionForm.name"
                            type="text"
                            required
                            class="w-full px-3 py-2 text-sm bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-slate-900 dark:text-slate-50 focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all"
                        />
                        <span v-if="editPermissionForm.errors.name" class="text-xs text-red-600 dark:text-red-400 font-medium block mt-1">{{ editPermissionForm.errors.name }}</span>
                    </div>

                    <div class="flex justify-end gap-3 pt-4 border-t border-slate-100 dark:border-slate-900">
                        <button
                            type="button"
                            @click="isEditingPermission = false"
                            class="px-4 py-2 text-sm font-medium text-slate-700 dark:text-slate-350 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-lg hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors focus:outline-none cursor-pointer"
                        >
                            Cancel
                        </button>
                        <button
                            type="submit"
                            :disabled="editPermissionForm.processing"
                            class="px-4 py-2 text-sm font-semibold text-white bg-red-600 hover:bg-red-700 rounded-lg shadow-sm transition-all focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 disabled:opacity-50 cursor-pointer"
                        >
                            Save Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Delete Permission Modal -->
        <div 
            v-if="isDeletingPermission" 
            class="fixed inset-0 z-50 flex items-center justify-center p-4 animate-fade-in"
        >
            <div 
                @click="isDeletingPermission = false"
                class="fixed inset-0 bg-slate-950/60 backdrop-blur-sm"
            />
            
            <div class="relative bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-2xl w-full max-w-md overflow-hidden flex flex-col animate-in zoom-in-95 duration-200">
                <div class="p-6 text-center space-y-4">
                    <div class="mx-auto h-12 w-12 rounded-full bg-red-50 dark:bg-red-905/30 flex items-center justify-center border border-red-100 dark:border-red-900/50 text-red-600 dark:text-red-400">
                        <Trash2 class="h-6 w-6" />
                    </div>
                    <div class="space-y-1">
                        <h3 class="text-base font-bold text-slate-900 dark:text-slate-50">Delete Security Permission</h3>
                        <p class="text-sm text-slate-500 dark:text-slate-400 leading-normal">
                            Are you sure you want to delete the permission <span class="font-semibold text-slate-900 dark:text-slate-50 font-mono">{{ permissionToDelete?.name }}</span>? This will permanently remove it from the system and detach it from all roles.
                        </p>
                    </div>
                </div>

                <div class="px-6 py-4 border-t border-slate-200 dark:border-slate-800 flex justify-end gap-3 bg-slate-50/50 dark:bg-slate-900/50">
                    <button
                        type="button"
                        @click="isDeletingPermission = false"
                        class="px-4 py-2 text-sm font-medium text-slate-700 dark:text-slate-350 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-lg hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors cursor-pointer"
                    >
                        Cancel
                    </button>
                    <button
                        type="button"
                        @click="deletePermission"
                        class="px-4 py-2 text-sm font-semibold text-white bg-red-600 hover:bg-red-700 rounded-lg shadow-sm transition-all focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 cursor-pointer"
                    >
                        Yes, Delete Permission
                    </button>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
