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

{% block title %}Notification Analytics{% endblock %}

{% block extra_css %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-900">Notification Analytics</h1>
        <div class="flex space-x-2">
            <select id="periodSelect" class="border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                <option value="7" {% if days == 7 %}selected{% endif %}>Last 7 days</option>
                <option value="30" {% if days == 30 %}selected{% endif %}>Last 30 days</option>
                <option value="90" {% if days == 90 %}selected{% endif %}>Last 90 days</option>
            </select>
            <button id="refreshBtn" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors">
                <span>🔄</span>Refresh
            </button>
        </div>
    </div>

    <!-- Overview Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <span>✈️</span>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">Total Notifications</p>
                    <p class="text-2xl font-bold text-gray-900">{{ total_notifications|default:0 }}</p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <span>✓</span>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">Total Deliveries</p>
                    <p class="text-2xl font-bold text-gray-900">{{ total_deliveries|default:0 }}</p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <span>⚠️</span>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">Escalations</p>
                    <p class="text-2xl font-bold text-gray-900">{{ escalation_stats.total|default:0 }}</p>
                    <p class="text-xs text-gray-500">{{ escalation_stats.resolved|default:0 }} resolved</p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <i class="fas fa-layer-group text-purple-600 text-2xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">Batch Jobs</p>
                    <p class="text-2xl font-bold text-gray-900">0</p>
                    <p class="text-xs text-gray-500">0 pending</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        <!-- Delivery Statistics Chart -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-lg font-semibold text-gray-900 mb-4">Delivery Statistics by Channel</h2>
            <canvas id="deliveryChart" width="400" height="200"></canvas>
        </div>
        
        <!-- Notification Types Chart -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-lg font-semibold text-gray-900 mb-4">Notifications by Type</h2>
            <canvas id="typeChart" width="400" height="200"></canvas>
        </div>
    </div>

    <!-- Detailed Statistics -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        <!-- Channel Performance -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-lg font-semibold text-gray-900 mb-4">Channel Performance</h2>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Channel</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Total</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Delivered</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Read</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Failed</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Success Rate</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        {% for channel in delivery_stats %}
                        <tr>
                            <td class="px-4 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                <i class="fas fa-{% if channel.channel == 'in_app' %}bell{% elif channel.channel == 'email' %}envelope{% elif channel.channel == 'sms' %}sms{% else %}mobile-alt{% endif %} mr-2"></i>
                                {{ channel.channel|title|replace:"_":" " }}
                            </td>
                            <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-900">{{ channel.total }}</td>
                            <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-900">{{ channel.delivered }}</td>
                            <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-900">{{ channel.read }}</td>
                            <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-900">{{ channel.failed }}</td>
                            <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-900">
                                <div class="flex items-center">
                                    <div class="flex-1 bg-gray-200 rounded-full h-2 mr-2">
                                        <div class="bg-green-600 h-2 rounded-full" style="width: {{ channel.delivery_rate }}%"></div>
                                    </div>
                                    <span class="text-xs">{{ channel.delivery_rate|floatformat:1 }}%</span>
                                </div>
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="6" class="px-4 py-4 text-center text-gray-500">No delivery data available</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- User Engagement by Role -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-lg font-semibold text-gray-900 mb-4">User Engagement by Role</h2>
            <div class="space-y-4">
                {% for role_stat in user_stats %}
                <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                    <div>
                        <p class="text-sm font-medium text-gray-900">{{ role_stat.user__role|title|replace:"_":" " }}</p>
                        <p class="text-xs text-gray-500">{{ role_stat.total }} notifications</p>
                    </div>
                    <div class="text-right">
                        <p class="text-sm font-bold text-gray-900">{{ role_stat.read_rate|floatformat:1 }}%</p>
                        <p class="text-xs text-gray-500">{{ role_stat.read }}/{{ role_stat.total }} read</p>
                    </div>
                </div>
                {% empty %}
                <p class="text-center text-gray-500">No user engagement data available</p>
                {% endfor %}
            </div>
        </div>
    </div>

    <!-- Recent Escalations -->
    {% if recent_escalations %}
    <div class="bg-white rounded-lg shadow-md p-6 mb-8">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">Recent Escalations</h2>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Notification</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Rule</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Escalated To</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Level</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Time</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {% for escalation in recent_escalations %}
                    <tr>
                        <td class="px-4 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">{{ escalation.original_notification.title|truncatechars:40 }}</div>
                            <div class="text-xs text-gray-500">{{ escalation.original_notification.notification_type }}</div>
                        </td>
                        <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-900">{{ escalation.rule.name }}</td>
                        <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-900">{{ escalation.escalated_to.get_full_name }}</td>
                        <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-900">{{ escalation.escalation_level }}</td>
                        <td class="px-4 py-4 whitespace-nowrap">
                            {% if escalation.resolved_at %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                Resolved
                            </span>
                            {% elif escalation.acknowledged_at %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                Acknowledged
                            </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">
                                Pending
                            </span>
                            {% endif %}
                        </td>
                        <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ escalation.escalated_at|timesince }} ago
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
    {% endif %}

    <!-- Notification Type Performance -->
    <div class="bg-white rounded-lg shadow-md p-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">Notification Type Performance</h2>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Type</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Total</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Read</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Read Rate</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Trend</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {% for type_stat in type_stats %}
                    <tr>
                        <td class="px-4 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                            {{ type_stat.notification_type|title|replace:"_":" " }}
                        </td>
                        <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-900">{{ type_stat.count }}</td>
                        <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-900">-</td>
                        <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-900">
                            <div class="flex items-center">
                                <div class="flex-1 bg-gray-200 rounded-full h-2 mr-2">
                                    <div class="bg-blue-600 h-2 rounded-full" style="width: 75%"></div>
                                </div>
                                <span class="text-xs">75%</span>
                            </div>
                        </td>
                        <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-900">
                            <span>↑</span>
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="5" class="px-4 py-4 text-center text-gray-500">No notification type data available</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const periodSelect = document.getElementById('periodSelect');
    const refreshBtn = document.getElementById('refreshBtn');
    
    // Initialize charts
    initializeCharts();
    
    // Event listeners
    refreshBtn.addEventListener('click', function() {
        const days = periodSelect.value;
        window.location.href = `?days=${days}`;
    });
    
    periodSelect.addEventListener('change', function() {
        const days = this.value;
        window.location.href = `?days=${days}`;
    });
    
    function initializeCharts() {
        // Delivery Statistics Chart
        const deliveryCtx = document.getElementById('deliveryChart').getContext('2d');
        const deliveryData = {
            labels: [{% for channel in delivery_stats %}'{{ channel.channel|title }}'{% if not forloop.last %},{% endif %}{% endfor %}],
            datasets: [{
                label: 'Delivered',
                data: [{% for channel in delivery_stats %}{{ channel.delivered }}{% if not forloop.last %},{% endif %}{% endfor %}],
                backgroundColor: 'rgba(34, 197, 94, 0.8)',
                borderColor: 'rgba(34, 197, 94, 1)',
                borderWidth: 1
            }, {
                label: 'Failed',
                data: [{% for channel in delivery_stats %}{{ channel.failed }}{% if not forloop.last %},{% endif %}{% endfor %}],
                backgroundColor: 'rgba(239, 68, 68, 0.8)',
                borderColor: 'rgba(239, 68, 68, 1)',
                borderWidth: 1
            }]
        };
        
        new Chart(deliveryCtx, {
            type: 'bar',
            data: deliveryData,
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                },
                plugins: {
                    legend: {
                        position: 'top',
                    }
                }
            }
        });
        
        // Notification Types Chart
        const typeCtx = document.getElementById('typeChart').getContext('2d');
        const typeData = {
            labels: [{% for type_stat in type_stats %}'{{ type_stat.notification_type|title }}'{% if not forloop.last %},{% endif %}{% endfor %}],
            datasets: [{
                data: [{% for type_stat in type_stats %}{{ type_stat.count }}{% if not forloop.last %},{% endif %}{% endfor %}],
                backgroundColor: [
                    'rgba(59, 130, 246, 0.8)',
                    'rgba(16, 185, 129, 0.8)',
                    'rgba(245, 158, 11, 0.8)',
                    'rgba(239, 68, 68, 0.8)',
                    'rgba(139, 92, 246, 0.8)',
                    'rgba(236, 72, 153, 0.8)',
                    'rgba(34, 197, 94, 0.8)',
                    'rgba(251, 146, 60, 0.8)'
                ],
                borderWidth: 1
            }]
        };
        
        new Chart(typeCtx, {
            type: 'doughnut',
            data: typeData,
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'right',
                    }
                }
            }
        });
    }
});
</script>
{% endblock %}