{% extends "base.html" %}

{% block title %}Dashboard - {{ app_name }}{% endblock %}

{% block content %}
{% from "_components.html" import page_header %}
<!-- Toast Container -->
<div id="toast-container" class="toast-container position-fixed top-0 end-0 p-3"></div>

<!-- Template meta for JS flags -->
<div id="dashboard-meta" data-has-active-timer="{{ 1 if active_timer else 0 }}" style="display:none;"></div>

<!-- Page Header matching admin style -->
<div class="row">
    <div class="col-12">
        {% set actions %}
        <a href="{{ url_for('timer.manual_entry') }}" class="btn btn-outline-light btn-sm">
            <i class="fas fa-plus"></i> Log Time
        </a>
        <a href="{{ url_for('reports.reports') }}" class="btn btn-outline-light btn-sm">
            <i class="fas fa-chart-line"></i> Reports
        </a>
        {% endset %}
        {{ page_header('fas fa-tachometer-alt', 'Dashboard', 'Welcome back, ' ~ current_user.display_name ~ ' • ' ~ (today_hours|round(1)) ~ 'h today', actions) }}
    </div>
</div>

<!-- Enhanced Timer Section -->
<div class="row section-spacing">
    <div class="col-12">
        <div class="card mobile-card hover-lift">
            <div class="card-header">
                <h5 class="mb-0 d-flex align-items-center">
                    <i class="fas fa-clock me-3 text-primary"></i>Timer Status
                </h5>
            </div>
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-lg-8 col-md-7 mb-4 mb-md-0">
                        {% if active_timer %}
                        <div class="d-flex align-items-center flex-column flex-md-row">
                            <div class="me-0 me-md-4 mb-4 mb-md-0">
                                <div class="bg-success bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center" style="width: 72px; height: 72px;">
                                    <i class="fas fa-play text-success fa-2x"></i>
                                </div>
                            </div>
                            <div class="text-center text-md-start">
                                <h4 class="mb-2 text-success fw-bold">Timer Running</h4>
                                <p class="mb-3 text-muted fs-6">
                                    <i class="fas fa-project-diagram me-2"></i>{{ active_timer.project.name }}{% if active_timer.task %} <span class="text-muted">•</span> <i class="fas fa-tasks ms-2 me-1"></i>{{ active_timer.task.name }}{% endif %}
                                </p>
                                <div class="timer-display mb-2" id="timer-display">
                                    {{ active_timer.duration_formatted }}
                                </div>
                                <small class="text-muted fs-6">
                                    Started at {{ active_timer.start_time.strftime('%H:%M') }}
                                </small>
                            </div>
                        </div>
                        {% else %}
                        <div class="d-flex align-items-center flex-column flex-md-row">
                            <div class="me-0 me-md-4 mb-4 mb-md-0">
                                <div class="bg-light rounded-circle d-flex align-items-center justify-content-center" style="width: 72px; height: 72px;">
                                    <i class="fas fa-stop text-muted fa-2x"></i>
                                </div>
                            </div>
                            <div class="text-center text-md-start">
                                <h4 class="mb-2 text-muted fw-bold">No Active Timer</h4>
                                <p class="text-muted mb-1 fs-6">Choose a project or one of its tasks to start tracking.</p>
                                <div class="mt-2">
                                    <span class="badge bg-light text-dark fs-6">Idle</span>
                                </div>
                            </div>
                        </div>
                        {% endif %}
                    </div>
                    <div class="col-lg-4 col-md-5 text-center">
                        {% if active_timer %}
                        <form method="POST" action="{{ url_for('timer.stop_timer') }}" class="d-inline w-100">
                            <button type="submit" class="btn btn-danger px-4 w-100 w-md-auto touch-target fw-bold">
                                <i class="fas fa-stop me-2"></i>Stop Timer
                            </button>
                        </form>
                        {% else %}
                        <button type="button" class="btn btn-success px-4 w-100 w-md-auto touch-target fw-bold" data-bs-toggle="modal" data-bs-target="#startTimerModal">
                            <i class="fas fa-play me-2"></i>Start Timer
                        </button>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Enhanced Statistics Cards -->
