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

{% block title %}Customer Requests Analytics{% endblock %}

{% block extra_css %}
<style>
    .analytics-card {
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        transition: all 0.3s;
    }
    
    .analytics-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    }
    
    .metric-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 15px;
        padding: 20px;
        text-align: center;
    }
    
    .metric-value {
        font-size: 2.5rem;
        font-weight: bold;
        margin-bottom: 5px;
    }
    
    .metric-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }
    
    .chart-container {
        position: relative;
        height: 300px;
        margin: 20px 0;
    }
    
    .workload-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 0;
        border-bottom: 1px solid #eee;
    }
    
    .workload-item:last-child {
        border-bottom: none;
    }
    
    .progress-bar-custom {
        height: 8px;
        border-radius: 4px;
        background-color: #e9ecef;
        overflow: hidden;
    }
    
    .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #28a745, #20c997);
        transition: width 0.3s ease;
    }
    
    .trend-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 0;
        border-bottom: 1px solid #f0f0f0;
    }
    
    .trend-item:last-child {
        border-bottom: none;
    }
    
    .overdue-badge {
        background-color: #dc3545;
        color: white;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 500;
    }
    
    .filters-section {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- Page Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="h3 mb-0">Customer Requests Analytics</h1>
                    <p class="text-muted">Performance metrics and insights</p>
                </div>
                <div>
                    <a href="{% url 'reports:customer_requests_list' %}" class="btn btn-outline-primary">
                        <span>📋</span> View Requests
                    </a>
                    <a href="{% url 'reports:customer_requests_report' %}" class="btn btn-outline-secondary ml-2">
                        <span>📊</span> Generate Report
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Date Range Filters -->
    <div class="filters-section">
        <form method="get" class="row align-items-end">
            <div class="col-md-3">
                <label for="start_date" class="form-label">Start Date</label>
                <input type="date" class="form-control" id="start_date" name="start_date" 
                       value="{{ start_date|date:'Y-m-d' }}">
            </div>
            <div class="col-md-3">
                <label for="end_date" class="form-label">End Date</label>
                <input type="date" class="form-control" id="end_date" name="end_date" 
                       value="{{ end_date|date:'Y-m-d' }}">
            </div>
            <div class="col-md-6">
                <button type="submit" class="btn btn-primary">
                    <span>🔍</span> Update Analytics
                </button>
                <button type="button" class="btn btn-outline-info ml-2" onclick="exportAnalytics()">
                    <span>⬇️</span> Export Data
                </button>
            </div>
        </form>
    </div>

    <!-- Key Metrics -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="metric-card">
                <div class="metric-value">{{ analytics_data.total_requests }}</div>
                <div class="metric-label">Total Requests</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="metric-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                <div class="metric-value">{{ analytics_data.resolved_requests }}</div>
                <div class="metric-label">Resolved Requests</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="metric-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                <div class="metric-value">{{ resolution_rate|floatformat:1 }}%</div>
                <div class="metric-label">Resolution Rate</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="metric-card" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
                <div class="metric-value">{{ avg_resolution_time|floatformat:1 }}h</div>
                <div class="metric-label">Avg Resolution Time</div>
            </div>
        </div>
    </div>

    <!-- Charts and Analytics -->
    <div class="row">
        <!-- Request Type Distribution -->
        <div class="col-md-6 mb-4">
            <div class="card analytics-card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <span>📊</span>
                        Request Type Distribution
                    </h5>
                </div>
                <div class="card-body">
                    <canvas id="typeDistributionChart" class="chart-container"></canvas>
                    <div class="mt-3">
                        {% for item in type_distribution %}
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span>{{ item.request_type|title }}</span>
                            <span class="badge badge-primary">{{ item.count }}</span>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>

        <!-- Priority Distribution -->
        <div class="col-md-6 mb-4">
            <div class="card analytics-card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <span>📊</span>
                        Priority Distribution
                    </h5>
                </div>
                <div class="card-body">
                    <canvas id="priorityDistributionChart" class="chart-container"></canvas>
                    <div class="mt-3">
                        {% for item in priority_distribution %}
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span>{{ item.priority|title }}</span>
                            <span class="badge badge-warning">{{ item.count }}</span>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Staff Workload -->
        <div class="col-md-6 mb-4">
            <div class="card analytics-card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <span>👥</span>
                        Staff Workload Distribution
                    </h5>
                </div>
                <div class="card-body">
                    {% for staff in staff_workload %}
                    <div class="workload-item">
                        <div>
                            <strong>{{ staff.assigned_to__first_name }} {{ staff.assigned_to__last_name }}</strong>
                            <div class="small text-muted">
                                Resolved: {{ staff.resolved_count }} | 
                                Pending: {{ staff.pending_count }} | 
                                In Progress: {{ staff.in_progress_count }}
                            </div>
                        </div>
                        <div class="text-right">
                            <span class="badge badge-primary">{{ staff.assigned_count }}</span>
                            <div class="progress-bar-custom mt-1" style="width: 100px;">
                                <div class="progress-fill" style="width: {% widthratio staff.assigned_count 50 100 %}%;"></div>
                            </div>
                        </div>
                    </div>
                    {% empty %}
                    <p class="text-muted text-center">No staff assignments found</p>
                    {% endfor %}
                </div>
            </div>
        </div>

        <!-- Monthly Trends -->
        <div class="col-md-6 mb-4">
            <div class="card analytics-card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <span>📈</span>
                        Monthly Trends
                    </h5>
                </div>
                <div class="card-body">
                    <canvas id="monthlyTrendsChart" class="chart-container"></canvas>
                    <div class="mt-3">
                        {% for trend in monthly_trends %}
                        <div class="trend-item">
                            <span>{{ trend.month }}</span>
                            <div>
                                <span class="badge badge-info mr-1">{{ trend.total_requests }}</span>
                                <span class="badge badge-success">{{ trend.resolved_requests }}</span>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Overdue Requests Alert -->
    {% if total_overdue > 0 %}
    <div class="row">
        <div class="col-12 mb-4">
            <div class="alert alert-warning">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h5 class="alert-heading mb-1">
                            <span>⚠️</span>
                            Overdue Requests Alert
                        </h5>
                        <p class="mb-0">
                            You have <strong>{{ total_overdue }}</strong> requests that are overdue (older than 24 hours).
                        </p>
                    </div>
                    <div>
                        <a href="{% url 'reports:customer_requests_list' %}?status=pending" class="btn btn-warning">
                            <i class="fas fa-eye"></i> View Overdue
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% endif %}

    <!-- Summary Statistics -->
    <div class="row">
        <div class="col-12">
            <div class="card analytics-card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <span>ℹ️</span>
                        Summary Statistics
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row text-center">
                        <div class="col-md-2">
                            <h6 class="text-primary">{{ analytics_data.pending_requests }}</h6>
                            <small class="text-muted">Pending</small>
                        </div>
                        <div class="col-md-2">
                            <h6 class="text-info">{{ analytics_data.in_progress_requests }}</h6>
                            <small class="text-muted">In Progress</small>
                        </div>
                        <div class="col-md-2">
                            <h6 class="text-success">{{ analytics_data.resolved_requests }}</h6>
                            <small class="text-muted">Resolved</small>
                        </div>
                        <div class="col-md-2">
                            <h6 class="text-warning">{{ total_overdue }}</h6>
                            <small class="text-muted">Overdue</small>
                        </div>
                        <div class="col-md-2">
                            <h6 class="text-secondary">{{ staff_workload|length }}</h6>
                            <small class="text-muted">Active Staff</small>
                        </div>
                        <div class="col-md-2">
                            <h6 class="text-dark">{{ type_distribution|length }}</h6>
                            <small class="text-muted">Request Types</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Request Type Distribution Chart
