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

{% block title %}Apply Role Template - {{ user.get_full_name }}{% 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>
                        Apply Role Template
                    </h3>
                    <p class="mt-1 max-w-2xl text-sm text-gray-500">
                        Apply role template permissions to {{ user.get_full_name }} ({{ user.get_role_display }})
                    </p>
                </div>
                <div class="flex space-x-2">
                    <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>
                    <a href="{% url 'users:resolve_permission_conflicts' user.id %}"
                        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>
                        Resolve Conflicts
                    </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 %}

    <!-- User Information -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:p-6">
            <div class="flex items-center space-x-4">
                <div class="flex-shrink-0 h-16 w-16">
                    {% if user.profile_image %}
                    <img class="h-16 w-16 rounded-full object-cover" src="{{ user.profile_image.url }}" alt="{{ user.get_full_name }}">
                    {% elif user.selfie %}
                    <img class="h-16 w-16 rounded-full object-cover" src="{{ user.selfie.url }}" alt="{{ user.get_full_name }}">
                    {% else %}
                    <div class="h-16 w-16 rounded-full bg-gray-300 flex items-center justify-center">
                        <span class="text-xl font-medium text-gray-700">{{ user.get_initials }}</span>
                    </div>
                    {% endif %}
                </div>
                <div class="flex-1">
                    <h4 class="text-xl font-medium text-gray-900">{{ user.get_full_name }}</h4>
                    <p class="text-sm text-gray-500">{{ user.email }}</p>
                    <p class="text-sm text-gray-500">{{ user.phone_number }}</p>
                    <div class="mt-2">
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                            <span>🏷️</span>{{ user.get_role_display }}
                        </span>
                    </div>
                </div>
                <div class="text-right">
                    <div class="text-sm text-gray-500">Current Permissions</div>
                    <div class="text-2xl font-semibold text-primary">{{ current_permissions.allowed_permissions|default:0 }}</div>
                    <div class="text-xs text-gray-400">of {{ current_permissions.total_permissions|default:0 }} total</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Template 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>
                Apply Role Template
            </h4>
            
            <form id="applyTemplateForm" class="space-y-6">
                {% csrf_token %}
                
                <!-- Role Template Selection -->
                <div>
                    <label for="roleTemplate" class="block text-sm font-medium text-gray-700">
                        Select Role Template
                    </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">
                        {% for role_code, role_name in available_roles %}
                        <option value="{{ role_code }}" {% if role_code == user.role %}selected{% endif %}>
                            {{ role_name }}
                            {% if role_code == user.role %} (Current Role){% endif %}
                        </option>
                        {% endfor %}
                    </select>
                    <p class="mt-2 text-sm text-gray-500">
                        Choose which role template to apply to this user. This will set their permissions based on the selected role's default template.
                    </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 with the role template. 
                        If unchecked, only missing permissions will be added.
                    </p>
                    
                    <div class="flex items-center">
                        <input id="createRollback" name="create_rollback" type="checkbox" checked class="rounded border-gray-300 text-primary focus:ring-primary">
                        <label for="createRollback" class="ml-2 text-sm text-gray-700">
                            Create rollback point before applying
                        </label>
                    </div>
                    <p class="text-xs text-gray-500 ml-6">
                        Creates a backup of current permissions that can be restored later if needed.
                    </p>
                </div>

                <!-- Preview Section -->
                <div id="templatePreview" class="border border-gray-200 rounded-lg p-4 bg-gray-50">
                    <h5 class="text-sm font-medium text-gray-900 mb-3">Template Preview</h5>
                    <div id="previewContent" class="text-sm text-gray-600">
                        Select a role template to see preview...
                    </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="button" onclick="previewTemplate()"
                            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">
                        <i class="fas fa-eye mr-2"></i>
                        Preview Changes
                    </button>
                    <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 Template
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Current Permissions Summary -->
    <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>
                Current Permissions Summary
            </h4>
            
            <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
                <div class="bg-blue-50 rounded-lg p-4 border border-blue-200">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <span>✓</span>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm font-medium text-blue-900">Allowed</p>
                            <p class="text-2xl font-semibold text-blue-600">{{ current_permissions.allowed_permissions|default:0 }}</p>
                        </div>
                    </div>
                </div>
                
                <div class="bg-red-50 rounded-lg p-4 border border-red-200">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <span>✕</span>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm font-medium text-red-900">Denied</p>
                            <p class="text-2xl font-semibold text-red-600">{{ current_permissions.denied_permissions|default:0 }}</p>
                        </div>
                    </div>
                </div>
                
                <div class="bg-yellow-50 rounded-lg p-4 border border-yellow-200">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <span>⚠️</span>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm font-medium text-yellow-900">Critical</p>
                            <p class="text-2xl font-semibold text-yellow-600">{{ current_permissions.has_critical_permissions|yesno:"Yes,No" }}</p>
                        </div>
                    </div>
                </div>
                
                <div class="bg-gray-50 rounded-lg p-4 border border-gray-200">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <span>⚙️</span>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm font-medium text-gray-900">Total</p>
                            <p class="text-2xl font-semibold text-gray-600">{{ current_permissions.total_permissions|default:0 }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Load initial preview
    previewTemplate();
    
    // Update preview when role changes
    document.getElementById('roleTemplate').addEventListener('change', previewTemplate);
});

