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

{% block title %}Permission Usage Analytics{% endblock %}

{% block extra_css %}
<link href="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.css" rel="stylesheet">
<style>
    .analytics-card {
        background: white;
        border-radius: 10px;
        padding: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
    }
    
    .suggestion-card {
        border-left: 4px solid #007bff;
        padding: 15px;
        margin-bottom: 15px;
        background: #f8f9fa;
        border-radius: 0 5px 5px 0;
    }
    
    .suggestion-card.cleanup {
        border-left-color: #6c757d;
    }
    
    .suggestion-card.role_adjustment {
        border-left-color: #ffc107;
    }
    
    .suggestion-card.training {
        border-left-color: #dc3545;
    }
    
    .impact-badge {
        padding: 3px 8px;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 500;
    }
    
    .impact-low {
        background: #d4edda;
        color: #155724;
    }
    
    .impact-medium {
        background: #fff3cd;
        color: #856404;
    }
    
    .impact-high {
        background: #f8d7da;
        color: #721c24;
    }
    
    .permission-row {
        padding: 10px 0;
        border-bottom: 1px solid #eee;
    }
    
    .permission-row:last-child {
        border-bottom: none;
    }
    
    .grant-rate-bar {
        height: 20px;
        background: #e9ecef;
        border-radius: 10px;
        overflow: hidden;
        position: relative;
    }
    
    .grant-rate-fill {
        height: 100%;
        background: linear-gradient(90deg, #dc3545 0%, #ffc107 50%, #28a745 100%);
        transition: width 0.3s ease;
    }
    
    .grant-rate-text {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 0.8rem;
        font-weight: bold;
        color: #495057;
    }
    
    .unused-permission {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 5px;
        padding: 8px 12px;
        margin: 5px;
        display: inline-block;
        font-size: 0.85rem;
    }
    
    .role-stats {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 15px;
    }
    
    .chart-container {
        position: relative;
        height: 300px;
        margin-bottom: 20px;
    }
    
    .export-section {
        margin-bottom: 20px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><span>🔑</span> Permission Usage Analytics</h2>
                <div class="d-flex align-items-center">
                    <div class="btn-group mr-3">
                        <a href="?days=30" class="btn btn-outline-primary {% if days == 30 %}active{% endif %}">30 Days</a>
                        <a href="?days=90" class="btn btn-outline-primary {% if days == 90 %}active{% endif %}">90 Days</a>
                        <a href="?days=180" class="btn btn-outline-primary {% if days == 180 %}active{% endif %}">180 Days</a>
                    </div>
                    <div class="export-section">
                        <div class="btn-group">
                            <button type="button" class="btn btn-outline-success dropdown-toggle" data-toggle="dropdown">
                                <span>⬇️</span> Export
                            </button>
                            <div class="dropdown-menu">
                                <a class="dropdown-item" href="#" onclick="exportReport('csv')">
                                    <i class="fas fa-file-csv"></i> Export as CSV
                                </a>
                                <a class="dropdown-item" href="#" onclick="exportReport('pdf')">
                                    <span>📄</span> Export as PDF
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Optimization Suggestions -->
    {% if suggestions %}
    <div class="row">
        <div class="col-12">
            <div class="analytics-card">
                <h5><span>💡</span> Optimization Suggestions</h5>
                {% for suggestion in suggestions %}
                <div class="suggestion-card {{ suggestion.type }}">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6>{{ suggestion.title }}</h6>
                            <p class="mb-2">{{ suggestion.description }}</p>
                            {% if suggestion.permissions %}
                            <div class="mt-2">
                                <small class="text-muted">Affected permissions:</small>
                                <div class="mt-1">
                                    {% for permission in suggestion.permissions %}
                                    <span class="unused-permission">{{ permission }}</span>
                                    {% endfor %}
                                </div>
                            </div>
                            {% endif %}
                        </div>
                        <div>
                            <span class="impact-badge impact-{{ suggestion.impact }}">{{ suggestion.impact|title }} Impact</span>
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>
    {% endif %}
    
    <!-- Permission Usage Overview -->
    <div class="row">
        <div class="col-md-8">
            <div class="analytics-card">
                <h5><span>📊</span> Permission Usage Frequency</h5>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Permission</th>
                                <th>Total Checks</th>
                                <th>Granted</th>
                                <th>Denied</th>
                                <th>Users</th>
                                <th>Grant Rate</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for usage in permission_usage %}
                            <tr>
                                <td>
                                    <code>{{ usage.permission_checked }}</code>
                                </td>
                                <td>{{ usage.total_checks }}</td>
                                <td><span class="text-success">{{ usage.granted_count }}</span></td>
                                <td><span class="text-danger">{{ usage.denied_count }}</span></td>
                                <td>{{ usage.unique_users }}</td>
                                <td>
                                    {% with grant_rate=usage.granted_count|floatformat:0|add:0 total=usage.total_checks|floatformat:0|add:0 %}
                                    {% if total > 0 %}
                                    {% widthratio grant_rate total 100 as percentage %}
                                    <div class="grant-rate-bar">
                                        <div class="grant-rate-fill" style="width: {{ percentage }}%"></div>
                                        <div class="grant-rate-text">{{ percentage }}%</div>
                                    </div>
                                    {% else %}
                                    <span class="text-muted">N/A</span>
                                    {% endif %}
                                    {% endwith %}
                                </td>
                            </tr>
                            {% empty %}
                            <tr>
                                <td colspan="6" class="text-center text-muted">No permission usage data available</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="analytics-card">
                <h5><span>📊</span> Most Denied Permissions</h5>
                <canvas id="deniedPermissionsChart"></canvas>
            </div>
        </div>
    </div>
    
    <!-- Role Permission Changes -->
    <div class="row">
        <div class="col-md-6">
            <div class="analytics-card">
                <h5><i class="fas fa-users-cog"></i> Permission Changes by Role</h5>
                {% for role in role_permission_changes %}
                <div class="role-stats">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="mb-1">{{ role.user__role|title }}</h6>
                            <small>{{ role.total_changes }} total changes</small>
                        </div>
                        <div class="text-right">
                            <div><span class="badge badge-light">+{{ role.grants }} grants</span></div>
                            <div><span class="badge badge-light">-{{ role.revokes }} revokes</span></div>
                        </div>
                    </div>
                </div>
                {% empty %}
                <p class="text-muted text-center">No role permission changes in this period</p>
                {% endfor %}
            </div>
        </div>
        <div class="col-md-6">
            <div class="analytics-card">
                <h5><i class="fas fa-user-times"></i> Users with Most Denials</h5>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>User</th>
                                <th>Role</th>
                                <th>Denials</th>
                                <th>Permissions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for user in users_with_denials %}
                            <tr>
                                <td>{{ user.user__first_name }} {{ user.user__last_name }}</td>
                                <td><span class="badge badge-secondary">{{ user.user__role|title }}</span></td>
                                <td><span class="badge badge-danger">{{ user.denial_count }}</span></td>
                                <td>{{ user.unique_permissions }}</td>
                            </tr>
                            {% empty %}
                            <tr>
                                <td colspan="4" class="text-center text-muted">No denial data available</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Unused Permissions -->
    {% if unused_permissions %}
    <div class="row">
        <div class="col-12">
            <div class="analytics-card">
                <h5><i class="fas fa-trash-alt"></i> Unused Permissions ({{ unused_permissions|length }} total)</h5>
                <p class="text-muted mb-3">These permissions haven't been checked in the last {{ days }} days and may be candidates for removal:</p>
                <div>
                    {% for permission in unused_permissions %}
                    <span class="unused-permission">{{ permission }}</span>
                    {% endfor %}
                </div>
                <div class="mt-3">
                    <button class="btn btn-outline-warning" onclick="showCleanupModal()">
                        <i class="fas fa-broom"></i> Suggest Cleanup
                    </button>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
    
    <!-- Permission Trends -->
    <div class="row">
        <div class="col-12">
            <div class="analytics-card">
                <h5><span>📈</span> Permission Usage Trends</h5>
                <div class="chart-container">
                    <canvas id="usageTrendsChart"></canvas>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Detailed Analysis -->
    <div class="row">
        <div class="col-12">
            <div class="analytics-card">
                <h5><i class="fas fa-microscope"></i> Detailed Permission Analysis</h5>
                <div class="row">
                    <div class="col-md-4">
                        <div class="text-center p-3 border rounded">
                            <h3 class="text-primary">{{ permission_usage|length }}</h3>
                            <small class="text-muted">Active Permissions</small>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="text-center p-3 border rounded">
                            <h3 class="text-warning">{{ unused_permissions|length }}</h3>
                            <small class="text-muted">Unused Permissions</small>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="text-center p-3 border rounded">
                            <h3 class="text-success">
                                {% if permission_usage %}
                                {% with total_checks=0 total_granted=0 %}
                                {% for usage in permission_usage %}
                                {% with total_checks=total_checks|add:usage.total_checks total_granted=total_granted|add:usage.granted_count %}
                                {% endwith %}
                                {% endfor %}
                                {% if total_checks > 0 %}
                                {% widthratio total_granted total_checks 100 %}%
                                {% else %}
                                0%
                                {% endif %}
                                {% endwith %}
                                {% else %}
                                0%
                                {% endif %}
                            </h3>
                            <small class="text-muted">Average Grant Rate</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Cleanup Suggestions Modal -->
