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

{% block title %}Default Role Permissions{% 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>
                    <h1 class="text-2xl font-bold text-gray-900">
                        <i class="fas fa-shield-alt text-primary mr-3"></i>
                        Default Role Permissions
                    </h1>
                    <p class="mt-2 text-sm text-gray-600">
                        Configure default permissions for each staff role. These will be automatically applied to new staff members.
                    </p>
                </div>
                <div class="flex space-x-3">
                    <a href="{% url 'users:staff_dashboard' %}" 
                       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">
                        <span>←</span>
                        Back to Dashboard
                    </a>
                    <a href="{% url 'users:permission_templates' %}" 
                       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">
                        <span>📋</span>
                        Permission Templates
                    </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 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 in staff_roles %}
                <button onclick="showRolePermissions('{{ role }}')" 
                        id="tab-{{ role }}"
                        class="role-tab whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm {% if forloop.first %}border-primary text-primary{% else %}border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300{% endif %}">
                    <i class="fas fa-{% if role == 'admin' %}crown{% elif role == 'team_leader' %}user-tie{% elif role == 'loan_officer' %}handshake{% else %}user-secret{% endif %} mr-2"></i>
                    {{ role|title|replace:"_":" " }}
                </button>
                {% endfor %}
            </nav>
        </div>

        <!-- Permission Forms -->
        {% for role in staff_roles %}
        <div id="permissions-{{ role }}" class="role-permissions {% if not forloop.first %}hidden{% endif %}">
            <form method="post" class="p-6">
                {% csrf_token %}
                <input type="hidden" name="role" value="{{ role }}">
                
                <div class="mb-6">
                    <div class="flex justify-between items-center">
                        <h3 class="text-lg font-medium text-gray-900">
                            {{ role|title|replace:"_":" " }} Default Permissions
                        </h3>
                        <div class="flex space-x-2">
                            <button type="button" onclick="selectAllPermissions('{{ role }}')" 
                                    class="text-sm text-primary hover:text-primary-dark">
                                Select All
                            </button>
                            <span class="text-gray-300">|</span>
                            <button type="button" onclick="deselectAllPermissions('{{ role }}')" 
                                    class="text-sm text-primary hover:text-primary-dark">
                                Deselect All
                            </button>
                        </div>
                    </div>
                    <p class="mt-1 text-sm text-gray-600">
                        These permissions will be automatically assigned to new {{ role|title|replace:"_":" " }} users.
                    </p>
                </div>

                <div class="space-y-6">
                    {% for module_choice in modules %}
                    {% with module=module_choice.0 module_name=module_choice.1 %}
                    <div class="border border-gray-200 rounded-lg p-4">
                        <div class="flex justify-between items-center mb-3">
                            <h4 class="text-md font-medium text-gray-900">
                                <i class="fas fa-{{ module|get_module_icon }} text-primary mr-2"></i>
                                {{ module_name }}
                            </h4>
                            <div class="flex space-x-2">
                                <button type="button" onclick="selectModulePermissions('{{ role }}', '{{ module }}')" 
                                        class="text-xs text-blue-600 hover:text-blue-800">
                                    All
                                </button>
                                <span class="text-gray-300">|</span>
                                <button type="button" onclick="deselectModulePermissions('{{ role }}', '{{ module }}')" 
                                        class="text-xs text-blue-600 hover:text-blue-800">
                                    None
                                </button>
                            </div>
                        </div>
                        <div class="grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-5">
                            {% for action_choice in actions %}
                            {% with action=action_choice.0 action_name=action_choice.1 %}
                            <label class="flex items-center">
                                <input type="checkbox" 
                                       name="default_{{ role }}_{{ module }}_{{ action }}" 
                                       id="perm_{{ role }}_{{ module }}_{{ action }}"
                                       {% if default_permissions|get_item:role|get_item:module|get_item:action %}checked{% endif %}
                                       class="rounded border-gray-300 text-primary focus:ring-primary">
                                <span class="ml-2 text-sm text-gray-700">{{ action_name }}</span>
                            </label>
                            {% endwith %}
                            {% endfor %}
                        </div>
                    </div>
                    {% endwith %}
                    {% endfor %}
                </div>

                <div class="mt-6 flex justify-end space-x-3">
                    <button type="button" onclick="resetToDefaults('{{ role }}')" 
                            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">
                        <span>↶</span>
                        Reset to System Defaults
                    </button>
                    <button type="submit" 
                            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 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                        <span>💾</span>
                        Save Default Permissions
                    </button>
                </div>
            </form>
        </div>
        {% endfor %}
    </div>

    <!-- Bulk Actions -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:p-6">
            <h3 class="text-lg font-medium text-gray-900 mb-4">
                <span>⚡</span>
                Bulk Actions
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <button onclick="applyDefaultsToAllUsers()" 
                        class="flex items-center justify-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                    <span>👥</span>
                    <div class="text-left">
                        <p class="font-medium text-gray-900">Apply to All Users</p>
                        <p class="text-sm text-gray-500">Update all existing staff</p>
                    </div>
                </button>
                
                <button onclick="exportPermissions()" 
                        class="flex items-center justify-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                    <span>⬇️</span>
                    <div class="text-left">
                        <p class="font-medium text-gray-900">Export Permissions</p>
                        <p class="text-sm text-gray-500">Download as JSON/CSV</p>
                    </div>
                </button>
                
                <button onclick="importPermissions()" 
                        class="flex items-center justify-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                    <span>⬆️</span>
                    <div class="text-left">
                        <p class="font-medium text-gray-900">Import Permissions</p>
                        <p class="text-sm text-gray-500">Upload from file</p>
                    </div>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Confirmation Modal -->
