{% extends 'dashboards/base_dashboard.html' %}
{% load humanize %}

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

{% block stats %}
<div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">Director General Dashboard</h1>
    <div>
        <a href="{% url 'reports:department_performance' department_id=department.id %}" class="btn btn-primary btn-sm">
            <i class="fas fa-download fa-sm text-white-50"></i> Generate Report
        </a>
    </div>
</div>

<!-- Stats Cards -->
<div class="col-xl-3 col-md-6 mb-4">
    <div class="card border-left-primary shadow h-100 py-2">
        <div class="card-body">
            <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                        Department</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ department.name }}</div>
                </div>
                <div class="col-auto">
                    <i class="fas fa-building fa-2x text-gray-300"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="col-xl-3 col-md-6 mb-4">
    <div class="card border-left-success shadow h-100 py-2">
        <div class="card-body">
            <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                        Team Members</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ total_users }}</div>
                </div>
                <div class="col-auto">
                    <i class="fas fa-users fa-2x text-gray-300"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="col-xl-3 col-md-6 mb-4">
    <div class="card border-left-warning shadow h-100 py-2">
        <div class="card-body">
            <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                        Pending Tasks</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ pending_tasks }}</div>
                </div>
                <div class="col-auto">
                    <i class="fas fa-tasks fa-2x text-gray-300"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="col-xl-3 col-md-6 mb-4">
    <div class="card border-left-info shadow h-100 py-2">
        <div class="card-body">
            <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                    <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                        Total Tasks</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ total_tasks }}</div>
                </div>
                <div class="col-auto">
                    <i class="fas fa-clipboard-list fa-2x text-gray-300"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- TaskFlow Statistics -->
