{% extends "base.html" %}
{% from "components/ui.html" import page_header, breadcrumb_nav, button, filter_badge %}

{% block content %}
{% set breadcrumbs = [
    {'text': _('Admin'), 'url': url_for('admin.admin_dashboard')},
    {'text': _('Roles & Permissions')}
] %}

{{ page_header(
    icon_class='fas fa-shield-alt',
    title_text=_('Roles & Permissions'),
    subtitle_text=_('Manage roles and their permissions'),
    breadcrumbs=breadcrumbs,
    actions_html=''
        + '<div class="flex gap-2">'
        +   '<a href="' + url_for("permissions.list_permissions") + '" class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 transition-colors">' + _('View Permissions') + '</a>'
        +   ('<a href="' + url_for("permissions.create_role") + '" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors"><i class="fas fa-plus mr-2"></i>' + _('Create Role') + '</a>' if (current_user.is_admin or has_permission('manage_roles')) else '')
        + '</div>'
) }}

<!-- Statistics Summary -->
<div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
    <div class="bg-card-light dark:bg-card-dark p-4 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
        <div class="flex items-center">
            <div class="flex-shrink-0 bg-primary/10 rounded-full p-3">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
                </svg>
            </div>
            <div class="ml-4">
                <p class="text-sm text-text-muted-light dark:text-text-muted-dark">{{ _('Total Roles') }}</p>
                <p class="text-2xl font-bold">{{ roles|length }}</p>
            </div>
        </div>
    </div>
    
    <div class="bg-card-light dark:bg-card-dark p-4 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
        <div class="flex items-center">
            <div class="flex-shrink-0 bg-blue-100 dark:bg-blue-900/30 rounded-full p-3">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-600 dark:text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                </svg>
            </div>
            <div class="ml-4">
                <p class="text-sm text-text-muted-light dark:text-text-muted-dark">{{ _('System Roles') }}</p>
                <p class="text-2xl font-bold">{{ roles|selectattr('is_system_role')|list|length }}</p>
            </div>
        </div>
    </div>
    
    <div class="bg-card-light dark:bg-card-dark p-4 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
        <div class="flex items-center">
            <div class="flex-shrink-0 bg-gray-100 dark:bg-gray-700 rounded-full p-3">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-600 dark:text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                </svg>
            </div>
            <div class="ml-4">
                <p class="text-sm text-text-muted-light dark:text-text-muted-dark">{{ _('Custom Roles') }}</p>
                <p class="text-2xl font-bold">{{ roles|rejectattr('is_system_role')|list|length }}</p>
            </div>
        </div>
    </div>
    
    <div class="bg-card-light dark:bg-card-dark p-4 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
        <div class="flex items-center">
            <div class="flex-shrink-0 bg-green-100 dark:bg-green-900/30 rounded-full p-3">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-green-600 dark:text-green-400" 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" />
                </svg>
            </div>
            <div class="ml-4">
                <p class="text-sm text-text-muted-light dark:text-text-muted-dark">{{ _('Assigned Users') }}</p>
                <p class="text-2xl font-bold">
                    {% set total_users = namespace(count=0) %}
                    {% for role in roles %}
                        {% set total_users.count = total_users.count + role.users.count() %}
                    {% endfor %}
                    {{ total_users.count }}
                </p>
            </div>
        </div>
    </div>
</div>

