{% extends 'base.html' %}
{% load static %}

{% block title %}Bulk Apply Role Templates{% endblock %}

{% block content %}
<div class="space-y-6">
    <!-- Header -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:p-6">
            <div class="flex justify-between items-center">
                <div>
                    <h3 class="text-lg leading-6 font-medium text-gray-900">
                        <i class="fas fa-users-cog text-primary mr-2"></i>
                        Bulk Apply Role Templates
                    </h3>
                    <p class="mt-1 max-w-2xl text-sm text-gray-500">
                        Apply role templates to multiple users at once. {{ total_users }} staff members available.
                    </p>
                </div>
                <a href="{% url 'users:role_template_configuration' %}"
                    class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                    <span>←</span>
                    Back to Templates
                </a>
            </div>
        </div>
    </div>

    {% if messages %}
    {% for message in messages %}
    <div class="bg-{% if message.tags == 'error' %}red{% else %}green{% endif %}-50 border border-{% if message.tags == 'error' %}red{% else %}green{% endif %}-200 rounded-md p-4">
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fas fa-{% if message.tags == 'error' %}exclamation-triangle{% else %}check-circle{% endif %} text-{% if message.tags == 'error' %}red{% else %}green{% endif %}-400"></i>
            </div>
            <div class="ml-3">
                <p class="text-sm text-{% if message.tags == 'error' %}red{% else %}green{% endif %}-700">{{ message }}</p>
            </div>
        </div>
    </div>
    {% endfor %}
    {% endif %}

    <!-- Bulk Application Form -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:p-6">
            <h4 class="text-lg font-medium text-gray-900 mb-4">
                <span>⚙️</span>
                Bulk Template Application
            </h4>
            
            <form id="bulkApplyForm" class="space-y-6">
                {% csrf_token %}
                
                <!-- Template Selection -->
                <div>
                    <label for="roleTemplate" class="block text-sm font-medium text-gray-700">
                        Select Role Template to Apply
                    </label>
                    <select id="roleTemplate" name="role_template" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary">
                        <option value="">Choose a role template...</option>
                        {% for role_code, role_name in available_roles %}
                        <option value="{{ role_code }}">{{ role_name }}</option>
                        {% endfor %}
                    </select>
                    <p class="mt-2 text-sm text-gray-500">
                        This template will be applied to all selected users.
                    </p>
                </div>

                <!-- Options -->
                <div class="space-y-4">
                    <div class="flex items-center">
                        <input id="updateExisting" name="update_existing" type="checkbox" class="rounded border-gray-300 text-primary focus:ring-primary">
                        <label for="updateExisting" class="ml-2 text-sm text-gray-700">
                            Update existing custom permissions
                        </label>
                    </div>
                    <p class="text-xs text-gray-500 ml-6">
                        If checked, existing custom permissions will be overwritten. If unchecked, only missing permissions will be added.
                    </p>
                </div>

                <!-- User Selection -->
                <div>
                    <div class="flex justify-between items-center mb-4">
                        <label class="block text-sm font-medium text-gray-700">
                            Select Users
                        </label>
                        <div class="flex space-x-2">
                            <button type="button" onclick="selectAll()" 
                                    class="text-xs px-3 py-1 bg-blue-100 text-blue-700 rounded hover:bg-blue-200">
                                Select All
                            </button>
                            <button type="button" onclick="deselectAll()" 
                                    class="text-xs px-3 py-1 bg-gray-100 text-gray-700 rounded hover:bg-gray-200">
                                Deselect All
                            </button>
                        </div>
                    </div>

                    <!-- Filter by Role -->
                    <div class="mb-4">
                        <label for="roleFilter" class="block text-sm font-medium text-gray-700 mb-2">
                            Filter by Current Role
                        </label>
                        <div class="flex flex-wrap gap-2">
                            <button type="button" onclick="filterByRole('all')" 
                                    class="role-filter-btn active text-xs px-3 py-1 bg-primary text-white rounded hover:bg-primary-dark"
                                    data-role="all">
                                All Roles
                            </button>
                            {% for role_code, role_name in available_roles %}
                            <button type="button" onclick="filterByRole('{{ role_code }}')" 
                                    class="role-filter-btn text-xs px-3 py-1 bg-gray-100 text-gray-700 rounded hover:bg-gray-200"
                                    data-role="{{ role_code }}">
                                {{ role_name }}
                            </button>
                            {% endfor %}
                        </div>
                    </div>

                    <!-- Users List -->
                    <div class="border border-gray-200 rounded-lg max-h-96 overflow-y-auto">
                        <div class="divide-y divide-gray-200">
                            {% for role_code, users in users_by_role.items %}
                            {% for user in users %}
                            <label class="user-item flex items-center p-4 hover:bg-gray-50 cursor-pointer" 
                                   data-role="{{ user.role }}">
                                <input type="checkbox" name="user_ids" value="{{ user.id }}" 
                                       class="rounded border-gray-300 text-primary focus:ring-primary mr-3 user-checkbox">
                                <div class="flex-shrink-0 h-10 w-10">
                                    {% if user.profile_image %}
                                    <img class="h-10 w-10 rounded-full object-cover" src="{{ user.profile_image.url }}" alt="{{ user.get_full_name }}">
                                    {% elif user.selfie %}
                                    <img class="h-10 w-10 rounded-full object-cover" src="{{ user.selfie.url }}" alt="{{ user.get_full_name }}">
                                    {% else %}
                                    <div class="h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center">
                                        <span class="text-sm font-medium text-gray-700">{{ user.get_initials }}</span>
                                    </div>
                                    {% endif %}
                                </div>
                                <div class="ml-3 flex-1">
                                    <div class="text-sm font-medium text-gray-900">{{ user.get_full_name }}</div>
                                    <div class="text-sm text-gray-500">{{ user.email }}</div>
                                </div>
                                <div class="text-right">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium 
                                        {% if user.role == 'admin' %}bg-red-100 text-red-800
                                        {% elif user.role == 'team_leader' %}bg-blue-100 text-blue-800
                                        {% elif user.role == 'loan_officer' %}bg-green-100 text-green-800
                                        {% elif user.role == 'secretary' %}bg-purple-100 text-purple-800
                                        {% elif user.role == 'auditor' %}bg-yellow-100 text-yellow-800
                                        {% else %}bg-gray-100 text-gray-800{% endif %}">
                                        {{ user.get_role_display }}
                                    </span>
                                </div>
                            </label>
                            {% endfor %}
                            {% endfor %}
                        </div>
                    </div>

                    <!-- Selection Summary -->
                    <div class="mt-4 p-3 bg-gray-50 rounded-lg">
                        <div class="flex justify-between items-center">
                            <span class="text-sm text-gray-700">
                                <span id="selectedCount">0</span> users selected
                            </span>
                            <span class="text-xs text-gray-500" id="selectionSummary">
                                No users selected
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="flex justify-end space-x-3">
                    <a href="{% url 'users:role_template_configuration' %}"
                        class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                        Cancel
                    </a>
                    <button type="submit"
                            class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary-dark focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                        <span>✓</span>
                        Apply Templates
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    updateSelectionSummary();
    
    // Add event listeners to checkboxes
    document.querySelectorAll('.user-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', updateSelectionSummary);
    });
});

