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

{% block title %}Security Alerts{% endblock %}

{% block extra_css %}
<style>
    .alerts-card {
        background: white;
        border-radius: 10px;
        padding: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
    }
    
    .alert-item {
        border-left: 4px solid #dc3545;
        padding: 15px;
        margin-bottom: 15px;
        background: #f8f9fa;
        border-radius: 0 5px 5px 0;
        transition: all 0.3s ease;
    }
    
    .alert-item:hover {
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    
    .alert-item.resolved {
        border-left-color: #28a745;
        background: #f8fff9;
        opacity: 0.8;
    }
    
    .alert-item.critical {
        border-left-color: #dc3545;
        background: #fff5f5;
    }
    
    .alert-item.high {
        border-left-color: #fd7e14;
        background: #fff8f0;
    }
    
    .alert-item.medium {
        border-left-color: #ffc107;
        background: #fffdf5;
    }
    
    .alert-item.low {
        border-left-color: #17a2b8;
        background: #f7fdff;
    }
    
    .severity-badge {
        padding: 4px 10px;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
    }
    
    .severity-critical {
        background: #dc3545;
        color: white;
    }
    
    .severity-high {
        background: #fd7e14;
        color: white;
    }
    
    .severity-medium {
        background: #ffc107;
        color: #212529;
    }
    
    .severity-low {
        background: #17a2b8;
        color: white;
    }
    
    .alert-type-badge {
        background: #6c757d;
        color: white;
        padding: 3px 8px;
        border-radius: 12px;
        font-size: 0.7rem;
        margin-left: 5px;
    }
    
    .filter-card {
        background: white;
        border-radius: 10px;
        padding: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
    }
    
    .stats-card {
        text-align: center;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 20px;
        color: white;
    }
    
    .stats-card.critical {
        background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
    }
    
    .stats-card.warning {
        background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%);
    }
    
    .stats-card.info {
        background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
    }
    
    .stats-card.success {
        background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);
    }
    
    .stat-value {
        font-size: 2rem;
        font-weight: bold;
        margin-bottom: 5px;
    }
    
    .stat-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }
    
    .resolve-btn {
        transition: all 0.3s ease;
    }
    
    .resolve-btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    }
    
    .alert-meta {
        font-size: 0.85rem;
        color: #6c757d;
        margin-top: 10px;
    }
    
    .alert-context {
        background: #e9ecef;
        border-radius: 5px;
        padding: 10px;
        margin-top: 10px;
        font-size: 0.9rem;
    }
