{% extends "dashboard/base.html" %}

{% block title %}Access Management{% endblock %}

{% block content %}
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-8"
    x-data="{ selectedGroup: {{ groups.0.id if groups else 'null' }} }">

    <!-- Page Header -->
    <div class="mb-8">
        <h1 class="text-3xl font-bold text-slate-800 dark:text-slate-100">Access Management</h1>
        <p class="mt-1 text-slate-500 dark:text-slate-400">Manage user groups, feature permissions, and user
            assignments.</p>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">

        <!-- Left Column: Group List & Creation -->
        <div class="lg:col-span-1 flex flex-col space-y-6">

            <!-- Create Group Form -->
            <div
                class="bg-white dark:bg-slate-800 p-5 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700">
                <h2 class="text-lg font-semibold mb-4 text-slate-800 dark:text-slate-200">Create New Group</h2>
                <form method="post" class="space-y-4">
                    {% csrf_token %}
                    <input type="hidden" name="action" value="create_group">
                    <div>
                        <label for="group_name" class="sr-only">Group Name</label>
                        <input type="text" id="group_name" name="group_name" required placeholder="New group name..."
                            class="w-full pl-4 pr-4 py-2 bg-slate-50 dark:bg-slate-700/50 border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500 transition">
                    </div>
                    <div>
                        <label for="description" class="sr-only">Description</label>
                        <textarea id="description" name="description" placeholder="Group description (optional)..."
                            rows="2"
                            class="w-full pl-4 pr-4 py-2 bg-slate-50 dark:bg-slate-700/50 border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500 transition"></textarea>
                    </div>
                    <button type="submit"
                        class="w-full inline-flex justify-center items-center px-4 py-2 bg-indigo-600 text-white font-semibold rounded-lg hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-slate-800 transition">
                        Create Group
                    </button>
                </form>
            </div>

            <!-- Group List -->
            <div class="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700">
                <div class="p-4 border-b border-slate-200 dark:border-slate-700">
                    <h3 class="text-lg font-medium text-slate-800 dark:text-slate-100">Groups</h3>
                </div>
                <nav class="p-2 space-y-1">
                    {% for group in groups %}
                    <a href="#" @click.prevent="selectedGroup = {{ group.id }}"
                        :class="{ 'bg-indigo-50 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-300': selectedGroup === {{ group.id }}, 'text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700/50': selectedGroup !== {{ group.id }} }"
                        class="flex justify-between items-center px-3 py-2.5 rounded-md text-sm font-medium transition-colors">
                        <div>
                            <span class="block">{{ group.group_name }}</span>
                        </div>
                        <span
                            class="text-xs px-2 py-0.5 rounded-full bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-300">{{
                            group.users.count() }} users</span>
                    </a>
                    {% endfor %}
                </nav>
            </div>
        </div>

        <!-- Right Column: Group Details Management -->
        <div class="lg:col-span-3">
            {% if not groups %}
            <div
                class="flex items-center justify-center h-full bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 p-8">
                <div class="text-center">
                    <svg class="mx-auto h-12 w-12 text-slate-400 dark:text-slate-500" fill="none" viewBox="0 0 24 24"
                        stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M17 14v6m-3-3h6M6 10h2a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v2a2 2 0 002 2zm10 0h2a2 2 0 002-2V6a2 2 0 00-2-2h-2a2 2 0 00-2 2v2a2 2 0 002 2zM6 20h2a2 2 0 002-2v-2a2 2 0 00-2-2H6a2 2 0 00-2 2v2a2 2 0 002 2z">
                        </path>
                    </svg>
                    <h3 class="mt-2 text-lg font-medium text-slate-900 dark:text-slate-100">No Groups Found</h3>
                    <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">Create a group to get started.</p>
                </div>
            </div>
            {% else %}
            {% for group in groups %}
            <div x-show="selectedGroup === {{ group.id }}" x-transition class="space-y-6">
                <!-- Header for the selected group -->
                <div class="flex justify-between items-start">
                    <div>
                        <h2 class="text-2xl font-bold text-slate-800 dark:text-slate-100">{{ group.group_name }}</h2>
                        {% if group.description %}
                        <p class="text-slate-600 dark:text-slate-400 mt-1">{{ group.description }}</p>
                        {% endif %}
                        <div class="flex items-center space-x-2 mt-2">
                            {% if group.is_active %}
                            <span
                                class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-800/30 dark:text-green-300">Active</span>
                            {% else %}
                            <span
                                class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 dark:bg-red-800/30 dark:text-red-300">Inactive</span>
                            {% endif %}
                        </div>
                    </div>
                    <div class="flex space-x-2">
                        <form method="post" class="inline">
                            {% csrf_token %}
                            <input type="hidden" name="action" value="toggle_group_status">
                            <input type="hidden" name="group_id" value="{{ group.id }}">
                            <button type="submit" class="inline-flex items-center px-3 py-1.5 text-sm 
                                    {% if group.is_active %}bg-yellow-50 text-yellow-600 dark:bg-yellow-900/20 dark:text-yellow-400 hover:bg-yellow-100 dark:hover:bg-yellow-900/40
                                    {% else %}bg-green-50 text-green-600 dark:bg-green-900/20 dark:text-green-400 hover:bg-green-100 dark:hover:bg-green-900/40{% endif %}
                                    font-semibold rounded-md transition">
                                {% if group.is_active %}Deactivate{% else %}Activate{% endif %}
                            </button>
                        </form>
                        <form method="post"
                            onsubmit="return confirm('Are you sure you want to delete this group? This action cannot be undone.');">
                            {% csrf_token %}
                            <input type="hidden" name="action" value="delete_group">
                            <input type="hidden" name="group_id" value="{{ group.id }}">
                            <button type="submit"
                                class="inline-flex items-center px-3 py-1.5 text-sm bg-red-50 text-red-600 dark:bg-red-900/20 dark:text-red-400 font-semibold rounded-md hover:bg-red-100 dark:hover:bg-red-900/40 transition">
                                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16">
                                    </path>
                                </svg>
                                Delete
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Permissions Management Card -->
                <div
                    class="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700">
                    <form method="post">
                        {% csrf_token %}
                        <input type="hidden" name="action" value="update_group_permissions">
                        <input type="hidden" name="group_id" value="{{ group.id }}">
                        <div class="p-5 border-b border-slate-200 dark:border-slate-700">
                            <h4 class="text-lg font-semibold text-slate-700 dark:text-slate-200">Feature Permissions
                            </h4>
                            <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Select the features this group
                                can access.</p>
                        </div>
                        <div class="p-5">
                            {% if features %}
                            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                {% for feature in features %}
                                {% if feature.url_name != 'access_management' %}
                                <label for="feature-{{ group.id }}-{{ feature.id }}"
                                    class="flex items-start space-x-3 p-3 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700/50 cursor-pointer transition-colors {% if not feature.is_active %}opacity-50 cursor-not-allowed{% endif %}">
                                    <input id="feature-{{ group.id }}-{{ feature.id }}" type="checkbox" name="features"
                                        value="{{ feature.id }}" {% if feature in group.features.all() and
                                        feature.is_active %}checked{% endif %} {% if not feature.is_active %}disabled{%
                                        endif %}
                                        class="h-4 w-4 mt-0.5 rounded border-slate-300 dark:border-slate-600 text-indigo-600 focus:ring-indigo-500 dark:focus:ring-indigo-400 dark:bg-slate-700">
                                    <div class="flex-1">
                                        <span class="text-sm font-medium text-slate-800 dark:text-slate-200 block">{{
                                            feature.name }}</span>
                                        {% if feature.description %}
                                        <span class="text-xs text-slate-500 dark:text-slate-400 block mt-1">{{
                                            feature.description }}</span>
                                        {% endif %}
                                        <span class="text-xs text-slate-400 dark:text-slate-500 font-mono block mt-1">{{
                                            feature.url_name }}</span>
                                        {% if not feature.is_active %}
                                        <span class="text-xs text-red-500 dark:text-red-400 block mt-1">(Feature
                                            Disabled)</span>
                                        {% endif %}
                                    </div>
                                </label>
                                {% endif %}
                                {% endfor %}
                            </div>
                            {% else %}
                            <div class="text-center py-8">
                                <svg class="mx-auto h-12 w-12 text-slate-400 dark:text-slate-500" fill="none"
                                    viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10">
                                    </path>
                                </svg>
                                <h3 class="mt-2 text-sm font-medium text-slate-900 dark:text-slate-100">No Features
                                    Available</h3>
                                <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">Create features first to
                                    assign permissions.</p>
                            </div>
                            {% endif %}
                        </div>
                        {% if features %}
                        <div
                            class="p-5 bg-slate-50 dark:bg-slate-800/50 border-t border-slate-200 dark:border-slate-700 text-right rounded-b-xl">
                            <button type="submit"
                                class="px-4 py-2 text-sm bg-indigo-600 text-white font-semibold rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:focus:ring-indigo-400 transition">Update
                                Permissions</button>
                        </div>
                        {% endif %}
                    </form>
                </div>

                <!-- User Management Card -->
                <div
                    class="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700">
                    <form method="post" x-data="{ 
        search: '', 
        get filteredUsers() {
            if (this.search.trim().length < 2) return [];
            const searchLower = this.search.trim().toLowerCase();
            return Array.from(document.querySelectorAll('[data-user-search]')).filter(el => {
                const username = el.getAttribute('data-username').toLowerCase();
                const email = el.getAttribute('data-email').toLowerCase();
                return username.includes(searchLower) || email.includes(searchLower);
            });
        },
        get resultCount() {
            return this.filteredUsers.length;
        }
    }">
                        {% csrf_token %}
                        <input type="hidden" name="action" value="update_group_users">
                        <input type="hidden" name="group_id" value="{{ group.id }}">

                        <!-- Header -->
                        <div class="p-5 border-b border-slate-200 dark:border-slate-700">
                            <div class="flex items-center justify-between mb-4">
                                <div>
                                    <h4 class="text-lg font-semibold text-slate-700 dark:text-slate-200">User Assignment
                                    </h4>
                                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Search for users to
                                        assign to this group</p>
                                </div>
                                <!-- Search Result Counter -->
                                <div x-show="search.trim().length >= 2" x-transition
                                    class="flex items-center space-x-2">
                                    <span
                                        class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-300">
                                        <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z">
                                            </path>
                                        </svg>
                                        <span x-text="resultCount"></span> found
                                    </span>
                                </div>
                            </div>

                            <!-- Enhanced Search Input -->
                            <div class="relative">
                                <span class="absolute inset-y-0 left-0 flex items-center pl-3">
                                    <svg class="w-5 h-5 text-slate-400 dark:text-slate-500" fill="none"
                                        stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                    </svg>
                                </span>
                                <input x-model="search" type="text"
                                    placeholder="Type at least 2 characters to search..."
                                    class="w-full pl-10 pr-10 py-3 text-sm bg-slate-50 dark:bg-slate-700/50 border-2 border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500 transition">

                                <!-- Clear Search Button -->
                                <button x-show="search.length > 0" @click="search = ''" type="button"
                                    class="absolute inset-y-0 right-0 flex items-center pr-3 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            d="M6 18L18 6M6 6l12 12"></path>
                                    </svg>
                                </button>
                            </div>
                        </div>

                        <!-- User List Area -->
                        <div class="p-5 max-h-96 overflow-y-auto">
                            <!-- Empty State: Before Search -->
                            <div x-show="search.trim().length < 2" class="text-center py-16">
                                <div
                                    class="inline-flex items-center justify-center w-20 h-20 rounded-full bg-indigo-100 dark:bg-indigo-900/20 mb-6">
                                    <svg class="w-10 h-10 text-indigo-600 dark:text-indigo-400" fill="none"
                                        stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                    </svg>
                                </div>
                                <h3 class="text-lg font-semibold text-slate-700 dark:text-slate-200 mb-3">Search for
                                    Users</h3>
                                <p class="text-sm text-slate-500 dark:text-slate-400 max-w-md mx-auto leading-relaxed">
                                    Start typing a username or email address (minimum 2 characters) to find and assign
                                    users to this group.
                                </p>
                                <div class="mt-4 text-xs text-slate-400 dark:text-slate-500">
                                    💡 This prevents loading thousands of users at once
                                </div>
                            </div>

                            {% if users %}
                            <!-- Hidden User Data for Search -->
                            <div class="hidden">
                                {% for user in users %}
                                {% if user.role != 'superadmin' and user.role != 'super_admin' %}
                                <div data-user-search data-username="{{ user.username|lower }}"
                                    data-email="{{ user.email|lower }}" data-user-id="{{ user.id }}"
                                    data-user-display-name="{{ user.username }}"
                                    data-user-display-email="{{ user.email }}" data-user-role="{{ user.role|title }}"
                                    data-user-assigned="{% if user in group.users.all() %}true{% else %}false{% endif %}">
                                </div>
                                {% endif %}
                                {% endfor %}
                            </div>

                            <!-- User Results Grid -->
                            <div x-show="search.trim().length >= 2" class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                {% for user in users %}
                                {% if user.role != 'superadmin' and user.role != 'super_admin' %}
                                <label for="user-{{ group.id }}-{{ user.id }}"
                                    x-show="search.trim().length >= 2 && ('{{ user.username|lower }}'.includes(search.trim().toLowerCase()) || '{{ user.email|lower }}'.includes(search.trim().toLowerCase()))"
                                    x-transition
                                    class="flex items-center space-x-3 p-4 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700/50 cursor-pointer transition-colors border-2 border-slate-200 dark:border-slate-600 hover:border-indigo-300 dark:hover:border-indigo-600">
                                    <input id="user-{{ group.id }}-{{ user.id }}" type="checkbox" name="users"
                                        value="{{ user.id }}" {% if user in group.users.all() %}checked{% endif %}
                                        class="h-4 w-4 rounded border-slate-300 dark:border-slate-600 text-indigo-600 focus:ring-indigo-500 dark:focus:ring-indigo-400 dark:bg-slate-700">
                                    <div class="flex-1 min-w-0">
                                        <p class="text-sm font-medium text-slate-800 dark:text-slate-200 truncate">{{
                                            user.username }}</p>
                                        <p class="text-xs text-slate-500 dark:text-slate-400 truncate">{{ user.email }}
                                        </p>
                                        <span
                                            class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-slate-100 text-slate-800 dark:bg-slate-700 dark:text-slate-300 mt-1">
                                            {{ user.role|title }}
                                        </span>
                                    </div>
                                    <!-- Assignment Status -->
                                    <div class="flex-shrink-0">
                                        {% if user in group.users.all() %}
                                        <div class="flex items-center text-green-600 dark:text-green-400">
                                            <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                                                <path fill-rule="evenodd"
                                                    d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                                                    clip-rule="evenodd"></path>
                                            </svg>
                                        </div>
                                        {% endif %}
                                    </div>
                                </label>
                                {% endif %}
                                {% endfor %}
                            </div>

                            <!-- Empty State: No Results -->
                            <div x-show="search.trim().length >= 2 && resultCount === 0" x-transition
                                class="text-center py-12">
                                <div
                                    class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-slate-100 dark:bg-slate-700 mb-4">
                                    <svg class="w-8 h-8 text-slate-400 dark:text-slate-500" fill="none"
                                        stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4">
                                        </path>
                                    </svg>
                                </div>
                                <h3 class="text-base font-semibold text-slate-700 dark:text-slate-200 mb-2">No Users
                                    Found</h3>
                                <p class="text-sm text-slate-500 dark:text-slate-400">
                                    No users match "<span class="font-medium text-slate-700 dark:text-slate-300"
                                        x-text="search"></span>"
                                </p>
                                <p class="text-xs text-slate-400 dark:text-slate-500 mt-2">Try a different search term
                                </p>
                            </div>

                            {% else %}
                            <!-- No Users in System -->
                            <div x-show="search.trim().length >= 2" class="text-center py-12">
                                <svg class="mx-auto h-12 w-12 text-slate-400 dark:text-slate-500 mb-4" fill="none"
                                    viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                                </svg>
                                <h3 class="text-base font-semibold text-slate-700 dark:text-slate-200 mb-2">No Users
                                    Available</h3>
                                <p class="text-sm text-slate-500 dark:text-slate-400">No users found in the system to
                                    assign to groups.</p>
                            </div>
                            {% endif %}
                        </div>

                        {% if users %}
                        <!-- Footer with Submit Button -->
                        <div x-show="search.trim().length >= 2 && resultCount > 0"
                            class="p-5 bg-slate-50 dark:bg-slate-800/50 border-t border-slate-200 dark:border-slate-700 flex items-center justify-between rounded-b-xl">
                            <p class="text-xs text-slate-500 dark:text-slate-400">
                                Select users and click update to save changes
                            </p>
                            <button type="submit"
                                class="px-5 py-2.5 text-sm bg-indigo-600 text-white font-semibold rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:focus:ring-indigo-400 shadow-sm hover:shadow transition-all">
                                <span class="flex items-center">
                                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            d="M5 13l4 4L19 7"></path>
                                    </svg>
                                    Update Users
                                </span>
                            </button>
                        </div>
                        {% endif %}
                    </form>
                </div>
            </div>
            {% endfor %}
            {% endif %}
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
{% endblock %}