{% extends "layouts/base.html" %}
{% load i18n %}

{% block title %}{% trans "Admin Evaluation" %} - PX360{% endblock %}

{% block extra_css %}
<style>
    /* PX360 App Theme Variables */
    :root {
        --hh-navy: #005696;
        --hh-blue: #007bbd;
        --hh-light: #eef6fb;
        --hh-slate: #64748b;
        --hh-success: #10b981;
        --hh-warning: #f59e0b;
        --hh-danger: #ef4444;
    }

    /* Page Header */
    .page-header-gradient {
        background: linear-gradient(135deg, var(--hh-navy) 0%, #0069a8 50%, var(--hh-blue) 100%);
        color: white;
        padding: 2rem 2.5rem;
        border-radius: 1rem;
        margin-bottom: 2rem;
        box-shadow: 0 10px 15px -3px rgba(0, 86, 150, 0.2);
        position: relative;
        overflow: hidden;
    }

    .page-header-gradient::before {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        width: 200px;
        height: 200px;
        background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
    }

    /* Section Cards */
    .section-card {
        background: white;
        border-radius: 1rem;
        border: 2px solid #e2e8f0;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        transition: all 0.3s ease;
    }
    .section-card:hover {
        border-color: #005696;
        box-shadow: 0 10px 25px -5px rgba(0, 86, 150, 0.15);
    }

    .section-header {
        padding: 1rem 1.5rem;
        border-bottom: 2px solid #e2e8f0;
        background: linear-gradient(to right, #f8fafc, #f1f5f9);
    }

    /* KPI Cards */
    .kpi-card {
        background: white;
        border-radius: 1rem;
        border: 2px solid #e2e8f0;
        padding: 1.25rem;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        transition: all 0.3s ease;
        height: 100%;
    }
    .kpi-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        border-color: #005696;
    }

    .kpi-icon {
        width: 48px;
        height: 48px;
        border-radius: 0.75rem;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .kpi-value {
        font-size: 1.75rem;
        font-weight: 800;
        color: #1e293b;
    }

    .kpi-label {
        font-size: 0.8rem;
        font-weight: 600;
        color: #64748b;
        text-transform: uppercase;
        letter-spacing: 0.025em;
    }

    /* Form Styling */
    .form-select-px360 {
        background: white;
        border: 2px solid #e2e8f0;
        border-radius: 0.75rem;
        padding: 0.625rem 1rem;
        color: #1e293b;
        font-size: 0.875rem;
        cursor: pointer;
        transition: all 0.2s;
    }
    .form-select-px360:hover {
        border-color: #005696;
    }
    .form-select-px360:focus {
        outline: none;
        border-color: #005696;
        box-shadow: 0 0 0 3px rgba(0, 86, 150, 0.1);
    }

    /* Chart Cards */
    .chart-card {
        background: white;
        border-radius: 1rem;
        border: 2px solid #e2e8f0;
        overflow: hidden;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        transition: all 0.3s ease;
    }
    .chart-card:hover {
        border-color: #005696;
    }

    .chart-header {
        background: linear-gradient(135deg, #f8fafc, #eef6fb);
        padding: 1rem 1.25rem;
        border-bottom: 2px solid #e2e8f0;
    }

    /* Data Tables */
    .data-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
    }
    .data-table th {
        background: #f8fafc;
        border-bottom: 2px solid #e2e8f0;
        padding: 0.875rem 1rem;
        font-size: 0.75rem;
        font-weight: 700;
        text-transform: uppercase;
        color: #64748b;
        text-align: left;
    }
    .data-table td {
        border-bottom: 1px solid #e2e8f0;
        padding: 0.875rem 1rem;
        color: #1e293b;
    }
    .data-table tr:hover td {
        background: #f8fafc;
    }

    /* Tab Styles */
    .tab-btn {
        padding: 0.625rem 1.25rem;
        border-radius: 0.75rem;
        font-weight: 600;
        font-size: 0.875rem;
        transition: all 0.2s;
        border: 2px solid transparent;
    }
    .tab-btn.active {
        background-color: #005696;
        color: white;
    }
    .tab-btn:not(.active) {
        background-color: white;
        color: #64748b;
        border-color: #e2e8f0;
    }
    .tab-btn:not(.active):hover {
        border-color: #005696;
        color: #005696;
    }

    /* Status Badges */
    .badge {
        padding: 0.25rem 0.75rem;
        border-radius: 9999px;
        font-size: 0.75rem;
        font-weight: 600;
    }
    .badge-blue { background: #dbeafe; color: #1d4ed8; }
    .badge-green { background: #d1fae5; color: #047857; }
    .badge-orange { background: #fef3c7; color: #b45309; }
    .badge-yellow { background: #fef9c3; color: #a16207; }
    .badge-red { background: #fee2e2; color: #b91c1c; }

    /* Animations */
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .animate-in {
        animation: fadeIn 0.4s ease-out forwards;
    }
    .delay-100 { animation-delay: 100ms; }
    .delay-200 { animation-delay: 200ms; }
    .delay-300 { animation-delay: 300ms; }
</style>
{% endblock %}

{% block content %}
<div class="px-4 py-6 max-w-[1600px] mx-auto">
    
    <!-- Page Header -->
    <div class="page-header-gradient animate-in">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 relative z-10">
            <div>
                <h1 class="text-2xl font-bold flex items-center gap-3">
                    <i data-lucide="shield-check" class="w-8 h-8"></i>
                    {% trans "Admin Evaluation" %}
                </h1>
                <p class="mt-1 opacity-90">{% trans "Staff performance analysis for complaints and inquiries" %}</p>
            </div>
            <div class="text-right">
                <p class="text-xs opacity-70 uppercase tracking-wider">{% trans "Last Updated" %}</p>
                <p class="text-sm font-bold">{% now "j M Y, H:i" %}</p>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="section-card mb-6 animate-in delay-100">
        <div class="section-header">
            <h3 class="font-bold text-navy flex items-center gap-2">
                <i data-lucide="filter" class="w-5 h-5"></i>
                {% trans "Filters" %}
            </h3>
        </div>
        <div class="p-6">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
                <!-- Date Range -->
                <div>
                    <label class="block text-xs font-bold text-slate uppercase tracking-wider mb-2">{% trans "Date Range" %}</label>
                    <select class="form-select-px360 w-full" id="dateRange" onchange="toggleCustomDates()">
                        <option value="7d" {% if date_range == '7d' %}selected{% endif %}>{% trans "Last 7 Days" %}</option>
                        <option value="30d" {% if date_range == '30d' %}selected{% endif %}>{% trans "Last 30 Days" %}</option>
                        <option value="90d" {% if date_range == '90d' %}selected{% endif %}>{% trans "Last 90 Days" %}</option>
                        <option value="this_month" {% if date_range == 'this_month' %}selected{% endif %}>{% trans "This Month" %}</option>
                        <option value="last_month" {% if date_range == 'last_month' %}selected{% endif %}>{% trans "Last Month" %}</option>
                        <option value="quarter" {% if date_range == 'quarter' %}selected{% endif %}>{% trans "This Quarter" %}</option>
                        <option value="year" {% if date_range == 'year' %}selected{% endif %}>{% trans "This Year" %}</option>
                        <option value="custom" {% if date_range == 'custom' %}selected{% endif %}>{% trans "Custom Range" %}</option>
                    </select>
                    <div id="customDateFields" class="mt-2 space-y-2 {% if date_range != 'custom' %}hidden{% endif %}">
                        <div>
                            <label class="block text-xs font-semibold text-slate mb-1">{% trans "From" %}</label>
                            <input type="date" id="customStart" class="form-select-px360 w-full"
                                   value="{% if custom_start %}{{ custom_start|date:'Y-m-d' }}{% endif %}">
                        </div>
                        <div>
                            <label class="block text-xs font-semibold text-slate mb-1">{% trans "To" %}</label>
                            <input type="date" id="customEnd" class="form-select-px360 w-full"
                                   value="{% if custom_end %}{{ custom_end|date:'Y-m-d' }}{% endif %}">
                        </div>
                        <button onclick="applyCustomDates()" class="w-full px-4 py-2 bg-navy hover:bg-blue-700 text-white rounded-xl font-bold transition text-sm">
                            {% trans "Apply" %}
                        </button>
                    </div>
                </div>

                <!-- Department Filter -->
                <div>
                    <label class="block text-xs font-bold text-slate uppercase tracking-wider mb-2">{% trans "Department" %}</label>
                    <select class="form-select-px360 w-full" id="departmentFilter" data-tomselect>
                        <option value="">{% trans "All Departments" %}</option>
                        {% for department in departments %}
                        <option value="{{ department.id }}" {% if selected_department_id == department.id|stringformat:"s" %}selected{% endif %}>
                            {{ department.name }}
                        </option>
                        {% endfor %}
                    </select>
                </div>

                <!-- Status Filter -->
                <div>
                    <label class="block text-xs font-bold text-slate uppercase tracking-wider mb-2">{% trans "Status" %}</label>
                    <select class="form-select-px360 w-full" id="statusFilter" onchange="applyFilters(document.getElementById('dateRange').value)">
                        <option value="active" {% if status_filter == 'active' %}selected{% endif %}>{% trans "Active" %}</option>
                        <option value="inactive" {% if status_filter == 'inactive' %}selected{% endif %}>{% trans "Inactive" %}</option>
                        <option value="all" {% if status_filter == 'all' %}selected{% endif %}>{% trans "All" %}</option>
                    </select>
                </div>

                <!-- Staff Filter -->
                <div>
                    <label class="block text-xs font-bold text-slate uppercase tracking-wider mb-2">{% trans "Compare Staff" %}</label>
                    <select class="form-select-px360 w-full h-[42px]" id="staffFilter" multiple>
                        {% for staff in staff_list %}
                        <option value="{{ staff.id }}" {% if staff.id|stringformat:"s" in selected_staff_ids %}selected{% endif %}>
                            {{ staff.first_name }} {{ staff.last_name }}
                        </option>
                        {% endfor %}
                    </select>
                    <button id="applyStaffFilter" class="mt-2 w-full px-4 py-2 bg-navy hover:bg-blue-700 text-white rounded-xl font-bold transition text-sm">
                        {% trans "Apply Filter" %}
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Action Buttons -->
    <div class="flex flex-wrap gap-3 mb-6 animate-in delay-100">
        <a href="{% url 'dashboard:department_benchmarks' %}?date_range={{ date_range }}" class="inline-flex items-center gap-2 px-4 py-2.5 bg-white border-2 border-navy text-navy rounded-xl font-bold hover:bg-light transition text-sm">
            <i data-lucide="bar-chart-2" class="w-4 h-4"></i>
            {% trans "Department Benchmarks" %}
        </a>
        <button onclick="exportReport('csv')" class="inline-flex items-center gap-2 px-4 py-2.5 bg-white border-2 border-emerald-500 text-emerald-600 rounded-xl font-bold hover:bg-emerald-50 transition text-sm">
            <i data-lucide="download" class="w-4 h-4"></i>
            {% trans "Export CSV" %}
        </button>
        <button onclick="exportReport('json')" class="inline-flex items-center gap-2 px-4 py-2.5 bg-white border-2 border-purple-500 text-purple-600 rounded-xl font-bold hover:bg-purple-50 transition text-sm">
            <i data-lucide="file-code" class="w-4 h-4"></i>
            {% trans "Export JSON" %}
        </button>
    </div>

    {% if performance_data.staff_metrics %}
    <!-- KPI Cards -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6 animate-in delay-100">
        <!-- Total Staff -->
        <div class="kpi-card">
            <div class="flex items-start justify-between">
                <div>
                    <p class="kpi-label mb-1">{% trans "Total Staff" %}</p>
                    <p class="kpi-value">{{ performance_data.staff_metrics|length }}</p>
                    <div class="flex items-center gap-1.5 mt-2">
                        <i data-lucide="building" class="w-4 h-4 text-blue"></i>
                        <span class="text-sm text-slate">{% trans "Active Staff" %}</span>
                    </div>
                </div>
                <div class="kpi-icon" style="background: linear-gradient(135deg, #dbeafe, #bfdbfe);">
                    <i data-lucide="users" class="w-6 h-6 text-blue-600"></i>
                </div>
            </div>
        </div>

        <!-- Total Complaints -->
        <div class="kpi-card">
            <div class="flex items-start justify-between">
                <div>
                    <p class="kpi-label mb-1">{% trans "Total Complaints" %}</p>
                    <p class="kpi-value" id="totalComplaints">0</p>
                    <div class="flex items-center gap-1.5 mt-2">
                        <i data-lucide="trending-up" class="w-4 h-4 text-red-500"></i>
                        <span class="text-xs text-slate">{% trans "Requires Attention" %}</span>
                    </div>
                </div>
                <div class="kpi-icon" style="background: linear-gradient(135deg, #fee2e2, #fecaca);">
                    <i data-lucide="alert-triangle" class="w-6 h-6 text-red-600"></i>
                </div>
            </div>
        </div>

        <!-- Total Inquiries -->
        <div class="kpi-card">
            <div class="flex items-start justify-between">
                <div>
                    <p class="kpi-label mb-1">{% trans "Total Inquiries" %}</p>
                    <p class="kpi-value" id="totalInquiries">0</p>
                    <div class="flex items-center gap-1.5 mt-2">
                        <i data-lucide="message-circle" class="w-4 h-4 text-blue"></i>
                        <span class="text-xs text-slate">{% trans "Open Requests" %}</span>
                    </div>
                </div>
                <div class="kpi-icon" style="background: linear-gradient(135deg, #dbeafe, #bfdbfe);">
                    <i data-lucide="message-circle" class="w-6 h-6 text-blue-600"></i>
                </div>
            </div>
        </div>

        <!-- Resolution Rate -->
        <div class="kpi-card">
            <div class="flex items-start justify-between">
                <div>
                    <p class="kpi-label mb-1">{% trans "Resolution Rate" %}</p>
                    <p class="kpi-value" id="resolutionRate">0%</p>
                    <div class="flex items-center gap-1.5 mt-2">
                        <i data-lucide="trending-up" class="w-4 h-4 text-emerald-500"></i>
                        <span class="text-sm font-bold text-emerald-600">{% trans "Performance" %}</span>
                    </div>
                </div>
                <div class="kpi-icon" style="background: linear-gradient(135deg, #d1fae5, #a7f3d0);">
                    <i data-lucide="check-circle" class="w-6 h-6 text-emerald-600"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Dashboard Panel -->
    <div class="section-card animate-in delay-200">
        <!-- Tabs -->
        <div class="section-header">
            <nav class="flex gap-2" id="evaluationTabs">
                <button class="tab-btn active flex items-center gap-2" data-tab="complaints" id="complaints-tab">
                    <i data-lucide="message-square-warning" class="w-4 h-4"></i>
                    {% trans "Complaints" %}
                </button>
                <button class="tab-btn flex items-center gap-2" data-tab="inquiries" id="inquiries-tab">
                    <i data-lucide="help-circle" class="w-4 h-4"></i>
                    {% trans "Inquiries" %}
                </button>
            </nav>
        </div>

        <!-- Complaints Tab Content -->
        <div id="complaints-content" class="tab-content p-6">
            <!-- Charts Row 1 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                <div class="chart-card">
                    <div class="chart-header">
                        <h3 class="font-bold text-navy flex items-center gap-2">
                            <i data-lucide="pie-chart" class="w-5 h-5"></i>
                            {% trans "Complaint Source Breakdown" %}
                        </h3>
                    </div>
                    <div class="p-4">
                        <canvas id="complaintSourceChart" class="h-64 w-full"></canvas>
                    </div>
                </div>
                <div class="chart-card">
                    <div class="chart-header">
                        <h3 class="font-bold text-navy flex items-center gap-2">
                            <i data-lucide="bar-chart-2" class="w-5 h-5"></i>
                            {% trans "Complaint Status Distribution" %}
                        </h3>
                    </div>
                    <div class="p-4">
                        <canvas id="complaintStatusChart" class="h-64 w-full"></canvas>
                    </div>
                </div>
            </div>

            <!-- Staff Performance Table -->
            <div class="section-card">
                <div class="section-header">
                    <h3 class="font-bold text-navy flex items-center gap-2">
                        <i data-lucide="users" class="w-5 h-5"></i>
                        {% trans "Staff Complaint Performance" %}
                    </h3>
                </div>
                <div class="overflow-x-auto">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>{% trans "Staff Name" %}</th>
                                <th>{% trans "Hospital" %}</th>
                                <th>{% trans "Department" %}</th>
                                <th class="text-center">{% trans "Total" %}</th>
                                <th class="text-center">{% trans "Internal" %}</th>
                                <th class="text-center">{% trans "External" %}</th>
                                <th class="text-center">{% trans "Open" %}</th>
                                <th class="text-center">{% trans "Resolved" %}</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for staff in performance_data.staff_metrics %}
                            <tr>
                                <td class="font-bold text-navy">
                                    <a href="{% url 'dashboard:staff_performance_detail' staff.id %}?date_range={{ date_range }}" class="hover:text-blue transition">
                                        {{ staff.name }}
                                    </a>
                                </td>
                                <td class="text-slate">{{ staff.hospital|default:"-" }}</td>
                                <td class="text-slate">{{ staff.department|default:"-" }}</td>
                                <td class="text-center font-bold">{{ staff.complaints.total }}</td>
                                <td class="text-center">{{ staff.complaints.internal }}</td>
                                <td class="text-center">{{ staff.complaints.external }}</td>
                                <td class="text-center">
                                    <span class="badge badge-yellow">{{ staff.complaints.status.open }}</span>
                                </td>
                                <td class="text-center">
                                    <span class="badge badge-green">{{ staff.complaints.status.resolved }}</span>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Inquiries Tab Content -->
        <div id="inquiries-content" class="tab-content hidden p-6">
            <!-- Charts Row -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                <div class="chart-card">
                    <div class="chart-header">
                        <h3 class="font-bold text-navy flex items-center gap-2">
                            <i data-lucide="bar-chart-2" class="w-5 h-5"></i>
                            {% trans "Inquiry Status Distribution" %}
                        </h3>
                    </div>
                    <div class="p-4">
                        <canvas id="inquiryStatusChart" class="h-64 w-full"></canvas>
                    </div>
                </div>
                <div class="chart-card">
                    <div class="chart-header">
                        <h3 class="font-bold text-navy flex items-center gap-2">
                            <i data-lucide="gauge" class="w-5 h-5"></i>
                            {% trans "Inquiry Response Time" %}
                        </h3>
                    </div>
                    <div class="p-4">
                        <canvas id="inquiryResponseChart" class="h-64 w-full"></canvas>
                    </div>
                </div>
            </div>

            <!-- Staff Performance Table -->
            <div class="section-card">
                <div class="section-header">
                    <h3 class="font-bold text-navy flex items-center gap-2">
                        <i data-lucide="users" class="w-5 h-5"></i>
                        {% trans "Staff Inquiry Performance" %}
                    </h3>
                </div>
                <div class="overflow-x-auto">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>{% trans "Staff Name" %}</th>
                                <th>{% trans "Hospital" %}</th>
                                <th>{% trans "Department" %}</th>
                                <th class="text-center">{% trans "Total" %}</th>
                                <th class="text-center">{% trans "Open" %}</th>
                                <th class="text-center">{% trans "Resolved" %}</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for staff in performance_data.staff_metrics %}
                            <tr>
                                <td class="font-bold text-navy">{{ staff.name }}</td>
                                <td class="text-slate">{{ staff.hospital|default:"-" }}</td>
                                <td class="text-slate">{{ staff.department|default:"-" }}</td>
                                <td class="text-center font-bold">{{ staff.inquiries.total }}</td>
                                <td class="text-center">
                                    <span class="badge badge-yellow">{{ staff.inquiries.status.open }}</span>
                                </td>
                                <td class="text-center">
                                    <span class="badge badge-green">{{ staff.inquiries.status.resolved }}</span>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    {% else %}
    <!-- No Data State -->
    <div class="section-card p-12 text-center animate-in delay-100">
        <div class="w-20 h-20 bg-blue-50 rounded-full flex items-center justify-center mx-auto mb-6">
            <i data-lucide="users" class="w-10 h-10 text-blue"></i>
        </div>
        <h3 class="text-xl font-bold text-navy mb-2">{% trans "No Data Available" %}</h3>
        <p class="text-slate max-w-md mx-auto">{% trans "No staff members with assigned complaints or inquiries found in the selected time period." %}</p>
    </div>
    {% endif %}

</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
{{ performance_data|json_script:"performanceData" }}
<script>
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();

    // Tab switching
    const tabs = document.querySelectorAll('#evaluationTabs button[data-tab]');
    const contents = document.querySelectorAll('.tab-content');

    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            const tabName = this.dataset.tab;
            tabs.forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            contents.forEach(content => {
                if (content.id === `${tabName}-content`) {
                    content.classList.remove('hidden');
                } else {
                    content.classList.add('hidden');
                }
            });
        });
    });

    // Initialize charts
    const performanceData = JSON.parse(document.getElementById('performanceData').textContent);
    if (performanceData && performanceData.staff_metrics) {
        initCharts(performanceData);
        updateSummaryCards(performanceData);
    }
});