<div id="confirmationModal" 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 text-center">
            <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-yellow-100">
                <span>⚠️</span>
            </div>
            <h3 class="text-lg font-medium text-gray-900 mt-2" id="modalTitle">Confirm Action</h3>
            <div class="mt-2 px-7 py-3">
                <p class="text-sm text-gray-500" id="modalMessage">Are you sure you want to proceed?</p>
            </div>
            <div class="items-center px-4 py-3">
                <button id="confirmButton" 
                        class="px-4 py-2 bg-primary text-white text-base font-medium rounded-md w-24 mr-2 hover:bg-primary-dark focus:outline-none focus:ring-2 focus:ring-primary">
                    Confirm
                </button>
                <button onclick="closeModal()" 
                        class="px-4 py-2 bg-gray-300 text-gray-800 text-base font-medium rounded-md w-24 hover:bg-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-300">
                    Cancel
                </button>
            </div>
        </div>
    </div>
</div>

<script>
// Tab switching
function showRolePermissions(role) {
    // Hide all permission forms
    document.querySelectorAll('.role-permissions').forEach(form => {
        form.classList.add('hidden');
    });
    
    // Remove active class from all tabs
    document.querySelectorAll('.role-tab').forEach(tab => {
        tab.classList.remove('border-primary', 'text-primary');
        tab.classList.add('border-transparent', 'text-gray-500');
    });
    
    // Show selected role permissions
    document.getElementById(`permissions-${role}`).classList.remove('hidden');
    
    // Activate selected tab
    const activeTab = document.getElementById(`tab-${role}`);
    activeTab.classList.remove('border-transparent', 'text-gray-500');
    activeTab.classList.add('border-primary', 'text-primary');
}

// Permission selection helpers
function selectAllPermissions(role) {
    document.querySelectorAll(`#permissions-${role} input[type="checkbox"]`).forEach(checkbox => {
        checkbox.checked = true;
    });
}

function deselectAllPermissions(role) {
    document.querySelectorAll(`#permissions-${role} input[type="checkbox"]`).forEach(checkbox => {
        checkbox.checked = false;
    });
}

function selectModulePermissions(role, module) {
    document.querySelectorAll(`input[name^="default_${role}_${module}_"]`).forEach(checkbox => {
        checkbox.checked = true;
    });
}

function deselectModulePermissions(role, module) {
    document.querySelectorAll(`input[name^="default_${role}_${module}_"]`).forEach(checkbox => {
        checkbox.checked = false;
    });
}