const typeCtx = document.getElementById('typeDistributionChart').getContext('2d');
const typeChart = new Chart(typeCtx, {
    type: 'doughnut',
    data: {
        labels: [
            {% for item in type_distribution %}
            '{{ item.request_type|title }}'{% if not forloop.last %},{% endif %}
            {% endfor %}
        ],
        datasets: [{
            data: [
                {% for item in type_distribution %}
                {{ item.count }}{% if not forloop.last %},{% endif %}
                {% endfor %}
            ],
            backgroundColor: [
                '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40'
            ]
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'bottom'
            }
        }
    }
});

// Priority Distribution Chart
const priorityCtx = document.getElementById('priorityDistributionChart').getContext('2d');
const priorityChart = new Chart(priorityCtx, {
    type: 'bar',
    data: {
        labels: [
            {% for item in priority_distribution %}
            '{{ item.priority|title }}'{% if not forloop.last %},{% endif %}
            {% endfor %}
        ],
        datasets: [{
            label: 'Requests',
            data: [
                {% for item in priority_distribution %}
                {{ item.count }}{% if not forloop.last %},{% endif %}
                {% endfor %}
            ],
            backgroundColor: ['#dc3545', '#fd7e14', '#ffc107', '#28a745']
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false
            }
        },
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});

// Monthly Trends Chart
const trendsCtx = document.getElementById('monthlyTrendsChart').getContext('2d');
const trendsChart = new Chart(trendsCtx, {
    type: 'line',
    data: {
        labels: [
            {% for trend in monthly_trends %}
            '{{ trend.month }}'{% if not forloop.last %},{% endif %}
            {% endfor %}
        ],
        datasets: [{
            label: 'Total Requests',
            data: [
                {% for trend in monthly_trends %}
                {{ trend.total_requests }}{% if not forloop.last %},{% endif %}
                {% endfor %}
            ],
            borderColor: '#36A2EB',
            backgroundColor: 'rgba(54, 162, 235, 0.1)',
            tension: 0.4
        }, {
            label: 'Resolved Requests',
            data: [
                {% for trend in monthly_trends %}
                {{ trend.resolved_requests }}{% if not forloop.last %},{% endif %}
                {% endfor %}
            ],
            borderColor: '#4BC0C0',
            backgroundColor: 'rgba(75, 192, 192, 0.1)',
            tension: 0.4
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'bottom'
            }
        },
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});

function exportAnalytics() {
    const params = new URLSearchParams(window.location.search);
    params.set('format', 'json');
    
    fetch(window.location.pathname + '?' + params.toString())
        .then(response => response.json())
        .then(data => {
            const blob = new Blob([JSON.stringify(data, null, 2)], {
                type: 'application/json'
            });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'customer_requests_analytics.json';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        })
        .catch(error => {
            console.error('Export failed:', error);
            alert('Failed to export analytics data');
        });
}

// Auto-refresh every 5 minutes
setInterval(function() {
    location.reload();
}, 300000);
</script>
{% endblock %}