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

{% block title %}Role Comparison{% 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-balance-scale text-primary mr-2"></i>
                        Role Comparison: {{ role1_name }} vs {{ role2_name }}
                    </h3>
                    <p class="mt-1 max-w-2xl text-sm text-gray-500">
                        Compare permissions between different roles to identify differences and similarities.
                    </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 Configuration
                    </a>
                    <button onclick="openCloneModal()" 
                            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>
                        Clone Permissions
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Role Selection -->
    <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">Compare Different Roles</h4>
            <form method="get" class="flex items-end space-x-4">
                <div class="flex-1">
                    <label for="role1" class="block text-sm font-medium text-gray-700">First Role</label>
                    <select name="role1" id="role1" 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 }}" {% if role_code == role1 %}selected{% endif %}>{{ role_name }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="flex-1">
                    <label for="role2" class="block text-sm font-medium text-gray-700">Second Role</label>
                    <select name="role2" id="role2" 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 }}" {% if role_code == role2 %}selected{% endif %}>{{ role_name }}</option>
                        {% endfor %}
                    </select>
                </div>
                <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">
                    <span>🔍</span>
                    Compare
                </button>
            </form>
        </div>
    </div>

    <!-- Comparison Statistics -->
    <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">Comparison Statistics</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">
                            <i class="fas fa-check-double text-blue-500"></i>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm font-medium text-blue-900">Both Allowed</p>
                            <p class="text-2xl font-semibold text-blue-600">{{ stats.both_allowed }}</p>
                        </div>
                    </div>
                </div>
                
                <div class="bg-green-50 rounded-lg p-4 border border-green-200">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <i class="fas fa-user-check text-green-500"></i>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm font-medium text-green-900">{{ role1_name }} Only</p>
                            <p class="text-2xl font-semibold text-green-600">{{ stats.role1_only }}</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">{{ role2_name }} Only</p>
                            <p class="text-2xl font-semibold text-yellow-600">{{ stats.role2_only }}</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">
                            <i class="fas fa-ban text-gray-500"></i>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm font-medium text-gray-900">Neither Allowed</p>
                            <p class="text-2xl font-semibold text-gray-600">{{ stats.neither_allowed }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Comparison Filters -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:p-6">
            <div class="flex flex-wrap items-center justify-between gap-4">
                <div class="flex items-center space-x-4">
                    <div>
                        <label for="pageFilter" class="block text-sm font-medium text-gray-700">Filter by Page</label>
                        <select id="pageFilter" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary">
                            <option value="">All Pages</option>
                            {% for page_name in comparison_data.keys %}
                            <option value="{{ page_name }}">{{ page_name|title }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div>
                        <label for="statusFilter" class="block text-sm font-medium text-gray-700">Filter by Status</label>
                        <select id="statusFilter" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary">
                            <option value="">All Statuses</option>
                            <option value="both">Both Allowed</option>
                            <option value="role1_only">{{ role1_name }} Only</option>
                            <option value="role2_only">{{ role2_name }} Only</option>
                            <option value="neither">Neither Allowed</option>
                        </select>
                    </div>
                </div>
                <button onclick="clearFilters()" 
                        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">
                    <span>✕</span>Clear Filters
                </button>
            </div>
        </div>
    </div>

    <!-- Detailed Comparison -->
    <div class="bg-white shadow rounded-lg overflow-hidden">
        <div class="px-4 py-5 sm:p-6">
            <h4 class="text-lg font-medium text-gray-900 mb-4">Detailed Permission Comparison</h4>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Permission
                            </th>
                            <th scope="col" class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                                {{ role1_name }}
                            </th>
                            <th scope="col" class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                                {{ role2_name }}
                            </th>
                            <th scope="col" class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Status
                            </th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        {% for page_name, page_permissions in comparison_data.items %}
                        <!-- Page Header -->
                        <tr class="bg-gray-100 page-header" data-page="{{ page_name }}">
                            <td colspan="4" class="px-6 py-3 text-sm font-medium text-gray-900">
                                <div class="flex items-center">
                                    {% if 'dashboard' in page_name %}
                                    <i class="fas fa-tachometer-alt text-blue-500 mr-2"></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 }} Page
                                </div>
                            </td>
                        </tr>
                        
                        {% for action_code, perm_data in page_permissions.items %}
                        <tr class="permission-row hover:bg-gray-50" 
                            data-page="{{ page_name }}" 
                            data-status="{{ perm_data.status }}">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0">
                                        {% if perm_data.category == 'view' %}
                                        <i class="fas fa-eye text-blue-400"></i>
                                        {% elif perm_data.category == 'create' %}
                                        <span>+</span>
                                        {% elif perm_data.category == 'edit' %}
                                        <span>✏️</span>
                                        {% elif perm_data.category == 'delete' %}
                                        <span>🗑️</span>
                                        {% elif perm_data.category == 'approve' %}
                                        <span>✓</span>
                                        {% elif perm_data.category == 'export' %}
                                        <span>⬇️</span>
                                        {% else %}
                                        <span>⚙️</span>
                                        {% endif %}
                                    </div>
                                    <div class="ml-3">
                                        <div class="text-sm font-medium text-gray-900">{{ perm_data.action_name }}</div>
                                        <div class="text-xs text-gray-500">{{ perm_data.category|title }}</div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-center">
                                {% if perm_data.role1_allowed %}
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                    <span>✓</span>Allowed
                                </span>
                                {% else %}
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                    <span>✕</span>Denied
                                </span>
                                {% endif %}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-center">
                                {% if perm_data.role2_allowed %}
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                    <span>✓</span>Allowed
                                </span>
                                {% else %}
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                    <span>✕</span>Denied
                                </span>
                                {% endif %}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-center">
                                {% if perm_data.status == 'both' %}
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                    <i class="fas fa-check-double mr-1"></i>Both
                                </span>
                                {% elif perm_data.status == 'role1_only' %}
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                    <i class="fas fa-user-check mr-1"></i>{{ role1_name }} Only
                                </span>
                                {% elif perm_data.status == 'role2_only' %}
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                    <span>👤+</span>{{ role2_name }} Only
                                </span>
                                {% else %}
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                                    <i class="fas fa-ban mr-1"></i>Neither
                                </span>
                                {% endif %}
                            </td>
                        </tr>
                        {% endfor %}
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Clone 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 Permissions</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">
                            <option value="{{ role1 }}">{{ role1_name }}</option>
                            <option value="{{ role2 }}">{{ role2_name }}</option>
                        </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 Permissions
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    setupFilters();
});

