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

{% block title %}Role Template Configuration{% 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-user-cog text-primary mr-2"></i>
                        Role Template Configuration
                    </h3>
                    <p class="mt-1 max-w-2xl text-sm text-gray-500">
                        Configure default permissions for each user role. These templates will be applied to new users automatically.
                    </p>
                </div>
                <div class="flex space-x-2">
                    <a href="{% url 'users:role_comparison' %}"
                        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">
                        <i class="fas fa-balance-scale mr-2"></i>
                        Compare Roles
                    </a>
                    <a href="{% url 'users:permission_matrix_view' %}"
                        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">
                        <i class="fas fa-table mr-2"></i>
                        Permission Matrix
                    </a>
                </div>
            </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 %}

    <!-- Role Statistics Overview -->
    <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>
                Role Permission Overview
            </h4>
            <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
                {% for role_code, role_data in role_stats.items %}
                <div class="bg-gray-50 rounded-lg p-4 border border-gray-200">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-900">{{ role_data.name }}</p>
                            <p class="text-xs text-gray-500">{{ role_data.allowed_permissions }}/{{ role_data.total_permissions }} permissions</p>
                        </div>
                        <div class="text-right">
                            <p class="text-lg font-semibold text-primary">{{ role_data.percentage }}%</p>
                        </div>
                    </div>
                    <div class="mt-2">
                        <div class="bg-gray-200 rounded-full h-2">
                            <div class="bg-primary rounded-full h-2" style="width: {{ role_data.percentage }}%"></div>
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>

    <!-- Role Selection Tabs -->
    <div class="bg-white shadow rounded-lg">
        <div class="border-b border-gray-200">
            <nav class="-mb-px flex space-x-8 px-6" aria-label="Tabs">
                {% for role_code, role_name in roles %}
                <button onclick="switchRole('{{ role_code }}')" 
                        class="role-tab {% if forloop.first %}active{% endif %} whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
                        data-role="{{ role_code }}">
                    {% if role_code == 'admin' %}
                        <i class="fas fa-crown mr-2"></i>
                    {% elif role_code == 'team_leader' %}
                        <span>👔</span>
                    {% elif role_code == 'loan_officer' %}
                        <i class="fas fa-handshake mr-2"></i>
                    {% elif role_code == 'secretary' %}
                        <i class="fas fa-user-secret mr-2"></i>
                    {% elif role_code == 'auditor' %}
                        <span>🔍</span>
                    {% else %}
                        <span>👤</span>
                    {% endif %}
                    {{ role_name }}
                    <span class="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                        {{ role_stats|get_item:role_code.allowed_permissions|default:0 }}
                    </span>
                </button>
                {% endfor %}
            </nav>
        </div>

        <!-- Role Configuration Content -->
        <div class="p-6">
            {% for role_code, role_name in roles %}
            <div id="role-{{ role_code }}" class="role-content {% if not forloop.first %}hidden{% endif %}">
                <div class="flex justify-between items-center mb-6">
                    <div>
                        <h4 class="text-lg font-medium text-gray-900">{{ role_name }} Permissions</h4>
                        <p class="text-sm text-gray-500">Configure default permissions for {{ role_name|lower }} users</p>
                    </div>
                    <div class="flex space-x-2">
                        <button onclick="selectAllForRole('{{ role_code }}')" 
                                class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                            <i class="fas fa-check-square mr-2"></i>Select All
                        </button>
                        <button onclick="deselectAllForRole('{{ role_code }}')" 
                                class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                            <i class="fas fa-square mr-2"></i>Deselect All
                        </button>
                        <button onclick="saveRoleTemplate('{{ role_code }}')" 
                                class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-primary hover:bg-primary-dark">
                            <span>💾</span>Save Template
                        </button>
                    </div>
                </div>

                <!-- Bulk Actions -->
                <div class="bg-gray-50 rounded-lg p-4 mb-6">
                    <h5 class="text-sm font-medium text-gray-900 mb-3">Bulk Actions</h5>
                    <div class="flex flex-wrap gap-2">
                        <button onclick="selectByPage('{{ role_code }}', 'all')" 
                                class="text-xs px-3 py-1 bg-blue-100 text-blue-700 rounded hover:bg-blue-200">
                            All Pages
                        </button>
                        {% for page_name in page_names %}
                        <button onclick="selectByPage('{{ role_code }}', '{{ page_name }}')" 
                                class="text-xs px-3 py-1 bg-green-100 text-green-700 rounded hover:bg-green-200">
                            {{ page_name|title }}
                        </button>
                        {% endfor %}
                        <button onclick="selectByCategory('{{ role_code }}', 'view')" 
                                class="text-xs px-3 py-1 bg-purple-100 text-purple-700 rounded hover:bg-purple-200">
                            View Only
                        </button>
                        <button onclick="selectByCategory('{{ role_code }}', 'create')" 
                                class="text-xs px-3 py-1 bg-yellow-100 text-yellow-700 rounded hover:bg-yellow-200">
                            Create Only
                        </button>
                    </div>
                </div>

                <!-- Permissions by Page -->
                <div class="space-y-6">
                    {% for page_name, categories in permissions_by_page.items %}
                    <div class="border border-gray-200 rounded-lg p-6">
                        <div class="flex items-center justify-between mb-4">
                            <h5 class="text-lg font-medium text-gray-900 flex items-center">
                                {% if 'dashboard' in page_name %}
                                <i class="fas fa-tachometer-alt text-blue-500 mr-3"></i>
                                {% elif 'client' in page_name %}
                                <span>👥</span>
                                {% elif 'loan' in page_name %}
                                <span>💵</span>
                                {% elif 'repayment' in page_name or 'payment' in page_name %}
                                <span>💳</span>
                                {% elif 'report' in page_name %}
                                <span>📊</span>
                                {% else %}
                                <span>📦</span>
                                {% endif %}
                                {{ page_name|title }}
                            </h5>
                            <div class="flex space-x-2">
                                <button onclick="selectPageAll('{{ role_code }}', '{{ page_name }}')" 
                                        class="text-xs px-2 py-1 bg-green-100 text-green-700 rounded hover:bg-green-200">
                                    Select All
                                </button>
                                <button onclick="deselectPageAll('{{ role_code }}', '{{ page_name }}')" 
                                        class="text-xs px-2 py-1 bg-red-100 text-red-700 rounded hover:bg-red-200">
                                    Deselect All
                                </button>
                            </div>
                        </div>

                        {% for category, permissions in categories.items %}
                        <div class="mb-4">
                            <h6 class="text-sm font-medium text-gray-700 mb-2 flex items-center">
                                {% if category == 'view' %}
                                <i class="fas fa-eye text-blue-400 mr-2"></i>
                                {% elif category == 'create' %}
                                <span>+</span>
                                {% elif category == 'edit' %}
                                <span>✏️</span>
                                {% elif category == 'delete' %}
                                <span>🗑️</span>
                                {% elif category == 'approve' %}
                                <span>✓</span>
                                {% elif category == 'export' %}
                                <span>⬇️</span>
                                {% else %}
                                <span>⚙️</span>
                                {% endif %}
                                {{ category|title }} Actions
                            </h6>
                            <div class="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6">
                                {% for permission in permissions %}
                                <label class="flex items-center text-sm cursor-pointer hover:bg-gray-50 p-2 rounded">
                                    <input type="checkbox" 
                                           id="perm_{{ role_code }}_{{ permission.id }}"
                                           class="rounded border-gray-300 text-primary focus:ring-primary mr-2 permission-checkbox"
                                           data-role="{{ role_code }}"
                                           data-page="{{ page_name }}"
                                           data-category="{{ category }}"
                                           data-action="{{ permission.action_code }}"
                                           data-permission-id="{{ permission.id }}"
                                           {% if role_templates|get_item:role_code|get_item:page_name|get_item:permission.action_code.is_allowed %}checked{% endif %}>
                                    <span class="text-gray-700 flex-1">{{ permission.action_name }}</span>
                                    {% if permission.is_critical %}
                                    <span class="ml-1 text-red-500 font-bold text-xs" title="Critical Permission">!</span>
                                    {% endif %}
                                </label>
                                {% endfor %}
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    {% endfor %}
                </div>
            </div>
            {% endfor %}
        </div>
    </div>

    <!-- Clone Role Template Modal -->
    <div id="cloneModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3">
                <h3 class="text-lg font-medium text-gray-900 mb-4">Clone Role Template</h3>
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700">From Role</label>
                        <select id="sourceRole" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary">
                            {% for role_code, role_name in roles %}
                            <option value="{{ role_code }}">{{ role_name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">To Role</label>
                        <select id="targetRole" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary">
                            {% for role_code, role_name in roles %}
                            <option value="{{ role_code }}">{{ role_name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="flex items-center">
                        <input type="checkbox" id="overwriteExisting" class="rounded border-gray-300 text-primary focus:ring-primary">
                        <label for="overwriteExisting" class="ml-2 text-sm text-gray-700">Overwrite existing permissions</label>
                    </div>
                </div>
                <div class="flex justify-end space-x-3 mt-6">
                    <button onclick="closeCloneModal()" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400">
                        Cancel
                    </button>
                    <button onclick="executeClone()" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-dark">
                        Clone Template
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize the first role tab as active
    switchRole('{{ roles.0.0 }}');
});

function switchRole(roleCode) {
    // Hide all role content
    document.querySelectorAll('.role-content').forEach(content => {
        content.classList.add('hidden');
    });
    
    // Show selected role content
    document.getElementById('role-' + roleCode).classList.remove('hidden');
    
    // Update tab styles
    document.querySelectorAll('.role-tab').forEach(tab => {
        tab.classList.remove('active', 'border-primary', 'text-primary');
        tab.classList.add('border-transparent', 'text-gray-500', 'hover:text-gray-700', 'hover:border-gray-300');
    });
    
    // Activate selected tab
    const activeTab = document.querySelector(`[data-role="${roleCode}"]`);
    activeTab.classList.add('active', 'border-primary', 'text-primary');
    activeTab.classList.remove('border-transparent', 'text-gray-500', 'hover:text-gray-700', 'hover:border-gray-300');
}

function selectAllForRole(roleCode) {
    const checkboxes = document.querySelectorAll(`[data-role="${roleCode}"]`);
    checkboxes.forEach(checkbox => {
        checkbox.checked = true;
        checkbox.dispatchEvent(new Event('change'));
    });
}

function deselectAllForRole(roleCode) {
    const checkboxes = document.querySelectorAll(`[data-role="${roleCode}"]`);
    checkboxes.forEach(checkbox => {
        checkbox.checked = false;
        checkbox.dispatchEvent(new Event('change'));
    });
}

function selectByPage(roleCode, pageName) {
    let selector = `[data-role="${roleCode}"]`;
    if (pageName !== 'all') {
        selector += `[data-page="${pageName}"]`;
    }
    
    const checkboxes = document.querySelectorAll(selector);
    checkboxes.forEach(checkbox => {
        checkbox.checked = true;
        checkbox.dispatchEvent(new Event('change'));
    });
}

function selectByCategory(roleCode, category) {
    const checkboxes = document.querySelectorAll(`[data-role="${roleCode}"][data-category="${category}"]`);
    checkboxes.forEach(checkbox => {
        checkbox.checked = true;
        checkbox.dispatchEvent(new Event('change'));
    });
}

function selectPageAll(roleCode, pageName) {
    const checkboxes = document.querySelectorAll(`[data-role="${roleCode}"][data-page="${pageName}"]`);
    checkboxes.forEach(checkbox => {
        checkbox.checked = true;
        checkbox.dispatchEvent(new Event('change'));
    });
}

function deselectPageAll(roleCode, pageName) {
    const checkboxes = document.querySelectorAll(`[data-role="${roleCode}"][data-page="${pageName}"]`);
    checkboxes.forEach(checkbox => {
        checkbox.checked = false;
        checkbox.dispatchEvent(new Event('change'));
    });
}

function saveRoleTemplate(roleCode) {
    const checkboxes = document.querySelectorAll(`[data-role="${roleCode}"]`);
    const permissions = {};
    
    checkboxes.forEach(checkbox => {
        const pageName = checkbox.dataset.page;
        const actionCode = checkbox.dataset.action;
        
        if (!permissions[pageName]) {
            permissions[pageName] = {};
        }
        
        permissions[pageName][actionCode] = checkbox.checked;
    });
    
    // Show loading state
    const saveButton = event.target;
    const originalText = saveButton.innerHTML;
    saveButton.innerHTML = '<span>⟳</span>Saving...';
    saveButton.disabled = true;
    
    fetch('{% url "users:save_role_template" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
        },
        body: JSON.stringify({
            role: roleCode,
            permissions: permissions
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Show success message
            showNotification('success', data.message);
            
            // Update role statistics
            updateRoleStats(roleCode, data.stats);
        } else {
            showNotification('error', data.error || 'Failed to save role template');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('error', 'An error occurred while saving the role template');
    })
    .finally(() => {
        // Restore button state
        saveButton.innerHTML = originalText;
        saveButton.disabled = false;
    });
}

function showNotification(type, message) {
    // Create notification element
    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);
    
    // Auto-remove after 5 seconds
    setTimeout(() => {
        if (notification.parentElement) {
            notification.remove();
        }
    }, 5000);
}

function updateRoleStats(roleCode, stats) {
    // Update the role statistics display
    const roleStatElement = document.querySelector(`[data-role="${roleCode}"] .inline-flex`);
    if (roleStatElement) {
        roleStatElement.textContent = stats.allowed || 0;
    }
}

// Add visual feedback for permission changes
document.addEventListener('change', function(e) {
    if (e.target.classList.contains('permission-checkbox')) {
        const label = e.target.parentElement;
        if (e.target.checked) {
            label.classList.add('bg-green-50', 'border-green-200');
            label.classList.remove('bg-gray-50');
        } else {
            label.classList.remove('bg-green-50', 'border-green-200');
            label.classList.add('bg-gray-50');
        }
    }
});

function openCloneModal() {
    document.getElementById('cloneModal').classList.remove('hidden');
}

function closeCloneModal() {
    document.getElementById('cloneModal').classList.add('hidden');
}

function executeClone() {
    const sourceRole = document.getElementById('sourceRole').value;
    const targetRole = document.getElementById('targetRole').value;
    const overwrite = document.getElementById('overwriteExisting').checked;
    
    if (sourceRole === targetRole) {
        showNotification('error', 'Source and target roles cannot be the same');
        return;
    }
    
    fetch('{% url "users:clone_role_template" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
        },
        body: JSON.stringify({
            source_role: sourceRole,
            target_role: targetRole,
            overwrite: overwrite
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('success', data.message);
            closeCloneModal();
            // Refresh the page to show updated permissions
            setTimeout(() => location.reload(), 1000);
        } else {
            showNotification('error', data.error || 'Failed to clone role template');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('error', 'An error occurred while cloning the role template');
    });
}
</script>

<style>
.role-tab.active {
    border-color: #3B82F6;
    color: #3B82F6;
}

.permission-checkbox:checked + span {
    font-weight: 600;
    color: #059669;
}

.hover\:bg-gray-50:hover {
    background-color: #f9fafb;
}

.bg-green-50 {
    background-color: #f0fdf4;
}

.border-green-200 {
    border-color: #bbf7d0;
}
</style>

{% csrf_token %}
{% endblock %}