function selectAll() {
    const visibleCheckboxes = document.querySelectorAll('.user-item:not([style*="display: none"]) .user-checkbox');
    visibleCheckboxes.forEach(checkbox => {
        checkbox.checked = true;
    });
    updateSelectionSummary();
}

function deselectAll() {
    const visibleCheckboxes = document.querySelectorAll('.user-item:not([style*="display: none"]) .user-checkbox');
    visibleCheckboxes.forEach(checkbox => {
        checkbox.checked = false;
    });
    updateSelectionSummary();
}

function filterByRole(role) {
    // Update filter button styles
    document.querySelectorAll('.role-filter-btn').forEach(btn => {
        btn.classList.remove('active', 'bg-primary', 'text-white');
        btn.classList.add('bg-gray-100', 'text-gray-700');
    });
    
    const activeBtn = document.querySelector(`[data-role="${role}"]`);
    activeBtn.classList.add('active', 'bg-primary', 'text-white');
    activeBtn.classList.remove('bg-gray-100', 'text-gray-700');
    
    // Filter users
    document.querySelectorAll('.user-item').forEach(item => {
        if (role === 'all' || item.dataset.role === role) {
            item.style.display = '';
        } else {
            item.style.display = 'none';
        }
    });
    
    updateSelectionSummary();
}

