{% extends "base.html" %}
{% from "components/ui.html" import page_header, empty_state, alert %}

{% block title %}{{ _('Overdue Tasks') }} - Time Tracker{% endblock %}

{% block content %}
{% set breadcrumbs = [
    {'text': _('Tasks'), 'url': url_for('tasks.list_tasks')},
    {'text': _('Overdue Tasks')}
] %}
{% set actions %}
<a href="{{ url_for('tasks.list_tasks') }}" class="btn btn-secondary btn-sm">
    <i class="fas fa-arrow-left"></i> {{ _('Back to Tasks') }}
</a>
{% endset %}

{{ page_header(
    'fas fa-exclamation-triangle',
    _('Overdue Tasks'),
    subtitle_text=_('Requires immediate attention') ~ ' • ' ~ (tasks|length) ~ ' ' ~ _('items'),
    actions_html=actions,
    breadcrumbs=breadcrumbs
) }}

<!-- Overdue Summary -->
{{ alert(_('There are') ~ ' ' ~ (tasks|length) ~ ' ' ~ _('overdue tasks that require immediate attention. Please review and update these tasks to prevent further delays.'), type='warning', icon='fa-exclamation-triangle') }}

<!-- Overdue Tasks List -->
{% if tasks %}
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
    {% for task in tasks %}
    <div class="bg-card-light dark:bg-card-dark rounded-xl border-2 border-red-200 dark:border-red-800 shadow-sm overflow-hidden transition-all duration-200 hover:shadow-md">
        <div class="flex justify-between items-center px-4 py-2 bg-red-500/10 dark:bg-red-900/20 border-b border-border-light dark:border-border-dark">
            <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300">
                <i class="fas fa-exclamation-triangle"></i> {{ _('Overdue') }}
            </span>
            {% if task.priority_display %}
            <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium priority-badge priority-{{ task.priority }}">
                {{ task.priority_display }}
            </span>
            {% endif %}
        </div>
        <div class="p-4">
            <h3 class="text-base font-semibold text-text-light dark:text-text-dark mb-2">
                <a href="{{ url_for('tasks.view_task', task_id=task.id) }}" class="hover:text-primary transition-colors">
                    {{ task.name }}
                </a>
            </h3>
            {% if task.description %}
            <p class="text-sm text-text-muted-light dark:text-text-muted-dark mb-3 line-clamp-2">{{ task.description[:100] }}{% if task.description|length > 100 %}...{% endif %}</p>
            {% endif %}
            <div class="space-y-1 text-sm text-text-muted-light dark:text-text-muted-dark">
                <div><i class="fas fa-project-diagram w-4 mr-2 text-primary/70"></i>{{ task.project.name }}</div>
                <div><i class="fas fa-user w-4 mr-2 text-primary/70"></i>{% if task.assigned_user %}{{ task.assigned_user.display_name }}{% else %}{{ _('Unassigned') }}{% endif %}</div>
                <div class="font-semibold text-red-600 dark:text-red-400"><i class="fas fa-calendar w-4 mr-2"></i>{{ _('Due:') }} {{ task.due_date|format_date }}</div>
                {% if task.estimated_hours %}<div><i class="fas fa-clock w-4 mr-2 text-primary/70"></i>{{ _('Est:') }} {{ task.estimated_hours }}h</div>{% endif %}
                {% if task.total_hours > 0 %}<div><i class="fas fa-stopwatch w-4 mr-2 text-primary/70"></i>{{ _('Actual:') }} {{ task.total_hours }}h</div>{% endif %}
            </div>
            {% if task.estimated_hours and task.total_hours > 0 %}
            <div class="mt-3">
                <div class="flex justify-between text-xs text-text-muted-light dark:text-text-muted-dark mb-1">
                    <span>{{ _('Progress') }}</span>
                    <span>{{ task.progress_percentage }}%</span>
                </div>
                <div class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2 overflow-hidden">
                    <div class="bg-primary h-full rounded-full transition-all" style="width: {{ task.progress_percentage }}%"></div>
                </div>
            </div>
            {% endif %}
        </div>
        <div class="px-4 py-3 bg-background-light dark:bg-background-dark border-t border-border-light dark:border-border-dark flex flex-wrap gap-2">
            <a href="{{ url_for('tasks.view_task', task_id=task.id) }}" class="btn btn-ghost btn-sm"><i class="fas fa-eye"></i> {{ _('View') }}</a>
            {% if current_user.is_admin or task.created_by == current_user.id %}
            <a href="{{ url_for('tasks.edit_task', task_id=task.id) }}" class="btn btn-ghost btn-sm"><i class="fas fa-edit"></i> {{ _('Edit') }}</a>
            {% endif %}
            <a href="{{ url_for('timer.start_timer_for_project', project_id=task.project.id, task_id=task.id) }}" class="btn btn-primary btn-sm"><i class="fas fa-play"></i> {{ _('Timer') }}</a>
        </div>
    </div>
    {% endfor %}