function initCharts(data) {
    if (typeof Chart === 'undefined') return;
    
    Chart.defaults.color = '#64748b';
    Chart.defaults.borderColor = '#e2e8f0';

    // Complaint Source Chart
    const sourceCtx = document.getElementById('complaintSourceChart');
    if (sourceCtx) {
        new Chart(sourceCtx, {
            type: 'doughnut',
            data: {
                labels: ['Internal', 'External'],
                datasets: [{
                    data: [data.totals?.complaints_internal || 0, data.totals?.complaints_external || 0],
                    backgroundColor: ['#3b82f6', '#10b981'],
                    borderColor: '#ffffff',
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { position: 'bottom', labels: { padding: 15, usePointStyle: true } }
                }
            }
        });
    }

    // Complaint Status Chart
    const statusCtx = document.getElementById('complaintStatusChart');
    if (statusCtx) {
        new Chart(statusCtx, {
            type: 'bar',
            data: {
                labels: ['Open', 'In Progress', 'Resolved', 'Closed'],
                datasets: [{
                    label: 'Complaints',
                    data: [
                        data.totals?.complaints_open || 0,
                        data.totals?.complaints_in_progress || 0,
                        data.totals?.complaints_resolved || 0,
                        data.totals?.complaints_closed || 0
                    ],
                    backgroundColor: ['#f59e0b', '#3b82f6', '#10b981', '#64748b'],
                    borderRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    y: { beginAtZero: true, grid: { color: '#e2e8f0' } },
                    x: { grid: { display: false } }
                }
            }
        });
    }

    // Inquiry Status Chart
    const inquiryStatusCtx = document.getElementById('inquiryStatusChart');
    if (inquiryStatusCtx) {
        new Chart(inquiryStatusCtx, {
            type: 'doughnut',
            data: {
                labels: ['Open', 'In Progress', 'Resolved', 'Closed'],
                datasets: [{
                    data: [
                        data.totals?.inquiries_open || 0,
                        data.totals?.inquiries_in_progress || 0,
                        data.totals?.inquiries_resolved || 0,
                        data.totals?.inquiries_closed || 0
                    ],
                    backgroundColor: ['#f59e0b', '#3b82f6', '#10b981', '#64748b'],
                    borderColor: '#ffffff',
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { position: 'bottom', labels: { padding: 15, usePointStyle: true } }
                }
            }
        });
    }

    // Inquiry Response Chart
    const inquiryResponseCtx = document.getElementById('inquiryResponseChart');
    if (inquiryResponseCtx) {
        new Chart(inquiryResponseCtx, {
            type: 'bar',
            data: {
                labels: ['≤24h', '≤48h', '≤72h', '>72h'],
                datasets: [{
                    label: 'Response Time',
                    data: [
                        data.totals?.inquiries_within_24h || 0,
                        data.totals?.inquiries_within_48h || 0,
                        data.totals?.inquiries_within_72h || 0,
                        data.totals?.inquiries_over_72h || 0
                    ],
                    backgroundColor: ['#10b981', '#3b82f6', '#f59e0b', '#ef4444'],
                    borderRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    y: { beginAtZero: true, grid: { color: '#e2e8f0' } },
                    x: { grid: { display: false } }
                }
            }
        });
    }
}

function updateSummaryCards(data) {
    const totalComplaints = data.totals?.complaints_total || 0;
    const totalInquiries = data.totals?.inquiries_total || 0;
    const resolvedComplaints = data.totals?.complaints_resolved || 0;
    const resolutionRate = totalComplaints > 0 ? Math.round((resolvedComplaints / totalComplaints) * 100) : 0;
    
    document.getElementById('totalComplaints').textContent = totalComplaints;
    document.getElementById('totalInquiries').textContent = totalInquiries;
    document.getElementById('resolutionRate').textContent = resolutionRate + '%';
}

function toggleCustomDates() {
    const dateRange = document.getElementById('dateRange').value;
    const customFields = document.getElementById('customDateFields');
    if (dateRange === 'custom') {
        customFields.classList.remove('hidden');
    } else {
        customFields.classList.add('hidden');
        // Auto-submit for preset ranges
        applyFilters(dateRange);
    }
}

function applyCustomDates() {
    const startDate = document.getElementById('customStart').value;
    const endDate = document.getElementById('customEnd').value;
    if (!startDate || !endDate) {
        alert('{% trans "Please select both start and end dates." %}');
        return;
    }
    if (startDate > endDate) {
        alert('{% trans "Start date must be before end date." %}');
        return;
    }
    applyFilters('custom', startDate, endDate);
}

function applyFilters(dateRange, customStart, customEnd) {
    const department = document.getElementById('departmentFilter')?.value || '';
    const status = document.getElementById('statusFilter')?.value || 'active';
    const staffSelect = document.getElementById('staffFilter');
    const selectedStaff = staffSelect ? Array.from(staffSelect.selectedOptions).map(opt => opt.value) : [];
    
    const params = new URLSearchParams();
    params.append('date_range', dateRange);
    if (customStart) params.append('custom_start', customStart);
    if (customEnd) params.append('custom_end', customEnd);
    if (department) params.append('department_id', department);
    if (status && status !== 'all') params.append('status', status);
    selectedStaff.forEach(id => params.append('staff_ids', id));
    
    window.location.href = window.location.pathname + '?' + params.toString();
}

function exportReport(format) {
    const dateRange = document.getElementById('dateRange').value;
    const hospital = '{{ current_hospital.id|default:"" }}';
    const department = document.getElementById('departmentFilter')?.value || '';
    
    const params = new URLSearchParams({
        date_range: dateRange,
        format: format,
        hospital: hospital,
        department: department
    });

    // Include custom dates if selected
    if (dateRange === 'custom') {
        const customStart = document.getElementById('customStart').value;
        const customEnd = document.getElementById('customEnd').value;
        if (customStart) params.append('custom_start', customStart);
        if (customEnd) params.append('custom_end', customEnd);
    }
    
    window.location.href = `/dashboard/admin-evaluation/export/?${params.toString()}`;
}
</script>
{% endblock %}
