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

{% block title %}System Activity Analysis{% endblock %}

{% block extra_css %}
<link href="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.css" rel="stylesheet">
<style>
    .analysis-card {
        background: white;
        border-radius: 10px;
        padding: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
    }
    
    .activity-metric {
        text-align: center;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 20px;
        color: white;
    }
    
    .activity-metric.primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }
    
    .activity-metric.success {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }
    
    .activity-metric.warning {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }
    
    .activity-metric.info {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    }
    
    .metric-value {
        font-size: 2.5rem;
        font-weight: bold;
        margin-bottom: 5px;
    }
    
    .metric-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }
    
    .user-row {
        padding: 10px 0;
        border-bottom: 1px solid #eee;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .user-row:last-child {
        border-bottom: none;
    }
    
    .activity-badge {
        background: #007bff;
        color: white;
        padding: 3px 8px;
        border-radius: 12px;
        font-size: 0.8rem;
        margin-left: 5px;
    }
    
    .security-badge {
        background: #dc3545;
        color: white;
        padding: 3px 8px;
        border-radius: 12px;
        font-size: 0.8rem;
        margin-left: 5px;
    }
    
    .pattern-alert {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 5px;
        padding: 15px;
        margin-bottom: 15px;
    }
    
    .pattern-alert.critical {
        background: #f8d7da;
        border-color: #f5c6cb;
    }
    
    .chart-container {
        position: relative;
        height: 300px;
        margin-bottom: 20px;
    }
    
    .module-bar {
        height: 25px;
        background: #e9ecef;
        border-radius: 12px;
        overflow: hidden;
        position: relative;
        margin-bottom: 10px;
    }
    
    .module-fill {
        height: 100%;
        background: linear-gradient(90deg, #007bff, #28a745);
        transition: width 0.3s ease;
    }
    
    .module-text {
        position: absolute;
        top: 50%;
        left: 10px;
        transform: translateY(-50%);
        font-size: 0.8rem;
        font-weight: bold;
        color: #495057;
    }
    
    .module-count {
        position: absolute;
        top: 50%;
        right: 10px;
        transform: translateY(-50%);
        font-size: 0.8rem;
        font-weight: bold;
        color: #495057;
    }
</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> System Activity Analysis</h2>
                <div class="btn-group">
                    <a href="?days=7" class="btn btn-outline-primary {% if days == 7 %}active{% endif %}">7 Days</a>
                    <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>
                </div>
            </div>
        </div>
    </div>
    
    <!-- User Selection -->
    <div class="row">
        <div class="col-12">
            <div class="analysis-card">
                <h5><i class="fas fa-user-search"></i> Analyze Individual User</h5>
                <form method="get" class="form-inline">
                    <select name="user_id" class="form-control mr-2" style="width: 300px;">
                        <option value="">Select a user for detailed analysis...</option>
                        {% for user in users %}
                        <option value="{{ user.id }}">
                            {{ user.get_full_name }} ({{ user.role|title }})
                        </option>
                        {% endfor %}
                    </select>
                    <input type="hidden" name="days" value="{{ days }}">
                    <button type="submit" class="btn btn-primary">
                        <span>🔍</span> Analyze User
                    </button>
                </form>
            </div>
        </div>
    </div>
    
    <!-- System Overview Metrics -->
    <div class="row">
        <div class="col-md-3">
            <div class="activity-metric primary">
                <div class="metric-value">{{ active_users|length }}</div>
                <div class="metric-label">Active Users</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="activity-metric success">
                <div class="metric-value">{{ module_activity|length }}</div>
                <div class="metric-label">Active Modules</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="activity-metric warning">
                <div class="metric-value">{{ after_hours|length }}</div>
                <div class="metric-label">After-Hours Users</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="activity-metric info">
                <div class="metric-value">{{ bulk_operations|length }}</div>
                <div class="metric-label">Bulk Operations</div>
            </div>
        </div>
    </div>
    
    <!-- Most Active Users -->
    <div class="row">
        <div class="col-md-8">
            <div class="analysis-card">
                <h5><span>👥</span> Most Active Users (Last {{ days }} Days)</h5>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>User</th>
                                <th>Role</th>
                                <th>Total Activities</th>
                                <th>Security Events</th>
                                <th>Activity Level</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for user in active_users %}
                            <tr>
                                <td>
                                    <strong>{{ user.user__first_name }} {{ user.user__last_name }}</strong>
                                </td>
                                <td>
                                    <span class="badge badge-secondary">{{ user.user__role|title }}</span>
                                </td>
                                <td>
                                    <span class="activity-badge">{{ user.activity_count }}</span>
                                </td>
                                <td>
                                    {% if user.security_events > 0 %}
                                    <span class="security-badge">{{ user.security_events }}</span>
                                    {% else %}
                                    <span class="text-muted">0</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if user.activity_count > 100 %}
                                    <span class="badge badge-success">High</span>
                                    {% elif user.activity_count > 50 %}
                                    <span class="badge badge-warning">Medium</span>
                                    {% else %}
                                    <span class="badge badge-info">Low</span>
                                    {% endif %}
                                </td>
                                <td>
                                    <a href="{% url 'users:user_activity_analysis' %}?user_id={{ user.user_id }}&days={{ days }}" 
                                       class="btn btn-sm btn-outline-primary">
                                        <span>📈</span> Analyze
                                    </a>
                                </td>
                            </tr>
                            {% empty %}
                            <tr>
                                <td colspan="6" class="text-center text-muted">No user activity data available</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="analysis-card">
                <h5><span>📊</span> Activity Distribution</h5>
                <div class="chart-container">
                    <canvas id="activityDistributionChart"></canvas>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Module Activity -->
    <div class="row">
        <div class="col-md-6">
            <div class="analysis-card">
                <h5><span>📦</span> Module Activity Overview</h5>
                {% for module in module_activity %}
                <div class="mb-3">
                    <div class="d-flex justify-content-between mb-1">
                        <span><strong>{{ module.module|title }}</strong></span>
                        <span class="text-muted">{{ module.unique_users }} users</span>
                    </div>
                    <div class="module-bar">
                        {% with max_count=module_activity.0.count %}
                        <div class="module-fill" style="width: {% widthratio module.count max_count 100 %}%"></div>
                        {% endwith %}
                        <div class="module-text">{{ module.count }} activities</div>
                    </div>
                </div>
                {% empty %}
                <p class="text-muted text-center">No module activity data available</p>
                {% endfor %}
            </div>
        </div>
        <div class="col-md-6">
            <div class="analysis-card">
                <h5><span>📊</span> Activity Trends</h5>
                <div class="chart-container">
                    <canvas id="activityTrendsChart"></canvas>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Unusual Patterns -->
    <div class="row">
        <div class="col-md-6">
            <div class="analysis-card">
                <h5><span>🌙</span> After-Hours Activity</h5>
                {% if after_hours %}
                <div class="pattern-alert">
                    <span>⚠️</span>
                    <strong>{{ after_hours|length }} users</strong> have been active outside normal business hours.
                </div>
                {% endif %}
                
                {% for activity in after_hours %}
                <div class="user-row">
                    <div>
                        <strong>{{ activity.user__first_name }} {{ activity.user__last_name }}</strong>
                        <br>
                        <small class="text-muted">Outside business hours activity</small>
                    </div>
                    <div class="text-right">
                        <span class="badge badge-warning">{{ activity.count }} activities</span>
                        <br>
                        <a href="{% url 'users:user_activity_analysis' %}?user_id={{ activity.user_id }}&days={{ days }}" 
                           class="btn btn-sm btn-outline-primary mt-1">
                            Analyze
                        </a>
                    </div>
                </div>
                {% empty %}
                <div class="text-center py-4">
                    <span>✓</span>
                    <p class="text-muted">No after-hours activity detected</p>
                </div>
                {% endfor %}
            </div>
        </div>
        <div class="col-md-6">
            <div class="analysis-card">
                <h5><i class="fas fa-layer-group"></i> Bulk Operations</h5>
                {% if bulk_operations %}
                <div class="pattern-alert">
                    <span>ℹ️</span>
                    <strong>{{ bulk_operations|length }} users</strong> have performed bulk operations.
                </div>
                {% endif %}
                
                {% for operation in bulk_operations %}
                <div class="user-row">
                    <div>
                        <strong>{{ operation.user__first_name }} {{ operation.user__last_name }}</strong>
                        <br>
                        <small class="text-muted">{{ operation.action|title }}</small>
                    </div>
                    <div class="text-right">
                        <span class="badge badge-info">{{ operation.count }} operations</span>
                        <br>
                        <a href="{% url 'users:user_activity_analysis' %}?user_id={{ operation.user_id }}&days={{ days }}" 
                           class="btn btn-sm btn-outline-primary mt-1">
                            Analyze
                        </a>
                    </div>
                </div>
                {% empty %}
                <div class="text-center py-4">
                    <span>ℹ️</span>
                    <p class="text-muted">No bulk operations detected</p>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>
    
    <!-- System Health Indicators -->
    <div class="row">
        <div class="col-12">
            <div class="analysis-card">
                <h5><i class="fas fa-heartbeat"></i> System Health Indicators</h5>
                <div class="row">
                    <div class="col-md-3">
                        <div class="text-center p-3 border rounded">
                            <h4 class="text-success">
                                {% if active_users %}
                                {% with total_activities=0 %}
                                {% for user in active_users %}
                                {% with total_activities=total_activities|add:user.activity_count %}
                                {% endwith %}
                                {% endfor %}
                                {% widthratio total_activities active_users|length 1 %}
                                {% endwith %}
                                {% else %}
                                0
                                {% endif %}
                            </h4>
                            <small class="text-muted">Avg Activities per User</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="text-center p-3 border rounded">
                            <h4 class="{% if after_hours|length > 5 %}text-warning{% else %}text-success{% endif %}">
                                {{ after_hours|length }}
                            </h4>
                            <small class="text-muted">After-Hours Users</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="text-center p-3 border rounded">
                            <h4 class="text-info">{{ module_activity|length }}</h4>
                            <small class="text-muted">Active Modules</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="text-center p-3 border rounded">
                            <h4 class="{% if bulk_operations|length > 10 %}text-warning{% else %}text-success{% endif %}">
                                {{ bulk_operations|length }}
                            </h4>
                            <small class="text-muted">Bulk Operations</small>
                        </div>
                    </div>
                </div>
                
                <div class="mt-4">
                    <h6>System Recommendations:</h6>
                    <ul class="list-unstyled">
                        {% if after_hours|length > 5 %}
                        <li><span>⚠️</span> Consider reviewing after-hours access policies - {{ after_hours|length }} users active outside business hours</li>
                        {% endif %}
                        {% if bulk_operations|length > 10 %}
                        <li><span>ℹ️</span> High bulk operation activity detected - ensure proper authorization controls</li>
                        {% endif %}
                        {% if active_users|length < 5 %}
                        <li><span>❓</span> Low user activity - consider user engagement strategies</li>
                        {% endif %}
                        <li><span>✓</span> Regular monitoring of user activity patterns is recommended</li>
                    </ul>
                </div>
            </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() {
    // Activity Distribution Chart
    const distributionCtx = document.getElementById('activityDistributionChart').getContext('2d');
    const distributionData = {
        labels: [
            {% for user in active_users|slice:":5" %}
            '{{ user.user__first_name }} {{ user.user__last_name }}'{% if not forloop.last %},{% endif %}
            {% endfor %}
        ],
        datasets: [{
            data: [
                {% for user in active_users|slice:":5" %}
                {{ user.activity_count }}{% if not forloop.last %},{% endif %}
                {% endfor %}
            ],
            backgroundColor: [
                '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF'
            ]
        }]
    };
    
    new Chart(distributionCtx, {
        type: 'doughnut',
        data: distributionData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
    
    // Activity Trends Chart (placeholder data)
    const trendsCtx = document.getElementById('activityTrendsChart').getContext('2d');
    const trendsData = {
        labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        datasets: [{
            label: 'System Activity',
            data: [120, 150, 180, 200, 160, 80, 40],
            borderColor: '#007bff',
            backgroundColor: 'rgba(0, 123, 255, 0.1)',
            tension: 0.4
        }, {
            label: 'After Hours',
            data: [10, 15, 12, 18, 25, 35, 20],
            borderColor: '#ffc107',
            backgroundColor: 'rgba(255, 193, 7, 0.1)',
            tension: 0.4
        }]
    };
    
    new Chart(trendsCtx, {
        type: 'line',
        data: trendsData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
});
</script>
{% endblock %}