</div>

<!-- Bulk Actions -->
<div class="bg-card-light dark:bg-card-dark rounded-xl border border-border-light dark:border-border-dark shadow-sm overflow-hidden">
    <div class="px-6 py-4 border-b border-border-light dark:border-border-dark">
        <h3 class="text-lg font-semibold text-text-light dark:text-text-dark"><i class="fas fa-tools mr-2"></i>{{ _('Bulk Actions') }}</h3>
    </div>
    <div class="p-6 grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
            <h4 class="text-sm font-semibold text-text-light dark:text-text-dark mb-1">{{ _('Update Due Dates') }}</h4>
            <p class="text-sm text-text-muted-light dark:text-text-muted-dark mb-3">{{ _('Extend due dates for multiple tasks at once') }}</p>
            <button type="button" class="btn btn-secondary" onclick="extendDueDates()"><i class="fas fa-calendar-plus"></i> {{ _('Extend Due Dates') }}</button>
        </div>
        <div>
            <h4 class="text-sm font-semibold text-text-light dark:text-text-dark mb-1">{{ _('Priority Management') }}</h4>
            <p class="text-sm text-text-muted-light dark:text-text-muted-dark mb-3">{{ _('Adjust priorities for overdue tasks') }}</p>
            <button type="button" class="btn btn-secondary" onclick="adjustPriorities()"><i class="fas fa-arrow-up"></i> {{ _('Adjust Priorities') }}</button>
        </div>
    </div>
</div>
{% else %}
{% set actions %}
<a href="{{ url_for('tasks.list_tasks') }}" class="btn btn-primary"><i class="fas fa-list"></i> {{ _('View All Tasks') }}</a>
{% endset %}
{{ empty_state('fas fa-check-circle', _('No Overdue Tasks!'), _('Great job! All tasks are currently on schedule.'), actions, type='success') }}
{% endif %}

<script type="application/json" id="i18n-json-tasks-overdue">
{
    "enter_new_due_date": {{ _('Enter new due date (YYYY-MM-DD):')|tojson }},
    "confirm_extend_prefix": {{ _('Are you sure you want to extend the due date to')|tojson }},
    "confirm_extend_suffix": {{ _('for all overdue tasks?')|tojson }},
    "enter_new_priority": {{ _('Enter new priority (low/medium/high/urgent):')|tojson }},
    "confirm_set_priority_prefix": {{ _('Are you sure you want to set priority to')|tojson }},
    "confirm_set_priority_suffix": {{ _('for all overdue tasks?')|tojson }},
    "invalid_priority": {{ _('Invalid priority. Please use: low, medium, high, or urgent')|tojson }},
    "updated_success": {{ _('Updated %(count)s task(s). Reloading...')|tojson }},
    "error_message": {{ _('Update failed. Please try again.')|tojson }}
}
</script>
<script>
var i18n_overdue = (function(){
    try { var el = document.getElementById('i18n-json-tasks-overdue'); return el ? JSON.parse(el.textContent) : {}; }
    catch(e) { return {}; }
})();
var overdueTaskIds = [{% for t in tasks %}{{ t.id }}{% if not loop.last %}, {% endif %}{% endfor %}];