<div class="row section-spacing">
    <div class="col-lg-4 col-md-6 mb-3">
        <div class="card h-100 mobile-card hover-lift">
            <div class="card-body text-center py-4">
                <div class="bg-primary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center mx-auto mb-3" style="width: 72px; height: 72px;">
                    <i class="fas fa-calendar-day text-primary fa-2x"></i>
                </div>
                <h3 class="h1 text-primary mb-2 fw-bold">{{ "%.1f"|format(today_hours) }}</h3>
                <p class="mb-2 fw-semibold fs-5">Hours Today</p>
                <small class="text-muted fs-6">
                    {% if today_hours > 0 %}Active day{% else %}No activity yet{% endif %}
                </small>
            </div>
        </div>
    </div>
    <div class="col-lg-4 col-md-6 mb-3">
        <div class="card h-100 mobile-card hover-lift">
            <div class="card-body text-center py-4">
                <div class="bg-success bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center mx-auto mb-3" style="width: 72px; height: 72px;">
                    <i class="fas fa-calendar-week text-success fa-2x"></i>
                </div>
                <h3 class="h1 text-success mb-2 fw-bold">{{ "%.1f"|format(week_hours) }}</h3>
                <p class="mb-2 fw-semibold fs-5">Hours This Week</p>
                <small class="text-muted fs-6">
                    {% if week_hours > 0 %}Good progress{% else %}Start tracking{% endif %}
                </small>
            </div>
        </div>
    </div>
    <div class="col-lg-4 col-md-6 mb-3">
        <div class="card h-100 mobile-card hover-lift">
            <div class="card-body text-center py-4">
                <div class="bg-info bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center mx-auto mb-3" style="width: 72px; height: 72px;">
                    <i class="fas fa-calendar-alt text-info fa-2x"></i>
                </div>
                <h3 class="h1 text-info mb-2 fw-bold">{{ "%.1f"|format(month_hours) }}</h3>
                <p class="mb-2 fw-semibold fs-5">Hours This Month</p>
                <small class="text-muted fs-6">
                    {% if month_hours > 0 %}Consistent work{% else %}New month{% endif %}
                </small>
            </div>
        </div>
    </div>
</div>

<!-- Enhanced Quick Actions -->
<div class="row section-spacing">
    <div class="col-12">
        <div class="card mobile-card hover-lift">
            <div class="card-header">
                <h5 class="mb-0 d-flex align-items-center">
                    <i class="fas fa-bolt me-3 text-warning"></i>Quick Actions
                </h5>
            </div>
            <div class="card-body">
                <div class="row g-4">
                    <div class="col-lg-3 col-md-6 col-sm-6">
                        <a href="{{ url_for('timer.manual_entry') }}" class="card h-100 text-decoration-none mobile-card hover-lift">
                            <div class="card-body text-center py-4">
                                <div class="bg-primary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center mx-auto mb-3" style="width: 56px; height: 56px;">
                                    <i class="fas fa-plus text-primary fa-lg"></i>
                                </div>
                                <h6 class="fw-semibold mb-2 fs-5">Log Time</h6>
                                <small class="text-muted fs-6">Manual entry</small>
                            </div>
                        </a>
                    </div>
                    <div class="col-lg-3 col-md-6 col-sm-6">
                        <a href="{{ url_for('projects.list_projects') }}" class="card h-100 text-decoration-none mobile-card hover-lift">
                            <div class="card-body text-center py-4">
                                <div class="bg-secondary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center mx-auto mb-3" style="width: 56px; height: 56px;">
                                    <i class="fas fa-project-diagram text-secondary fa-lg"></i>
                                </div>
                                <h6 class="fw-semibold mb-2 fs-5">Projects</h6>
                                <small class="text-muted fs-6">Manage projects</small>
                            </div>
                        </a>
                    </div>
                    <div class="col-lg-3 col-md-6 col-sm-6">
                        <a href="{{ url_for('reports.reports') }}" class="card h-100 text-decoration-none mobile-card hover-lift">
                            <div class="card-body text-center py-4">
                                <div class="bg-info bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center mx-auto mb-3" style="width: 56px; height: 56px;">
                                    <i class="fas fa-chart-bar text-info fa-lg"></i>
                                </div>
                                <h6 class="fw-semibold mb-2 fs-5">Reports</h6>
                                <small class="text-muted fs-6">View analytics</small>
                            </div>
                        </a>
                    </div>
                    <div class="col-lg-3 col-md-6 col-sm-6">
                        <a href="{{ url_for('main.search') }}" class="card h-100 text-decoration-none mobile-card hover-lift">
                            <div class="card-body text-center py-4">
                                <div class="bg-warning bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center mx-auto mb-3" style="width: 56px; height: 56px;">
                                    <i class="fas fa-search text-warning fa-lg"></i>
                                </div>
                                <h6 class="fw-semibold mb-2 fs-5">Search</h6>
                                <small class="text-muted fs-6">Find entries</small>
                            </div>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Enhanced Recent Entries -->