function setupFilters() {
    const pageFilter = document.getElementById('pageFilter');
    const statusFilter = document.getElementById('statusFilter');
    
    [pageFilter, statusFilter].forEach(filter => {
        filter.addEventListener('change', applyFilters);
    });
}

function applyFilters() {
    const pageFilter = document.getElementById('pageFilter').value;
    const statusFilter = document.getElementById('statusFilter').value;
    
    const rows = document.querySelectorAll('.permission-row');
    const headers = document.querySelectorAll('.page-header');
    
    rows.forEach(row => {
        let show = true;
        
        if (pageFilter && row.dataset.page !== pageFilter) {
            show = false;
        }
        
        if (statusFilter && row.dataset.status !== statusFilter) {
            show = false;
        }
        
        row.style.display = show ? '' : 'none';
    });
    
    // Show/hide page headers based on visible rows
    headers.forEach(header => {
        const page = header.dataset.page;
        const visibleRows = document.querySelectorAll(`.permission-row[data-page="${page}"]`);
        const hasVisibleRows = Array.from(visibleRows).some(row => row.style.display !== 'none');
        header.style.display = hasVisibleRows ? '' : 'none';
    });
}

function clearFilters() {
    document.getElementById('pageFilter').value = '';
    document.getElementById('statusFilter').value = '';
    applyFilters();
}

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) {
        alert('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) {
            alert('Role permissions cloned successfully!');
            closeCloneModal();
        } else {
            alert('Error: ' + (data.error || 'Failed to clone role permissions'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred while cloning role permissions');
    });
}
</script>

{% csrf_token %}
{% endblock %}