function getCsrfHeaders() {
    var token = document.querySelector('meta[name="csrf-token"]');
    return { 'Content-Type': 'application/json', 'X-CSRFToken': token ? token.getAttribute('content') : '' };
}

async function extendDueDates() {
    if (!overdueTaskIds.length) return;
    const newDate = prompt(i18n_overdue.enter_new_due_date || 'Enter new due date (YYYY-MM-DD):', new Date().toISOString().split('T')[0]);
    if (!newDate) return;
    var p = i18n_overdue.confirm_extend_prefix || 'Are you sure you want to extend the due date to';
    var s = i18n_overdue.confirm_extend_suffix || 'for all overdue tasks?';
    const confirmed = typeof showConfirm === 'function'
        ? await showConfirm(p + ' ' + newDate + ' ' + s, { title: 'Extend Due Dates', confirmText: 'Extend', cancelText: 'Cancel', variant: 'primary' })
        : confirm(p + ' ' + newDate + ' ' + s);
    if (!confirmed) return;
    try {
        var r = await fetch('{{ url_for("tasks.bulk_update_due_date") }}', {
            method: 'POST',
            headers: getCsrfHeaders(),
            body: JSON.stringify({ task_ids: overdueTaskIds, due_date: newDate })
        });
        var data = await r.json().catch(function() { return {}; });
        if (r.ok && data.success) {
            if (window.toastManager && typeof window.toastManager.show === 'function') {
                window.toastManager.show({ message: (data.message || data.updated + ' updated'), type: 'success' });
            } else {
                alert((data.message || data.updated + ' updated') + ' ' + (i18n_overdue.updated_success || 'Reloading...'));
            }
            window.location.reload();
        } else {
            alert(data.message || i18n_overdue.error_message || 'Update failed.');
        }
    } catch (e) {
        alert(i18n_overdue.error_message || 'Update failed. Please try again.');
    }
}

async function adjustPriorities() {
    if (!overdueTaskIds.length) return;
    const newPriority = prompt(i18n_overdue.enter_new_priority || 'Enter new priority (low/medium/high/urgent):', 'high');
    if (!newPriority) return;
    if (!['low', 'medium', 'high', 'urgent'].includes(newPriority.toLowerCase())) {
        alert(i18n_overdue.invalid_priority || 'Invalid priority. Please use: low, medium, high, or urgent');
        return;
    }
    var p2 = i18n_overdue.confirm_set_priority_prefix || 'Are you sure you want to set priority to';
    var s2 = i18n_overdue.confirm_set_priority_suffix || 'for all overdue tasks?';
    const confirmed = typeof showConfirm === 'function'
        ? await showConfirm(p2 + ' ' + newPriority + ' ' + s2, { title: 'Adjust Priorities', confirmText: 'Update', cancelText: 'Cancel', variant: 'primary' })
        : confirm(p2 + ' ' + newPriority + ' ' + s2);
    if (!confirmed) return;
    try {
        var r = await fetch('{{ url_for("tasks.bulk_update_priority") }}', {
            method: 'POST',
            headers: getCsrfHeaders(),
            body: JSON.stringify({ task_ids: overdueTaskIds, priority: newPriority.toLowerCase() })
        });
        var data = await r.json().catch(function() { return {}; });
        if (r.ok && data.success) {
            if (window.toastManager && typeof window.toastManager.show === 'function') {
                window.toastManager.show({ message: (data.message || data.updated + ' updated'), type: 'success' });
            } else {
                alert((data.message || data.updated + ' updated') + ' ' + (i18n_overdue.updated_success || 'Reloading...'));
            }
            window.location.reload();
        } else {
            alert(data.message || i18n_overdue.error_message || 'Update failed.');
        }
    } catch (e) {
        alert(i18n_overdue.error_message || 'Update failed. Please try again.');
    }
}
</script>
<style>
.priority-badge.priority-low { @apply bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300; }
.priority-badge.priority-medium { @apply bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300; }
.priority-badge.priority-high { @apply bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300; }
.priority-badge.priority-urgent { @apply bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300; }
</style>
{% endblock %}