<div class="row">
    <div class="col-12">
        <div class="card mobile-card hover-lift">
            <div class="card-header d-flex justify-content-between align-items-center flex-column flex-md-row">
                <h5 class="mb-0 mb-3 mb-md-0 d-flex align-items-center">
                    <i class="fas fa-history me-3 text-primary"></i>Recent Entries
                </h5>
                <a href="{{ url_for('reports.reports') }}" class="btn btn-sm btn-outline-primary touch-target">
                    <i class="fas fa-external-link-alt me-2"></i>View All
                </a>
            </div>
            <div class="card-body p-0">
                {% if recent_entries %}
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr>
                                <th class="ps-4">Project</th>
                                <th>Duration</th>
                                <th>Date</th>
                                <th>Notes</th>
                                <th class="text-end pe-4">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for entry in recent_entries %}
                            <tr class="hover-lift">
                                <td class="ps-4" data-label="Project">
                                    <div class="d-flex align-items-center">
                                        <div class="me-3">
                                            <div class="bg-primary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                <i class="fas fa-project-diagram text-primary"></i>
                                            </div>
                                        </div>
                                        <div>
                                            <strong class="d-block fs-6">{{ entry.project.name }}</strong>
                                            <small class="text-muted fs-6">{{ entry.project.client }}</small>
                                        </div>
                                    </div>
                                </td>
                                <td data-label="Duration">
                                    <span class="badge bg-primary fs-6">{{ entry.duration_formatted }}</span>
                                </td>
                                <td data-label="Date">
                                    <div class="d-flex flex-column">
                                        <span class="fw-semibold fs-6">{{ entry.start_time.strftime('%b %d') }}</span>
                                        <small class="text-muted fs-6">{{ entry.start_time.strftime('%H:%M') }}</small>
                                    </div>
                                </td>
                                <td data-label="Notes">
                                    {% if entry.notes %}
                                    <div class="text-truncate" style="max-width: 200px;" title="{{ entry.notes }}">
                                        {{ entry.notes[:50] }}{% if entry.notes|length > 50 %}...{% endif %}
                                    </div>
                                    {% else %}
                                    <span class="text-muted fst-italic fs-6">No notes</span>
                                    {% endif %}
                                </td>
                                <td class="text-end pe-4 actions-cell" data-label="Actions">
                                    <div class="btn-group" role="group">
                                        <a href="{{ url_for('timer.edit_timer', timer_id=entry.id) }}" 
                                           class="btn btn-sm btn-action btn-action--edit touch-target" title="Edit entry">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        {% if current_user.is_admin or entry.user_id == current_user.id %}
                                        <button type="button" class="btn btn-sm btn-action btn-action--danger touch-target" title="Delete entry" 
                                                onclick="showDeleteEntryModal('{{ entry.id }}', '{{ entry.project.name }}', '{{ entry.duration_formatted }}')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                        {% endif %}
                                    </div>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                {% else %}
                <div class="text-center py-5">
                    <div class="mb-4">
                        <i class="fas fa-clock fa-3x text-muted opacity-50"></i>
                    </div>
                    <h5 class="text-muted mb-3">No recent entries</h5>
                    <p class="text-muted mb-4 fs-6">Start tracking your time to see entries here</p>
                    <a href="{{ url_for('timer.manual_entry') }}" class="btn btn-primary touch-target fw-bold">
                        <i class="fas fa-plus me-2"></i>Log Your First Entry
                    </a>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- Enhanced Start Timer Modal -->