function updateSelectionSummary() {
    const checkboxes = document.querySelectorAll('.user-checkbox:checked');
    const selectedCount = checkboxes.length;
    
    document.getElementById('selectedCount').textContent = selectedCount;
    
    if (selectedCount === 0) {
        document.getElementById('selectionSummary').textContent = 'No users selected';
    } else {
        // Count by role
        const roleCount = {};
        checkboxes.forEach(checkbox => {
            const userItem = checkbox.closest('.user-item');
            const role = userItem.dataset.role;
            roleCount[role] = (roleCount[role] || 0) + 1;
        });
        
        const roleSummary = Object.entries(roleCount).map(([role, count]) => {
            const roleName = document.querySelector(`[data-role="${role}"]`).textContent.trim();
            return `${count} ${roleName}`;
        }).join(', ');
        
        document.getElementById('selectionSummary').textContent = roleSummary;
    }
}

document.getElementById('bulkApplyForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const roleTemplate = formData.get('role_template');
    const updateExisting = formData.get('update_existing') === 'on';
    const userIds = Array.from(formData.getAll('user_ids'));
    
    if (!roleTemplate) {
        alert('Please select a role template to apply.');
        return;
    }
    
    if (userIds.length === 0) {
        alert('Please select at least one user.');
        return;
    }
    
    const templateName = document.querySelector(`option[value="${roleTemplate}"]`).textContent;
    
    if (!confirm(`Are you sure you want to apply the ${templateName} template to ${userIds.length} selected users?`)) {
        return;
    }
    
    // Show loading state
    const submitButton = this.querySelector('button[type="submit"]');
    const originalText = submitButton.innerHTML;
    submitButton.innerHTML = '<span>⟳</span>Applying Templates...';
    submitButton.disabled = true;
    
    fetch('{% url "users:bulk_apply_role_templates" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
        },
        body: JSON.stringify({
            user_ids: userIds,
            role_template: roleTemplate,
            update_existing: updateExisting
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('success', data.message);
            
            // Clear selections
            document.querySelectorAll('.user-checkbox').forEach(checkbox => {
                checkbox.checked = false;
            });
            updateSelectionSummary();
            
            // Reset form
            document.getElementById('roleTemplate').value = '';
            document.getElementById('updateExisting').checked = false;
        } else {
            showNotification('error', data.error || 'Failed to apply role templates');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('error', 'An error occurred while applying role templates');
    })
    .finally(() => {
        // Restore button state
        submitButton.innerHTML = originalText;
        submitButton.disabled = false;
    });
});

function showNotification(type, message) {
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 z-50 p-4 rounded-md shadow-lg ${type === 'success' ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'}`;
    notification.innerHTML = `
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} text-${type === 'success' ? 'green' : 'red'}-400"></i>
            </div>
            <div class="ml-3">
                <p class="text-sm text-${type === 'success' ? 'green' : 'red'}-700">${message}</p>
            </div>
            <div class="ml-auto pl-3">
                <button onclick="this.parentElement.parentElement.remove()" class="text-${type === 'success' ? 'green' : 'red'}-400 hover:text-${type === 'success' ? 'green' : 'red'}-600">
                    <span>✕</span>
                </button>
            </div>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        if (notification.parentElement) {
            notification.remove();
        }
    }, 5000);
}
</script>
{% endblock %}