// System defaults (you can customize these)
const systemDefaults = {
    'admin': {
        // Admin gets all permissions
        'all': true
    },
    'team_leader': {
        'dashboard': ['view'],
        'users': ['view', 'create', 'edit'],
        'clients': ['view', 'create', 'edit', 'assign'],
        'loans': ['view', 'create', 'edit', 'approve'],
        'applications': ['view', 'create', 'edit', 'approve', 'reject'],
        'repayments': ['view', 'create', 'edit'],
        'reports': ['view', 'export'],
        'portfolio': ['view', 'manage', 'assign', 'reassign'],
        'notifications': ['view', 'create'],
        'audit': ['view']
    },
    'loan_officer': {
        'dashboard': ['view'],
        'clients': ['view', 'create', 'edit'],
        'loans': ['view', 'create', 'edit'],
        'applications': ['view', 'create', 'edit'],
        'repayments': ['view', 'create'],
        'reports': ['view'],
        'portfolio': ['view'],
        'notifications': ['view']
    },
    'secretary': {
        'dashboard': ['view'],
        'clients': ['view', 'create', 'edit'],
        'documents': ['view', 'create', 'edit', 'upload'],
        'notifications': ['view', 'create'],
        'communications': ['view', 'create']
    }
};

function resetToDefaults(role) {
    showConfirmation(
        'Reset to System Defaults',
        `This will reset all permissions for ${role.replace('_', ' ')} to system defaults. Continue?`,
        () => {
            // First deselect all
            deselectAllPermissions(role);
            
            // Apply system defaults
            const defaults = systemDefaults[role];
            if (defaults.all) {
                selectAllPermissions(role);
            } else {
                for (const [module, actions] of Object.entries(defaults)) {
                    actions.forEach(action => {
                        const checkbox = document.getElementById(`perm_${role}_${module}_${action}`);
                        if (checkbox) {
                            checkbox.checked = true;
                        }
                    });
                }
            }
        }
    );
}

// Bulk actions
function applyDefaultsToAllUsers() {
    showConfirmation(
        'Apply Defaults to All Users',
        'This will update permissions for all existing staff members based on their roles. Custom permissions will be overridden. Continue?',
        () => {
            // Implementation for applying defaults to all users
            fetch('/users/bulk-apply-defaults/', {
                method: 'POST',
                headers: {
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert('Error: ' + data.error);
                }
            });
        }
    );
}

function exportPermissions() {
    window.location.href = '/users/export-permissions/';
}

function importPermissions() {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json,.csv';
    input.onchange = function(e) {
        const file = e.target.files[0];
        if (file) {
            const formData = new FormData();
            formData.append('file', file);
            
            fetch('/users/import-permissions/', {
                method: 'POST',
                headers: {
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert('Error: ' + data.error);
                }
            });
        }
    };
    input.click();
}

// Modal functions
function showConfirmation(title, message, onConfirm) {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalMessage').textContent = message;
    document.getElementById('confirmButton').onclick = () => {
        onConfirm();
        closeModal();
    };
    document.getElementById('confirmationModal').classList.remove('hidden');
}

function closeModal() {
    document.getElementById('confirmationModal').classList.add('hidden');
}

// Template filters (you'll need to implement these in Django)
function getModuleIcon(module) {
    const icons = {
        'dashboard': 'tachometer-alt',
        'users': 'users',
        'clients': 'user-friends',
        'loans': 'money-bill-wave',
        'applications': 'file-contract',
        'repayments': 'hand-holding-usd',
        'reports': 'chart-bar',
        'documents': 'file-alt',
        'settings': 'cogs',
        'notifications': 'bell',
        'audit': 'clipboard-list',
        'kyc': 'id-card',
        'payments': 'credit-card',
        'communications': 'envelope',
        'portfolio': 'briefcase',
        'receipts': 'receipt',
        'statements': 'file-invoice',
        'media': 'images',
        'backup': 'database',
        'system': 'server'
    };
    return icons[module] || 'cog';
}
</script>
{% endblock %}