<div class="modal fade" id="startTimerModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title d-flex align-items-center">
                    <i class="fas fa-play me-3 text-success"></i>Start Timer
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="{{ url_for('timer.start_timer') }}">
                <div class="modal-body">
                    <div class="mb-4">
                        <label for="project_id" class="form-label fw-semibold d-flex align-items-center">
                            <i class="fas fa-project-diagram me-2"></i>Select Project
                        </label>
                        <select class="form-select form-select-lg" id="project_id" name="project_id" required>
                            <option value="">Choose a project...</option>
                            {% for project in active_projects %}
                            <option value="{{ project.id }}">
                                {{ project.name }} ({{ project.client }})
                            </option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="mb-4">
                        <label for="task_id" class="form-label fw-semibold d-flex align-items-center">
                            <i class="fas fa-tasks me-2"></i>Select Task (Optional)
                        </label>
                        <select class="form-select" id="task_id" name="task_id" disabled>
                            <option value="">Choose a task...</option>
                        </select>
                        <small class="text-muted">Tasks list updates after choosing a project. Leave empty to log at project level.</small>
                    </div>
                    <div class="mb-3">
                        <label for="timer_notes" class="form-label fw-semibold d-flex align-items-center">
                            <i class="fas fa-sticky-note me-2"></i>Notes (Optional)
                        </label>
                        <textarea class="form-control" id="timer_notes" name="notes" rows="3" 
                                  placeholder="What are you working on?"></textarea>
                    </div>
                </div>
                <div class="modal-footer d-flex flex-column flex-md-row">
                    <button type="button" class="btn btn-secondary mb-2 mb-md-0 me-md-2" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i>Cancel
                    </button>
                    <button type="submit" class="btn btn-success fw-bold">
                        <i class="fas fa-play me-2"></i>Start Timer
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Enhanced Delete Time Entry Modal -->
<div class="modal fade" id="deleteEntryModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title d-flex align-items-center">
                    <i class="fas fa-trash me-3 text-danger"></i>Delete Time Entry
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Warning:</strong> This action cannot be undone.
                </div>
                <p class="mb-2">Are you sure you want to delete the time entry for <strong id="deleteEntryProjectName"></strong>?</p>
                <p class="text-muted mb-0 fs-6">Duration: <strong id="deleteEntryDuration"></strong></p>
            </div>
            <div class="modal-footer d-flex flex-column flex-md-row">
                <button type="button" class="btn btn-secondary mb-2 mb-md-0 me-md-2" data-bs-dismiss="modal">
                    <i class="fas fa-times me-2"></i>Cancel
                </button>
                <form method="POST" id="deleteEntryForm" class="d-inline">
                    <button type="submit" class="btn btn-danger fw-bold">
                        <i class="fas fa-trash me-2"></i>Delete Entry
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let timerInterval;
    const HAS_ACTIVE_TIMER = !!Number(document.getElementById('dashboard-meta')?.getAttribute('data-has-active-timer') || '0');
    if (HAS_ACTIVE_TIMER) {
        // Enhanced timer update
        function updateTimer() {
            fetch('/api/timer/status')
                .then(response => response.json())
                .then(data => {
                    if (data.active && data.timer) {
                        const display = document.getElementById('timer-display');
                        if (display) {
                            // Prefer server-provided current duration; fallback to computing from start_time
                            let totalSeconds = typeof data.timer.current_duration === 'number'
                                ? data.timer.current_duration
                                : Math.floor((new Date() - new Date(data.timer.start_time)) / 1000);
                            if (totalSeconds < 0 || Number.isNaN(totalSeconds)) totalSeconds = 0;
                            const hours = Math.floor(totalSeconds / 3600);
                            const minutes = Math.floor((totalSeconds % 3600) / 60);
                            const seconds = totalSeconds % 60;
                            display.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
                        }
                    } else {
                        // Timer stopped, reload page
                        clearInterval(timerInterval);
                        location.reload();
                    }
                })
                .catch(error => {
                    console.error('Error updating timer:', error);
                });
        }
        
        // Update timer immediately and then every second
        updateTimer();
        timerInterval = setInterval(updateTimer, 1000);
        
        // Clean up on page unload
        window.addEventListener('beforeunload', () => {
            if (timerInterval) {
                clearInterval(timerInterval);
            }
        });
    }
    
    // Populate tasks when project changes
    const projectSelect = document.getElementById('project_id');
    const taskSelect = document.getElementById('task_id');
    if (projectSelect && taskSelect) {
        projectSelect.addEventListener('change', async function() {
            const pid = this.value;
            taskSelect.innerHTML = '<option value="">Choose a task...</option>';
            taskSelect.disabled = true;
            if (!pid) return;
            try {
                const resp = await fetch(`/api/tasks?project_id=${encodeURIComponent(pid)}`);
                const data = await resp.json();
                if (Array.isArray(data.tasks)) {
                    for (const t of data.tasks) {
                        const opt = document.createElement('option');
                        opt.value = t.id;
                        opt.textContent = t.name;
                        taskSelect.appendChild(opt);
                    }
                    taskSelect.disabled = data.tasks.length === 0;
                }
            } catch (e) {
                console.warn('Failed to load tasks', e);
            }
        });
    }

    // Validate start timer submission
    const startForm = document.querySelector('#startTimerModal form');
    if (startForm) {
        startForm.addEventListener('submit', function(e) {
            const pid = projectSelect.value;
            if (!pid) {
                e.preventDefault();
                showToast('Please select a project', 'warning');
                return false;
            }
            const btn = this.querySelector('button[type="submit"]');
            if (btn) {
                btn.innerHTML = '<div class="loading-spinner me-2"></div>Starting...';
                btn.disabled = true;
            }
        });
    }
    
    // Enhanced function to show delete time entry modal
    function showDeleteEntryModal(entryId, projectName, duration) {
        document.getElementById('deleteEntryProjectName').textContent = projectName;
        document.getElementById('deleteEntryDuration').textContent = duration;
        document.getElementById('deleteEntryForm').action = "{{ url_for('timer.delete_timer', timer_id=0) }}".replace('0', entryId);
        new bootstrap.Modal(document.getElementById('deleteEntryModal')).show();
    }
    
    // Enhanced loading state to delete entry form
    document.addEventListener('DOMContentLoaded', function() {
        const deleteForm = document.getElementById('deleteEntryForm');
        if (deleteForm) {
            deleteForm.addEventListener('submit', function(e) {
                const submitBtn = this.querySelector('button[type="submit"]');
                submitBtn.innerHTML = '<div class="loading-spinner me-2"></div>Deleting...';
                submitBtn.disabled = true;
            });
        }
    });
</script>
{% endblock %}