<div class="row">
    <!-- Task Status Chart -->
    <div class="col-lg-8 mb-4">
        <div class="card shadow h-100">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">TaskFlow Overview</h6>
                <a href="{% url 'tasks:task-list' %}" class="btn btn-sm btn-primary">
                    <i class="fas fa-tasks me-1"></i> View All Tasks
                </a>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-4">
                        <div class="card border-left-primary h-100">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                            Total Tasks</div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">{{ total_tasks|default:0 }}</div>
                                    </div>
                                    <i class="fas fa-clipboard-list fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 mb-4">
                        <div class="card border-left-success h-100">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                            Completed Tasks</div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">{{ completed_tasks|default:0 }}</div>
                                    </div>
                                    <i class="fas fa-check-circle fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 mb-4">
                        <div class="card border-left-warning h-100">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                            In Progress</div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">{{ in_progress_tasks|default:0 }}</div>
                                    </div>
                                    <i class="fas fa-sync-alt fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 mb-4">
                        <div class="card border-left-danger h-100">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">
                                            Pending</div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">{{ pending_tasks|default:0 }}</div>
                                    </div>
                                    <i class="fas fa-clock fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Task Status Chart -->
    <div class="col-lg-4 mb-4">
        <div class="card shadow h-100">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">Task Status Distribution</h6>
            </div>
            <div class="card-body">
                <div class="chart-pie pt-4 pb-2">
                    <canvas id="taskStatusChart"></canvas>
                </div>
                <div class="mt-4 text-center small">
                    <span class="mr-2">
                        <i class="fas fa-circle text-warning"></i> Pending ({{ pending_tasks|default:0 }})
                    </span>
                    <span class="mr-2">
                        <i class="fas fa-circle text-primary"></i> In Progress ({{ in_progress_tasks|default:0 }})
                    </span>
                    <span class="mr-2">
                        <i class="fas fa-circle text-success"></i> Completed ({{ completed_tasks|default:0 }})
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Recent Tasks -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center">
        <h6 class="m-0 font-weight-bold text-primary">Recent Tasks</h6>
        <a href="{% url 'tasks:task-create' %}" class="btn btn-sm btn-primary">
            <i class="fas fa-plus me-1"></i> New Task
        </a>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Assigned To</th>
                        <th>Status</th>
                        <th>Due Date</th>
                    </tr>
                </thead>
                <tbody>
                    {% for task in recent_tasks %}
                    <tr>
                        <td>
                            <a href="{% url 'tasks:task-detail' task.id %}">{{ task.title|truncatechars:30 }}</a>
                            {% if task.due_date < now.date and task.status != 'completed' %}
                                <span class="badge bg-danger">Overdue</span>
                            {% endif %}
                        </td>
                        <td>{{ task.assigned_to.get_full_name|default:task.assigned_to.email }}</td>
                        <td>
                            <span class="badge {% if task.status == 'completed' %}bg-success
                                {% elif task.status == 'in_progress' %}bg-primary
                                {% else %}bg-warning{% endif %}">
                                {{ task.get_status_display }}
                            </span>
                        </td>
                        <td>{{ task.due_date|date:"M d, Y" }}</td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="4" class="text-center">No tasks found</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Recent Tasks in Department -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
        <h6 class="m-0 font-weight-bold text-primary">Recent Tasks in {{ department.name }}</h6>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Section</th>
                        <th>Assigned To</th>
                        <th>Status</th>
                        <th>Due Date</th>
                    </tr>
                </thead>
                <tbody>
                    {% for task in recent_tasks %}
                    <tr>
                        <td>{{ task.title }}</td>
                        <td>{{ task.assigned_to.department.name|default:"-" }}</td>
                        <td>{{ task.assigned_to.get_full_name|default:task.assigned_to.email }}</td>
                        <td><span class="badge {% if task.status == 'completed' %}bg-success{% else %}bg-warning{% endif %}">
                            {{ task.get_status_display }}
                        </span></td>
                        <td>{{ task.due_date|date:"M d, Y" }}</td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="5" class="text-center">No tasks found in your department</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Heads of Sections -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center">
        <h6 class="m-0 font-weight-bold text-primary">Heads of Sections</h6>
        {% if user.department %}
        <a href="{% url 'users:user_create' %}?role=head" class="btn btn-sm btn-primary">
            <i class="fas fa-user-plus me-1"></i> Add Head of Section
        </a>
        {% endif %}
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Section</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {% for head in heads_of_sections %}
                    <tr>
                        <td>{{ head.get_full_name|default:head.username }}</td>
                        <td>{{ head.email }}</td>
                        <td>{{ head.department.name|default:"-" }}</td>
                        <td>
                            {% if user.is_staff or user.department %}
                            <a href="{% url 'users:user_update' head.id %}" class="btn btn-sm btn-primary" data-toggle="tooltip" title="Edit">
                                <i class="fas fa-edit"></i>
                            </a>
                            <a href="{% url 'users:user_delete' head.id %}" class="btn btn-sm btn-danger" data-toggle="tooltip" title="Delete"
                               onclick="return confirm('Are you sure you want to delete this head of section?')">
                                <i class="fas fa-trash"></i>
                            </a>
                            {% else %}
                            <span class="text-muted">No actions available</span>
                            {% endif %}
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="4" class="text-center">
                            No heads of sections found. 
                            {% if user.department %}
                            <a href="{% url 'users:user_create' %}?role=head">Add a head of section</a>.
                            {% endif %}
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
//<![CDATA[
// Task Status Pie Chart
document.addEventListener('DOMContentLoaded', function() {
    // Initialize task status chart if element exists
    var taskStatusCtx = document.getElementById('taskStatusChart');
    if (taskStatusCtx) {
        var taskStatusData = {
            labels: JSON.parse('{{ task_status_data.labels|escapejs|safe }}'),
            datasets: [{
                data: JSON.parse('{{ task_status_data.data|escapejs|safe }}'),
                backgroundColor: JSON.parse('{{ task_status_data.colors|escapejs|safe }}'),
                hoverBackgroundColor: ['#f8d16e', '#6c8fd3', '#36b9cc'],
                hoverBorderColor: "rgba(234, 236, 244, 1)"
            }]
        };
        
        var taskStatusOptions = {
            maintainAspectRatio: false,
            tooltips: {
                backgroundColor: "rgb(255,255,255)",
                bodyFontColor: "#858796",
                borderColor: '#dddfeb',
                borderWidth: 1,
                xPadding: 15,
                yPadding: 15,
                displayColors: false,
                caretPadding: 10
            },
            legend: {
                display: false
            },
            cutoutPercentage: 70
        };
        
        new Chart(taskStatusCtx.getContext('2d'), {
            type: 'doughnut',
            data: taskStatusData,
            options: taskStatusOptions
        });
    }

    // Initialize section tasks chart if element exists
    var sectionTasksCtx = document.getElementById('sectionTasksChart');
    if (sectionTasksCtx) {
        // Prepare data for the chart
        var sectionLabels = [];
        var pendingData = [];
        var inProgressData = [];
        var completedData = [];
        
        // Process the template data into separate arrays
        {% for section in tasks_by_section %}
            sectionLabels.push('{{ section.assigned_to__department__name|default:"Unassigned"|escapejs }}');
            pendingData.push({{ section.pending|default:0 }});
            inProgressData.push({{ section.in_progress|default:0 }});
            completedData.push({{ section.completed|default:0 }});
        {% endfor %}
        
        var sectionTasksData = {
            labels: sectionLabels,
            datasets: [
                {
                    label: 'Pending',
                    backgroundColor: '#f6c23e',
                    data: pendingData
                },
                {
                    label: 'In Progress',
                    backgroundColor: '#4e73df',
                    data: inProgressData
                },
                {
                    label: 'Completed',
                    backgroundColor: '#1cc88a',
                    data: completedData
                }
            ]
        };
        
        var sectionTasksOptions = {
            maintainAspectRatio: false,
            layout: {
                padding: {
                    left: 10,
                    right: 25,
                    top: 25,
                    bottom: 0
                }
            },
            scales: {
                x: {
                    stacked: true,
                    grid: {
                        display: false,
                        drawBorder: false
                    },
                    ticks: {
                        maxTicksLimit: 6
                    }
                },
                y: {
                    stacked: true,
                    ticks: {
                        beginAtZero: true,
                        maxTicksLimit: 5,
                        padding: 10
                    },
                    grid: {
                        color: "rgb(234, 236, 244)",
                        zeroLineColor: "rgb(234, 236, 244)",
                        drawBorder: false,
                        borderDash: [2],
                        zeroLineBorderDash: [2]
                    }
                }
            },
            plugins: {
                legend: {
                    position: 'top'
                },
                tooltip: {
                    titleMarginBottom: 10,
                    titleFontColor: '#6e707e',
                    titleFontSize: 14,
                    backgroundColor: "rgb(255,255,255)",
                    bodyFontColor: "#858796",
                    borderColor: '#dddfeb',
                    borderWidth: 1,
                    xPadding: 15,
                    yPadding: 15,
                    displayColors: true,
                    caretPadding: 10
                }
            }
        };
        
        new Chart(sectionTasksCtx, {
            type: 'bar',
            data: sectionTasksData,
            options: sectionTasksOptions
        });
    }

    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();
});
//]]>
</script>
{% endblock %}