function previewTemplate() {
    const roleSelect = document.getElementById('roleTemplate');
    const selectedRole = roleSelect.value;
    const previewContent = document.getElementById('previewContent');
    
    if (!selectedRole) {
        previewContent.innerHTML = 'Select a role template to see preview...';
        return;
    }
    
    previewContent.innerHTML = '<span>⟳</span>Loading preview...';
    
    fetch(`{% url "users:get_role_template_data" "PLACEHOLDER" %}`.replace('PLACEHOLDER', selectedRole))
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                let html = `
                    <div class="mb-3">
                        <h6 class="font-medium text-gray-900">${data.role_name} Template</h6>
                        <p class="text-xs text-gray-500">
                            ${data.stats.allowed_permissions} of ${data.stats.total_permissions} permissions allowed (${data.stats.percentage}%)
                        </p>
                    </div>
                `;
                
                // Show permission breakdown by page
                const templateData = data.template_data;
                for (const [pageName, actions] of Object.entries(templateData)) {
                    const allowedCount = Object.values(actions).filter(perm => perm.is_allowed).length;
                    const totalCount = Object.keys(actions).length;
                    
                    html += `
                        <div class="mb-2">
                            <div class="flex justify-between items-center">
                                <span class="text-xs font-medium text-gray-700">${pageName.charAt(0).toUpperCase() + pageName.slice(1)}</span>
                                <span class="text-xs text-gray-500">${allowedCount}/${totalCount}</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-1">
                                <div class="bg-primary h-1 rounded-full" style="width: ${totalCount > 0 ? (allowedCount / totalCount * 100) : 0}%"></div>
                            </div>
                        </div>
                    `;
                }
                
                previewContent.innerHTML = html;
            } else {
                previewContent.innerHTML = `<span class="text-red-600">Error loading preview: ${data.error}</span>`;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            previewContent.innerHTML = '<span class="text-red-600">Error loading preview</span>';
        });
}

document.getElementById('applyTemplateForm').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 createRollback = formData.get('create_rollback') === 'on';
    
    // Confirm action
    if (!confirm(`Are you sure you want to apply the ${document.querySelector(`option[value="${roleTemplate}"]`).textContent} template to {{ user.get_full_name }}?`)) {
        return;
    }
    
    // Show loading state
    const submitButton = this.querySelector('button[type="submit"]');
    const originalText = submitButton.innerHTML;
    submitButton.innerHTML = '<span>⟳</span>Applying...';
    submitButton.disabled = true;
    
    // Create rollback point if requested
    let rollbackPromise = Promise.resolve();
    if (createRollback) {
        rollbackPromise = fetch('{% url "users:create_rollback_point" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
            },
            body: JSON.stringify({
                role: '{{ user.role }}'
            })
        });
    }
    
    rollbackPromise
        .then(() => {
            // Apply template
            return fetch('{% url "users:apply_role_template_to_user" user.id %}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                },
                body: JSON.stringify({
                    role_template: roleTemplate,
                    update_existing: updateExisting
                })
            });
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('success', data.message);
                
                // Update current permissions display
                setTimeout(() => {
                    location.reload();
                }, 2000);
            } else {
                showNotification('error', data.error || 'Failed to apply role template');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('error', 'An error occurred while applying the role template');
        })
        .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 %}