</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> Security Alerts</h2>
                <div class="btn-group">
                    <button type="button" class="btn btn-outline-primary" onclick="refreshAlerts()">
                        <span>🔄</span> Refresh
                    </button>
                    <button type="button" class="btn btn-outline-success" onclick="markAllResolved()">
                        <i class="fas fa-check-double"></i> Mark All Resolved
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Alert Statistics -->
    <div class="row">
        <div class="col-md-3">
            <div class="stats-card critical">
                <div class="stat-value">
                    {{ page_obj.paginator.count }}
                </div>
                <div class="stat-label">Total Alerts</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card warning">
                <div class="stat-value">
                    {% with unresolved=0 %}
                    {% for alert in page_obj %}
                    {% if not alert.is_resolved %}
                    {% with unresolved=unresolved|add:1 %}
                    {% endwith %}
                    {% endif %}
                    {% endfor %}
                    {{ unresolved }}
                    {% endwith %}
                </div>
                <div class="stat-label">Unresolved</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card info">
                <div class="stat-value">
                    {% with critical=0 %}
                    {% for alert in page_obj %}
                    {% if alert.severity == 'critical' and not alert.is_resolved %}
                    {% with critical=critical|add:1 %}
                    {% endwith %}
                    {% endif %}
                    {% endfor %}
                    {{ critical }}
                    {% endwith %}
                </div>
                <div class="stat-label">Critical</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card success">
                <div class="stat-value">
                    {% with resolved=0 %}
                    {% for alert in page_obj %}
                    {% if alert.is_resolved %}
                    {% with resolved=resolved|add:1 %}
                    {% endwith %}
                    {% endif %}
                    {% endfor %}
                    {{ resolved }}
                    {% endwith %}
                </div>
                <div class="stat-label">Resolved</div>
            </div>
        </div>
    </div>
    
    <!-- Filters -->
    <div class="row">
        <div class="col-12">
            <div class="filter-card">
                <h5><span>🔍</span> Filter Alerts</h5>
                <form method="get" id="filterForm">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="severity">Severity</label>
                                <select name="severity" id="severity" class="form-control">
                                    <option value="">All Severities</option>
                                    {% for value, label in severity_choices %}
                                    <option value="{{ value }}" {% if filters.severity == value %}selected{% endif %}>
                                        {{ label }}
                                    </option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="alert_type">Alert Type</label>
                                <select name="alert_type" id="alert_type" class="form-control">
                                    <option value="">All Types</option>
                                    {% for value, label in alert_type_choices %}
                                    <option value="{{ value }}" {% if filters.alert_type == value %}selected{% endif %}>
                                        {{ label }}
                                    </option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="resolved">Status</label>
                                <select name="resolved" id="resolved" class="form-control">
                                    <option value="">All Alerts</option>
                                    <option value="false" {% if filters.resolved == 'false' %}selected{% endif %}>Unresolved</option>
                                    <option value="true" {% if filters.resolved == 'true' %}selected{% endif %}>Resolved</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>&nbsp;</label>
                                <div class="d-flex">
                                    <button type="submit" class="btn btn-primary mr-2">
                                        <span>🔍</span> Filter
                                    </button>
                                    <a href="{% url 'users:security_alerts' %}" class="btn btn-outline-secondary">
                                        <span>✕</span> Clear
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Alerts List -->
    <div class="row">
        <div class="col-12">
            <div class="alerts-card">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5>Security Alerts ({{ page_obj.paginator.count }} total)</h5>
                    <div class="text-muted">
                        Showing {{ page_obj.start_index }}-{{ page_obj.end_index }} of {{ page_obj.paginator.count }}
                    </div>
                </div>
                
                {% for alert in page_obj %}
                <div class="alert-item {{ alert.severity }} {% if alert.is_resolved %}resolved{% endif %}" id="alert-{{ alert.id }}">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="flex-grow-1">
                            <div class="d-flex align-items-center mb-2">
                                <h6 class="mb-0">{{ alert.title }}</h6>
                                <span class="severity-badge severity-{{ alert.severity }} ml-2">{{ alert.severity }}</span>
                                <span class="alert-type-badge">{{ alert.get_alert_type_display }}</span>
                                {% if alert.is_resolved %}
                                <span class="badge badge-success ml-2">
                                    <span>✓</span> Resolved
                                </span>
                                {% endif %}
                            </div>
                            
                            <p class="mb-2">{{ alert.description }}</p>
                            
                            {% if alert.user %}
                            <div class="alert-meta">
                                <span>👤</span> <strong>User:</strong> {{ alert.user.get_full_name }}
                                ({{ alert.user.role|title }})
                            </div>
                            {% endif %}
                            
                            {% if alert.ip_address %}
                            <div class="alert-meta">
                                <span>🌐</span> <strong>IP Address:</strong> {{ alert.ip_address }}
                            </div>
                            {% endif %}
                            
                            {% if alert.additional_context %}
                            <div class="alert-context">
                                <strong>Additional Context:</strong>
                                <pre class="mb-0">{{ alert.additional_context|pprint }}</pre>
                            </div>
                            {% endif %}
                            
                            <div class="alert-meta">
                                <span>⏰</span> <strong>Created:</strong> {{ alert.created_at|date:"M d, Y H:i:s" }}
                                ({{ alert.created_at|timesince }} ago)
                            </div>
                            
                            {% if alert.is_resolved %}
                            <div class="alert-meta">
                                <span>✓</span> 
                                <strong>Resolved by:</strong> {{ alert.resolved_by.get_full_name }}
                                on {{ alert.resolved_at|date:"M d, Y H:i:s" }}
                                {% if alert.resolution_notes %}
                                <br>
                                <strong>Notes:</strong> {{ alert.resolution_notes }}
                                {% endif %}
                            </div>
                            {% endif %}
                        </div>
                        
                        <div class="text-right ml-3">
                            <div class="mb-2">
                                <small class="text-muted">{{ alert.created_at|timesince }} ago</small>
                            </div>
                            
                            {% if not alert.is_resolved %}
                            <button class="btn btn-sm btn-outline-success resolve-btn" 
                                    onclick="showResolveModal('{{ alert.id }}', '{{ alert.title|escapejs }}')">
                                <span>✓</span> Resolve
                            </button>
                            {% endif %}
                            
                            {% if alert.user %}
                            <br>
                            <a href="{% url 'users:user_activity_analysis' %}?user_id={{ alert.user.id }}&days=7" 
                               class="btn btn-sm btn-outline-primary mt-1">
                                <span>📈</span> Analyze User
                            </a>
                            {% endif %}
                        </div>
                    </div>
                </div>
                {% empty %}
                <div class="text-center py-5">
                    <i class="fas fa-shield-alt fa-3x text-success mb-3"></i>
                    <h5 class="text-success">No Security Alerts</h5>
                    <p class="text-muted">
                        {% if filters.resolved == 'false' %}
                        All security alerts have been resolved.
                        {% else %}
                        No security alerts match your current filters.
                        {% endif %}
                    </p>
                </div>
                {% endfor %}
                
                <!-- Pagination -->
                {% if page_obj.has_other_pages %}
                <nav aria-label="Security alerts pagination" class="mt-4">
                    <ul class="pagination justify-content-center">
                        {% if page_obj.has_previous %}
                        <li class="page-item">
                            <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ page_obj.previous_page_number }}">Previous</a>
                        </li>
                        {% endif %}
                        
                        {% for num in page_obj.paginator.page_range %}
                        {% if page_obj.number == num %}
                        <li class="page-item active">
                            <span class="page-link">{{ num }}</span>
                        </li>
                        {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                        <li class="page-item">
                            <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ num }}">{{ num }}</a>
                        </li>
                        {% endif %}
                        {% endfor %}
                        
                        {% if page_obj.has_next %}
                        <li class="page-item">
                            <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ page_obj.next_page_number }}">Next</a>
                        </li>
                        {% endif %}
                    </ul>
                </nav>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- Resolve Alert Modal -->
