{% extends 'users/base.html' %}

{% block title %}{% if form.instance.pk %}Edit Role{% else %}Add New Role{% endif %}{% endblock %}

{% block card_content %}
<form method="post" class="needs-validation" novalidate>
    {% csrf_token %}
    
    <div class="row mb-3">
        <div class="col-12">
            <div class="form-group">
                <label for="{{ form.name.id_for_label }}" class="form-label">{{ form.name.label }} *</label>
                {{ form.name }}
                {% if form.name.errors %}
                    <div class="invalid-feedback d-block">
                        {{ form.name.errors|join:", " }}
                    </div>
                {% endif %}
            </div>
        </div>
    </div>
    
    <div class="row mb-3">
        <div class="col-12">
            <div class="form-group">
                <label for="{{ form.permissions.id_for_label }}" class="form-label">{{ form.permissions.label }}</label>
                {{ form.permissions }}
                {% if form.permissions.errors %}
                    <div class="invalid-feedback d-block">
                        {{ form.permissions.errors|join:", " }}
                    </div>
                {% endif %}
                <small class="form-text text-muted">
                    Hold down "Control" or "Command" to select multiple permissions.
                </small>
            </div>
        </div>
    </div>
    
    <div class="d-flex justify-content-between mt-4">
        <a href="{% if form.instance.pk %}{% url 'users:role_detail' form.instance.pk %}{% else %}{% url 'users:role_list' %}{% endif %}" 
           class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> Cancel
        </a>
        <button type="submit" class="btn btn-primary">
            <i class="fas fa-save"></i> Save Changes
        </button>
    </div>
</form>
{% endblock %}

{% block extra_css %}
<style>
/* Style for the permissions select multiple */
select[multiple] {
    min-height: 200px;
}

/* Style for permission groups */
.permission-group {
    margin-bottom: 1rem;
    border: 1px solid #dee2e6;
    border-radius: 0.25rem;
    overflow: hidden;
}

.permission-group-header {
    padding: 0.5rem 1rem;
    background-color: #f8f9fa;
    border-bottom: 1px solid #dee2e6;
    font-weight: bold;
}

.permission-options {
    padding: 0.5rem;
    max-height: 200px;
    overflow-y: auto;
}

.permission-option {
    padding: 0.25rem 0.5rem;
    margin: 0.125rem 0;
    border-radius: 0.2rem;
    cursor: pointer;
}

.permission-option:hover {
    background-color: #f1f8ff;
}

.permission-option input[type="checkbox"] {
    margin-right: 0.5rem;
}
</style>
{% endblock %}

{% block extra_js %}
<script>
// Enable Bootstrap form validation
(function () {
  'use strict'
  
  // Fetch all the forms we want to apply custom Bootstrap validation styles to
  const forms = document.querySelectorAll('.needs-validation')
  
  // Loop over them and prevent submission
  Array.from(forms).forEach(form => {
    form.addEventListener('submit', event => {
      if (!form.checkValidity()) {
        event.preventDefault()
        event.stopPropagation()
      }
      
      form.classList.add('was-validated')
    }, false)
  })
})()

// Enhance the permissions select with search and better UX
document.addEventListener('DOMContentLoaded', function() {
    const permissionsSelect = document.getElementById('{{ form.permissions.id_for_label }}');
    
    if (permissionsSelect) {
        // Initialize Select2 if available
        if (typeof $ !== 'undefined' && $.fn.select2) {
            $(permissionsSelect).select2({
                placeholder: 'Select permissions',
                allowClear: true,
                width: '100%',
                dropdownParent: $(permissionsSelect).parent()
            });
        }
        
        // Group permissions by app label
        const options = Array.from(permissionsSelect.options);
        const groupedOptions = {};
        
        options.forEach(option => {
            if (option.value) {
                const parts = option.text.split(' | ');
                if (parts.length === 2) {
                    const [appLabel, permName] = parts;
                    if (!groupedOptions[appLabel]) {
                        groupedOptions[appLabel] = [];
                    }
                    groupedOptions[appLabel].push({
                        value: option.value,
                        text: permName,
                        selected: option.selected
                    });
                }
            }
        });
        
        // Clear the select
        permissionsSelect.innerHTML = '';
        
        // Add grouped options
        Object.entries(groupedOptions).forEach(([appLabel, perms]) => {
            const group = document.createElement('optgroup');
            group.label = appLabel;
            
            perms.forEach(perm => {
                const option = document.createElement('option');
                option.value = perm.value;
                option.textContent = perm.text;
                option.selected = perm.selected;
                group.appendChild(option);
            });
            
            permissionsSelect.appendChild(group);
        });
    }
});
</script>
{% endblock %}
