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

{% block title %}User 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;
    }
    
    .metric-box {
        text-align: center;
        padding: 20px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 8px;
        margin-bottom: 20px;
    }
    
    .metric-value {
        font-size: 2rem;
        font-weight: bold;
        margin-bottom: 5px;
    }
    
    .metric-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }
    
    .activity-item {
        padding: 10px 0;
        border-bottom: 1px solid #eee;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .activity-item:last-child {
        border-bottom: none;
    }
    
    .time-badge {
        background: #f8f9fa;
        color: #495057;
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 0.8rem;
    }
    
    .security-warning {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 5px;
        padding: 10px;
        margin-bottom: 15px;
    }
    
    .pattern-insight {
        background: #e7f3ff;
        border-left: 4px solid #007bff;
        padding: 15px;
        margin-bottom: 15px;
    }
    
    .chart-container {
        position: relative;
        height: 300px;
        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> User Activity Analysis</h2>
                <div class="btn-group">
                    <a href="?days=7{% if analyzed_user %}&user_id={{ analyzed_user.id }}{% endif %}" 
                       class="btn btn-outline-primary {% if days == 7 %}active{% endif %}">7 Days</a>
                    <a href="?days=30{% if analyzed_user %}&user_id={{ analyzed_user.id }}{% endif %}" 
                       class="btn btn-outline-primary {% if days == 30 %}active{% endif %}">30 Days</a>
                    <a href="?days=90{% if analyzed_user %}&user_id={{ analyzed_user.id }}{% endif %}" 
                       class="btn btn-outline-primary {% if days == 90 %}active{% endif %}">90 Days</a>
                </div>
            </div>
        </div>
    </div>
    
    {% if not analyzed_user %}
    <!-- User Selection -->
    <div class="row">
        <div class="col-12">
            <div class="analysis-card">
                <h5><i class="fas fa-user-search"></i> Select User for Analysis</h5>
                <form method="get">
                    <div class="row">
                        <div class="col-md-6">
                            <select name="user_id" class="form-control" onchange="this.form.submit()">
                                <option value="">Select a user...</option>
                                {% for user in users %}
                                <option value="{{ user.id }}">
                                    {{ user.get_full_name }} ({{ user.role|title }})
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-3">
                            <input type="hidden" name="days" value="{{ days }}">
                            <button type="submit" class="btn btn-primary">Analyze</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- System-wide Analysis -->
    <div class="row">
        <div class="col-md-6">
            <div class="analysis-card">
                <h5><span>👥</span> Most Active Users</h5>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>User</th>
                                <th>Role</th>
                                <th>Activities</th>
                                <th>Security Events</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for user in active_users %}
                            <tr>
                                <td>{{ user.user__first_name }} {{ user.user__last_name }}</td>
                                <td><span class="badge badge-secondary">{{ user.user__role|title }}</span></td>
                                <td>{{ user.activity_count }}</td>
                                <td>
                                    {% if user.security_events > 0 %}
                                    <span class="badge badge-warning">{{ user.security_events }}</span>
                                    {% else %}
                                    <span class="text-muted">0</span>
                                    {% endif %}
                                </td>
                                <td>
                                    <a href="?user_id={{ user.user_id }}&days={{ days }}" class="btn btn-sm btn-outline-primary">
                                        Analyze
                                    </a>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="analysis-card">
                <h5><span>📦</span> Module Activity</h5>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Module</th>
                                <th>Total Activities</th>
                                <th>Unique Users</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for module in module_activity %}
                            <tr>
                                <td>{{ module.module|title }}</td>
                                <td>{{ module.count }}</td>
                                <td>{{ module.unique_users }}</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </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>
                {% for activity in after_hours %}
                <div class="activity-item">
                    <div>
                        <strong>{{ activity.user__first_name }} {{ activity.user__last_name }}</strong>
                    </div>
                    <div>
                        <span class="badge badge-warning">{{ activity.count }} activities</span>
                        <a href="?user_id={{ activity.user_id }}&days={{ days }}" class="btn btn-sm btn-outline-primary ml-2">
                            Analyze
                        </a>
                    </div>
                </div>
                {% empty %}
                <p class="text-muted text-center">No after-hours activity detected</p>
                {% endfor %}
            </div>
        </div>
        <div class="col-md-6">
            <div class="analysis-card">
                <h5><i class="fas fa-layer-group"></i> Bulk Operations</h5>
                {% for operation in bulk_operations %}
                <div class="activity-item">
                    <div>
                        <strong>{{ operation.user__first_name }} {{ operation.user__last_name }}</strong>
                        <br>
                        <small class="text-muted">{{ operation.action }}</small>
                    </div>
                    <div>
                        <span class="badge badge-info">{{ operation.count }} operations</span>
                        <a href="?user_id={{ operation.user_id }}&days={{ days }}" class="btn btn-sm btn-outline-primary ml-2">
                            Analyze
                        </a>
                    </div>
                </div>
                {% empty %}
                <p class="text-muted text-center">No bulk operations detected</p>
                {% endfor %}
            </div>
        </div>
    </div>
    
    {% else %}
    <!-- Individual User Analysis -->
    <div class="row">
        <div class="col-12">
            <div class="analysis-card">
                <div class="d-flex justify-content-between align-items-center">
                    <h5><span>👤</span> Analysis for {{ analyzed_user.get_full_name }}</h5>
                    <a href="{% url 'users:user_activity_analysis' %}?days={{ days }}" class="btn btn-outline-secondary">
                        <span>←</span> Back to Overview
                    </a>
                </div>
                <div class="row mt-3">
                    <div class="col-md-6">
                        <strong>Role:</strong> {{ analyzed_user.role|title }}<br>
                        <strong>Email:</strong> {{ analyzed_user.email }}<br>
                        {% if analyzed_user.branch %}
                        <strong>Branch:</strong> {{ analyzed_user.branch.name }}
                        {% endif %}
                    </div>
                    <div class="col-md-6">
                        {% if security_events > 0 %}
                        <div class="security-warning">
                            <span>⚠️</span>
                            <strong>{{ security_events }} security events</strong> detected in the last {{ days }} days
                        </div>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Metrics -->
    <div class="row">
        <div class="col-md-3">
            <div class="metric-box">
                <div class="metric-value">{{ total_activities }}</div>
                <div class="metric-label">Total Activities</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="metric-box" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                <div class="metric-value">{{ unique_modules }}</div>
                <div class="metric-label">Modules Used</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="metric-box" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
                <div class="metric-value">{{ security_events }}</div>
                <div class="metric-label">Security Events</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="metric-box" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
                <div class="metric-value">
                    {% if total_activities > 0 %}
                    {{ total_activities|floatformat:0 }}
                    {% else %}
                    0
                    {% endif %}
                </div>
                <div class="metric-label">Avg Daily Activity</div>
            </div>
        </div>
    </div>
    
    <!-- Charts -->
    <div class="row">
        <div class="col-md-6">
            <div class="analysis-card">
                <h5><span>📈</span> Daily Activity Pattern</h5>
                <div class="chart-container">
                    <canvas id="dailyActivityChart"></canvas>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="analysis-card">
                <h5><span>⏰</span> Hourly Activity Pattern</h5>
                <div class="chart-container">
                    <canvas id="hourlyPatternChart"></canvas>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row">
        <div class="col-md-6">
            <div class="analysis-card">
                <h5><span>📦</span> Module Usage</h5>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Module</th>
                                <th>Activities</th>
                                <th>Percentage</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for module in module_usage %}
                            <tr>
                                <td>{{ module.module|title }}</td>
                                <td>{{ module.count }}</td>
                                <td>
                                    {% widthratio module.count total_activities 100 %}%
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="analysis-card">
                <h5><i class="fas fa-history"></i> Recent Activities</h5>
                <div style="max-height: 400px; overflow-y: auto;">
                    {% for activity in recent_activities %}
                    <div class="activity-item">
                        <div>
                            <strong>{{ activity.action }}</strong> in {{ activity.module|title }}
                            <br>
                            <small class="text-muted">{{ activity.description|truncatechars:60 }}</small>
                        </div>
                        <div class="text-right">
                            <div class="time-badge">{{ activity.timestamp|timesince }} ago</div>
                            {% if activity.is_security_event %}
                            <br>
                            <span class="badge badge-warning">Security</span>
                            {% endif %}
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
    
    <!-- Access Patterns -->
    {% if access_pattern %}
    <div class="row">
        <div class="col-12">
            <div class="analysis-card">
                <h5><i class="fas fa-fingerprint"></i> Access Patterns</h5>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Total Requests</th>
                                <th>Unique Pages</th>
                                <th>Data Exports</th>
                                <th>Failed Attempts</th>
                                <th>After Hours</th>
                                <th>Primary IP</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for pattern in access_pattern %}
                            <tr>
                                <td>{{ pattern.date|date:"M d, Y" }}</td>
                                <td>{{ pattern.total_requests }}</td>
                                <td>{{ pattern.unique_pages_accessed }}</td>
                                <td>{{ pattern.data_exports }}</td>
                                <td>
                                    {% if pattern.failed_access_attempts > 0 %}
                                    <span class="badge badge-warning">{{ pattern.failed_access_attempts }}</span>
                                    {% else %}
                                    0
                                    {% endif %}
                                </td>
                                <td>
                                    {% if pattern.after_hours_access > 0 %}
                                    <span class="badge badge-info">{{ pattern.after_hours_access }}</span>
                                    {% else %}
                                    0
                                    {% endif %}
                                </td>
                                <td>{{ pattern.primary_ip|default:"-" }}</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
    
    {% endif %}
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
{% if analyzed_user %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Daily Activity Chart
    const dailyCtx = document.getElementById('dailyActivityChart').getContext('2d');
    const dailyData = {
        labels: [
            {% for day in daily_activity %}
            '{{ day.day }}'{% if not forloop.last %},{% endif %}
            {% endfor %}
        ],
        datasets: [{
            label: 'Activities',
            data: [
                {% for day in daily_activity %}
                {{ day.count }}{% if not forloop.last %},{% endif %}
                {% endfor %}
            ],
            borderColor: '#007bff',
            backgroundColor: 'rgba(0, 123, 255, 0.1)',
            tension: 0.4
        }]
    };
    
    new Chart(dailyCtx, {
        type: 'line',
        data: dailyData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
    
    // Hourly Pattern Chart
    const hourlyCtx = document.getElementById('hourlyPatternChart').getContext('2d');
    const hourlyData = {
        labels: [
            {% for hour in hourly_pattern %}
            '{{ hour.hour }}:00'{% if not forloop.last %},{% endif %}
            {% endfor %}
        ],
        datasets: [{
            label: 'Activities by Hour',
            data: [
                {% for hour in hourly_pattern %}
                {{ hour.count }}{% if not forloop.last %},{% endif %}
                {% endfor %}
            ],
            backgroundColor: 'rgba(40, 167, 69, 0.8)',
            borderColor: '#28a745',
            borderWidth: 1
        }]
    };
    
    new Chart(hourlyCtx, {
        type: 'bar',
        data: hourlyData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
});
</script>
{% endif %}
{% endblock %}