<div class="modal fade" id="resolveAlertModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Resolve Security Alert</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <span>ℹ️</span>
                    <strong>Alert:</strong> <span id="alertTitle"></span>
                </div>
                <form id="resolveAlertForm">
                    <div class="form-group">
                        <label for="resolution_notes">Resolution Notes <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="resolution_notes" name="resolution_notes" rows="4" 
                                  placeholder="Describe how this alert was resolved, what actions were taken, and any follow-up required..." required></textarea>
                        <small class="form-text text-muted">Please provide detailed notes for audit purposes.</small>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" onclick="submitResolveAlert()">
                    <span>✓</span> Resolve Alert
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Bulk Resolve Modal -->
<div class="modal fade" id="bulkResolveModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Resolve All Unresolved Alerts</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> This will mark all unresolved alerts as resolved. This action cannot be undone.
                </div>
                <form id="bulkResolveForm">
                    <div class="form-group">
                        <label for="bulk_resolution_notes">Resolution Notes <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="bulk_resolution_notes" name="bulk_resolution_notes" rows="3" 
                                  placeholder="Provide a reason for bulk resolution..." required></textarea>
                    </div>
                </form>
            </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="submitBulkResolve()">
                    <i class="fas fa-check-double"></i> Resolve All
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentAlertId = null;

function showResolveModal(alertId, alertTitle) {
    currentAlertId = alertId;
    document.getElementById('alertTitle').textContent = alertTitle;
    document.getElementById('resolution_notes').value = '';
    $('#resolveAlertModal').modal('show');
}

function submitResolveAlert() {
    if (!currentAlertId) return;
    
    const notes = document.getElementById('resolution_notes').value.trim();
    if (!notes) {
        alert('Please provide resolution notes.');
        return;
    }
    
    const formData = new FormData();
    formData.append('resolution_notes', notes);
    formData.append('csrfmiddlewaretoken', document.querySelector('[name=csrfmiddlewaretoken]').value);
    
    fetch(`/users/audit/alerts/${currentAlertId}/resolve/`, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            $('#resolveAlertModal').modal('hide');
            
            // Update the alert item in the DOM
            const alertElement = document.getElementById(`alert-${currentAlertId}`);
            if (alertElement) {
                alertElement.classList.add('resolved');
                
                // Add resolved badge
                const titleElement = alertElement.querySelector('h6');
                if (titleElement && !titleElement.querySelector('.badge-success')) {
                    const resolvedBadge = document.createElement('span');
                    resolvedBadge.className = 'badge badge-success ml-2';
                    resolvedBadge.innerHTML = '<span>✓</span> Resolved';
                    titleElement.appendChild(resolvedBadge);
                }
                
                // Remove resolve button
                const resolveBtn = alertElement.querySelector('.resolve-btn');
                if (resolveBtn) {
                    resolveBtn.remove();
                }
                
                // Add resolution info
                const metaSection = alertElement.querySelector('.alert-meta:last-child');
                if (metaSection) {
                    const resolutionInfo = document.createElement('div');
                    resolutionInfo.className = 'alert-meta';
                    resolutionInfo.innerHTML = `
                        <span>✓</span> 
                        <strong>Resolved by:</strong> You just now
                        <br>
                        <strong>Notes:</strong> ${notes}
                    `;
                    metaSection.parentNode.insertBefore(resolutionInfo, metaSection.nextSibling);
                }
            }
            
            // Show success message
            showNotification('Alert resolved successfully', 'success');
        } else {
            alert('Error resolving alert: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error resolving alert');
    });
}

function markAllResolved() {
    $('#bulkResolveModal').modal('show');
}

function submitBulkResolve() {
    const notes = document.getElementById('bulk_resolution_notes').value.trim();
    if (!notes) {
        alert('Please provide resolution notes.');
        return;
    }
    
    // This would need to be implemented in the backend
    alert('Bulk resolve functionality would be implemented here');
    $('#bulkResolveModal').modal('hide');
}

function refreshAlerts() {
    location.reload();
}

function showNotification(message, type) {
    // Simple notification - could be enhanced with a proper notification library
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    notification.innerHTML = `
        ${message}
        <button type="button" class="close" data-dismiss="alert">
            <span>&times;</span>
        </button>
    `;
    
    document.body.appendChild(notification);
    
    // Auto-remove after 5 seconds
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 5000);
}

// Auto-submit form on filter change
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('filterForm');
    const selects = form.querySelectorAll('select');
    
    selects.forEach(select => {
        select.addEventListener('change', () => form.submit());
    });
});
</script>
{% endblock %}