<div class="modal fade" id="cleanupModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Permission Cleanup Suggestions</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <span>⚠️</span>
                    <strong>Warning:</strong> Removing permissions can affect system functionality. Please review carefully before proceeding.
                </div>
                <h6>Recommended Actions:</h6>
                <ul>
                    <li>Review unused permissions with your development team</li>
                    <li>Test permission removal in a staging environment first</li>
                    <li>Create a backup of current permission settings</li>
                    <li>Monitor system functionality after changes</li>
                </ul>
                <h6>Unused Permissions ({{ unused_permissions|length }}):</h6>
                <div class="row">
                    {% for permission in unused_permissions %}
                    <div class="col-md-6">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" value="{{ permission }}" id="perm_{{ forloop.counter }}">
                            <label class="form-check-label" for="perm_{{ forloop.counter }}">
                                <code>{{ permission }}</code>
                            </label>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-warning" onclick="generateCleanupScript()">
                    <i class="fas fa-file-code"></i> Generate Cleanup Script
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Denied Permissions Chart
    const deniedCtx = document.getElementById('deniedPermissionsChart').getContext('2d');
    const deniedData = {
        labels: [
            {% for denied in most_denied|slice:":5" %}
            '{{ denied.permission_checked|truncatechars:20 }}'{% if not forloop.last %},{% endif %}
            {% endfor %}
        ],
        datasets: [{
            data: [
                {% for denied in most_denied|slice:":5" %}
                {{ denied.denied_count }}{% if not forloop.last %},{% endif %}
                {% endfor %}
            ],
            backgroundColor: [
                '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF'
            ]
        }]
    };
    
    new Chart(deniedCtx, {
        type: 'doughnut',
        data: deniedData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
    
    // Usage Trends Chart (placeholder - would need time series data)
    const trendsCtx = document.getElementById('usageTrendsChart').getContext('2d');
    const trendsData = {
        labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
        datasets: [{
            label: 'Permission Checks',
            data: [120, 150, 180, 200],
            borderColor: '#007bff',
            backgroundColor: 'rgba(0, 123, 255, 0.1)',
            tension: 0.4
        }, {
            label: 'Denied Requests',
            data: [20, 25, 15, 18],
            borderColor: '#dc3545',
            backgroundColor: 'rgba(220, 53, 69, 0.1)',
            tension: 0.4
        }]
    };
    
    new Chart(trendsCtx, {
        type: 'line',
        data: trendsData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
});

function exportReport(format) {
    const params = new URLSearchParams(window.location.search);
    params.set('type', 'permission_usage');
    params.set('format', format);
    
    const exportUrl = '{% url "users:export_audit_report" %}?' + params.toString();
    window.open(exportUrl, '_blank');
}

function showCleanupModal() {
    $('#cleanupModal').modal('show');
}

function generateCleanupScript() {
    const selectedPermissions = [];
    const checkboxes = document.querySelectorAll('#cleanupModal input[type="checkbox"]:checked');
    
    checkboxes.forEach(checkbox => {
        selectedPermissions.push(checkbox.value);
    });
    
    if (selectedPermissions.length === 0) {
        alert('Please select at least one permission to include in the cleanup script.');
        return;
    }
    
    // Generate cleanup script
    let script = `# Permission Cleanup Script
# Generated on: ${new Date().toISOString()}
# Selected permissions for removal: ${selectedPermissions.length}

from users.enhanced_permissions_models import PagePermission

# Permissions to remove
permissions_to_remove = [
`;
    
    selectedPermissions.forEach(permission => {
        script += `    '${permission}',\n`;
    });
    
    script += `]

# Remove unused permissions
for permission_code in permissions_to_remove:
    try:
        permission = PagePermission.objects.get(action_code=permission_code)
        print(f"Removing permission: {permission_code}")
        permission.delete()
    except PagePermission.DoesNotExist:
        print(f"Permission not found: {permission_code}")

print("Cleanup completed!")
`;
    
    // Download script
    const blob = new Blob([script], { type: 'text/plain' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'permission_cleanup_script.py';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
    
    $('#cleanupModal').modal('hide');
}
</script>
{% endblock %}