<div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm overflow-x-auto">
    <table class="w-full text-left enhanced-table responsive-cards">
        <thead class="bg-background-light dark:bg-background-dark border-b border-border-light dark:border-border-dark">
            <tr>
                <th class="px-4 py-3">{{ _('Role Name') }}</th>
                <th class="px-4 py-3">{{ _('Description') }}</th>
                <th class="px-4 py-3">{{ _('Permissions') }}</th>
                <th class="px-4 py-3">{{ _('Users') }}</th>
                <th class="px-4 py-3">{{ _('Type') }}</th>
                <th class="px-4 py-3">{{ _('Actions') }}</th>
            </tr>
        </thead>
        <tbody>
            {% for role in roles %}
            <tr class="border-b border-border-light dark:border-border-dark hover:bg-bg-hover-light dark:hover:bg-bg-hover-dark">
                <td class="p-4 mobile-card-header" data-label="Role">
                    <div class="font-semibold">{{ role.name }}</div>
                    {% if role.is_system_role %}
                    <span class="text-xs text-text-muted-light dark:text-text-muted-dark">{{ _('Default role') }}</span>
                    {% endif %}
                </td>
                <td class="p-4 text-sm text-text-muted-light dark:text-text-muted-dark" data-label="Description">{{ role.description or '-' }}</td>
                <td class="p-4" data-label="Permissions">
                    <button type="button" 
                            onclick="document.getElementById('perms-{{ role.id }}').classList.toggle('hidden')"
                            class="text-primary hover:underline text-sm flex items-center gap-1">
                        <span>{{ role.permissions|length }} {{ _('permissions') }}</span>
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                        </svg>
                    </button>
                </td>
                <td class="p-4" data-label="Users">
                    {% set user_count = role.users.count() %}
                    {% if user_count > 0 %}
                    <a href="{{ url_for('permissions.view_role', role_id=role.id) }}" class="text-sm font-semibold text-primary hover:underline">
                        {{ user_count }} {{ _('user') if user_count == 1 else _('users') }}
                    </a>
                    {% else %}
                    <span class="text-sm text-text-muted-light dark:text-text-muted-dark">{{ _('No users') }}</span>
                    {% endif %}
                </td>
                <td class="p-4" data-label="Type">
                    {% if role.is_system_role %}
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
                        {{ _('System') }}
                    </span>
                    {% else %}
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200">
                        {{ _('Custom') }}
                    </span>
                    {% endif %}
                </td>
                <td class="p-4 mobile-actions" data-label="Actions">
                    <div class="flex gap-2">
                        <a href="{{ url_for('permissions.view_role', role_id=role.id) }}" class="text-primary hover:underline text-sm">{{ _('View') }}</a>
                        {% if current_user.is_admin or has_permission('manage_roles') %}
                        <a href="{{ url_for('permissions.edit_role', role_id=role.id) }}" class="text-primary hover:underline text-sm">{{ _('Edit') }}</a>
                        {% endif %}
                        {% if not role.is_system_role and (current_user.is_admin or has_permission('manage_roles')) %}
                        <form id="deleteRoleForm-{{ role.id }}" action="{{ url_for('permissions.delete_role', role_id=role.id) }}" method="post" class="inline">
                            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                            <button type="button" onclick="confirmDeleteRole({{ role.id }}, '{{ role.name }}')" class="text-red-600 hover:underline text-sm">{{ _('Delete') }}</button>
                        </form>
                        {% endif %}
                    </div>
                </td>
            </tr>
            <!-- Expandable permission details row -->
            <tr id="perms-{{ role.id }}" class="hidden bg-background-light dark:bg-background-dark">
                <td colspan="6" class="p-4">
                    <div class="text-sm">
                        <h4 class="font-semibold mb-2">{{ _('Permissions for') }} {{ role.name }}:</h4>
                        {% set categories = {} %}
                        {% for permission in role.permissions %}
                            {% if permission.category not in categories %}
                                {% set _ = categories.update({permission.category: []}) %}
                            {% endif %}
                            {% set _ = categories[permission.category].append(permission) %}
                        {% endfor %}
                        
                        {% if categories %}
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            {% for category, perms in categories.items() %}
                            <div class="border border-border-light dark:border-border-dark rounded p-3">
                                <h5 class="font-semibold text-primary text-xs uppercase mb-2">{{ category.replace('_', ' ') }}</h5>
                                <ul class="space-y-1">
                                    {% for perm in perms %}
                                    <li class="text-xs flex items-center gap-1">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3 text-green-600" viewBox="0 0 20 20" fill="currentColor">
                                            <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                        </svg>
                                        <span>{{ perm.name.replace('_', ' ') }}</span>
                                    </li>
                                    {% endfor %}
                                </ul>
                            </div>
                            {% endfor %}
                        </div>
                        {% else %}
                        <p class="text-text-muted-light dark:text-text-muted-dark">{{ _('No permissions assigned.') }}</p>
                        {% endif %}
                    </div>
                </td>
            </tr>
            {% else %}
            <tr>
                <td colspan="6" class="p-4 text-center text-text-muted-light dark:text-text-muted-dark">{{ _('No roles found.') }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

<div class="mt-6 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
    <h3 class="font-semibold text-blue-900 dark:text-blue-100 mb-2">{{ _('About Roles & Permissions') }}</h3>
    <p class="text-sm text-blue-800 dark:text-blue-200">
        {{ _('Roles are collections of permissions that can be assigned to users. System roles are predefined and cannot be deleted or renamed, but custom roles can be created for your specific needs.') }}
    </p>
</div>

<script>
async function confirmDeleteRole(roleId, roleName) {
    const confirmed = await showConfirm(
        '{{ _("Are you sure you want to delete the role") }} "' + roleName + '"?',
        {
            title: '{{ _("Delete Role") }}',
            confirmText: '{{ _("Delete") }}',
            cancelText: '{{ _("Cancel") }}',
            variant: 'danger'
        }
    );
    if (confirmed) {
        document.getElementById('deleteRoleForm-' + roleId).submit();
    }
}
</script>
{% endblock %}

