{% extends "base.html" %}

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

{% block content %}
<div class="container-fluid">
    {% from "_components.html" import page_header %}
    <div class="row">
        <div class="col-12">
            {% set actions %}
            <select id="timeRange" class="form-select form-select-sm" style="width: auto;">
                <option value="7">Last 7 days</option>
                <option value="30" selected>Last 30 days</option>
                <option value="90">Last 90 days</option>
                <option value="365">Last year</option>
            </select>
            <button id="refreshCharts" class="btn btn-outline-light btn-sm">
                <i class="fas fa-sync-alt"></i> Refresh
            </button>
            {% endset %}
            {{ page_header('fas fa-chart-line', 'Analytics Dashboard', 'Key metrics and insights', actions) }}
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="card text-center h-100">
                <div class="card-body">
                    <i class="fas fa-clock fa-2x text-primary mb-2"></i>
                    <h4 class="text-primary" id="totalHours">-</h4>
                    <p class="text-muted mb-0">Total Hours</p>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="card text-center h-100">
                <div class="card-body">
                    <i class="fas fa-dollar-sign fa-2x text-success mb-2"></i>
                    <h4 class="text-success" id="billableHours">-</h4>
                    <p class="text-muted mb-0">Billable Hours</p>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="card text-center h-100">
                <div class="card-body">
                    <i class="fas fa-project-diagram fa-2x text-info mb-2"></i>
                    <h4 class="text-info" id="activeProjects">-</h4>
                    <p class="text-muted mb-0">Active Projects</p>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="card text-center h-100">
                <div class="card-body">
                    <i class="fas fa-chart-line fa-2x text-warning mb-2"></i>
                    <h4 class="text-warning" id="avgDailyHours">-</h4>
                    <p class="text-muted mb-0">Avg Daily Hours</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row 1 -->
    <div class="row mb-4">
        <div class="col-lg-8 mb-4">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-chart-area"></i> Daily Hours Trend
                    </h5>
                </div>
                <div class="card-body">
                    <div class="chart-container" style="position: relative; height: 300px;">
                        <canvas id="dailyHoursChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-4 mb-4">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-chart-pie"></i> Billable vs Non-Billable
                    </h5>
                </div>
                <div class="card-body">
                    <div class="chart-container" style="position: relative; height: 300px;">
                        <canvas id="billableChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row 2 -->
    <div class="row mb-4">
        <div class="col-lg-6 mb-4">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-chart-bar"></i> Hours by Project
                    </h5>
                </div>
                <div class="card-body">
                    <div class="chart-container" style="position: relative; height: 300px;">
                        <canvas id="projectChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-6 mb-4">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-chart-line"></i> Weekly Trends
                    </h5>
                </div>
                <div class="card-body">
                    <div class="chart-container" style="position: relative; height: 300px;">
                        <canvas id="weeklyTrendsChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row 3 -->
    <div class="row mb-4">
        <div class="col-lg-6 mb-4">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-clock"></i> Hours by Time of Day
                    </h5>
                </div>
                <div class="card-body">
                    <div class="chart-container" style="position: relative; height: 300px;">
                        <canvas id="hourlyChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-6 mb-4">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-chart-bar"></i> Project Efficiency
                    </h5>
                </div>
                <div class="card-body">
                    <div class="chart-container" style="position: relative; height: 300px;">
                        <canvas id="efficiencyChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- User Performance Chart (Admin Only) -->
    {% if current_user.is_admin %}
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-users"></i> User Performance
                    </h5>
                </div>
                <div class="card-body">
                    <div class="chart-container" style="position: relative; height: 300px;">
                        <canvas id="userChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
</div>

<!-- Loading Spinner -->
<div id="loadingSpinner" class="position-fixed top-50 start-50 translate-middle" style="display: none; z-index: 9999;">
    <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">Loading...</span>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// Global chart instances
let charts = {};

// Chart.js global defaults
Chart.defaults.font.family = "'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif";
Chart.defaults.font.size = 12;
Chart.defaults.color = '#64748b';
Chart.defaults.plugins.legend.position = 'bottom';
Chart.defaults.plugins.legend.labels.usePointStyle = true;
Chart.defaults.plugins.legend.labels.padding = 20;

// Analytics Dashboard Controller
class AnalyticsDashboard {
    constructor() {
        this.timeRange = 30;
        this.charts = {};
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadCharts();
        this.updateSummaryCards();
    }

    bindEvents() {
        document.getElementById('timeRange').addEventListener('change', (e) => {
            this.timeRange = parseInt(e.target.value);
            this.refreshAllCharts();
        });

        document.getElementById('refreshCharts').addEventListener('click', () => {
            this.refreshAllCharts();
        });
    }

    showLoading() {
        document.getElementById('loadingSpinner').style.display = 'block';
    }

    hideLoading() {
        document.getElementById('loadingSpinner').style.display = 'none';
    }

    async loadCharts() {
        this.showLoading();
        
        try {
            await Promise.all([
                this.loadDailyHoursChart(),
                this.loadBillableChart(),
                this.loadProjectChart(),
                this.loadWeeklyTrendsChart(),
                this.loadHourlyChart(),
                this.loadEfficiencyChart(),
                {% if current_user.is_admin %}
                this.loadUserChart(),
                {% endif %}
            ]);
        } catch (error) {
            console.error('Error loading charts:', error);
            this.showError('Failed to load charts. Please try again.');
        } finally {
            this.hideLoading();
        }
    }

    async refreshAllCharts() {
        this.showLoading();
        
        try {
            await Promise.all([
                this.loadDailyHoursChart(true),
                this.loadBillableChart(true),
                this.loadProjectChart(true),
                this.loadWeeklyTrendsChart(true),
                this.loadHourlyChart(true),
                this.loadEfficiencyChart(true),
                {% if current_user.is_admin %}
                this.loadUserChart(true),
                {% endif %}
            ]);
            this.updateSummaryCards();
        } catch (error) {
            console.error('Error refreshing charts:', error);
            this.showError('Failed to refresh charts. Please try again.');
        } finally {
            this.hideLoading();
        }
    }

    async loadDailyHoursChart(refresh = false) {
        const response = await fetch(`/api/analytics/hours-by-day?days=${this.timeRange}`);
        const data = await response.json();
        
        if (refresh && this.charts.dailyHours) {
            this.charts.dailyHours.destroy();
        }
        
        const ctx = document.getElementById('dailyHoursChart').getContext('2d');
        this.charts.dailyHours = new Chart(ctx, {
            type: 'line',
            data: data,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Hours'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: 'Date'
                        }
                    }
                },
                interaction: {
                    intersect: false,
                    mode: 'index'
                }
            }
        });
    }

    async loadBillableChart(refresh = false) {
        const response = await fetch(`/api/analytics/billable-vs-nonbillable?days=${this.timeRange}`);
        const data = await response.json();
        
        if (refresh && this.charts.billable) {
            this.charts.billable.destroy();
        }
        
        const ctx = document.getElementById('billableChart').getContext('2d');
        this.charts.billable = new Chart(ctx, {
            type: 'doughnut',
            data: data,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    }

    async loadProjectChart(refresh = false) {
        const response = await fetch(`/api/analytics/hours-by-project?days=${this.timeRange}`);
        const data = await response.json();
        
        if (refresh && this.charts.project) {
            this.charts.project.destroy();
        }
        
        const ctx = document.getElementById('projectChart').getContext('2d');
        this.charts.project = new Chart(ctx, {
            type: 'bar',
            data: data,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Hours'
                        }
                    }
                }
            }
        });
    }

    async loadWeeklyTrendsChart(refresh = false) {
        const response = await fetch(`/api/analytics/weekly-trends?weeks=${Math.min(12, Math.ceil(this.timeRange / 7))}`);
        const data = await response.json();
        
        if (refresh && this.charts.weeklyTrends) {
            this.charts.weeklyTrends.destroy();
        }
        
        const ctx = document.getElementById('weeklyTrendsChart').getContext('2d');
        this.charts.weeklyTrends = new Chart(ctx, {
            type: 'line',
            data: data,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Hours'
                        }
                    }
                }
            }
        });
    }

    async loadHourlyChart(refresh = false) {
        const response = await fetch(`/api/analytics/hours-by-hour?days=${this.timeRange}`);
        const data = await response.json();
        
        if (refresh && this.charts.hourly) {
            this.charts.hourly.destroy();
        }
        
        const ctx = document.getElementById('hourlyChart').getContext('2d');
        this.charts.hourly = new Chart(ctx, {
            type: 'line',
            data: data,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Hours'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: 'Hour of Day'
                        }
                    }
                }
            }
        });
    }

    async loadEfficiencyChart(refresh = false) {
        const response = await fetch(`/api/analytics/project-efficiency?days=${this.timeRange}`);
        const data = await response.json();
        
        if (refresh && this.charts.efficiency) {
            this.charts.efficiency.destroy();
        }
        
        const ctx = document.getElementById('efficiencyChart').getContext('2d');
        this.charts.efficiency = new Chart(ctx, {
            type: 'bar',
            data: data,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                },
                scales: {
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        title: {
                            display: true,
                            text: 'Hours'
                        }
                    },
                    y1: {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        title: {
                            display: true,
                            text: 'Revenue'
                        },
                        grid: {
                            drawOnChartArea: false,
                        },
                    }
                }
            }
        });
    }

    {% if current_user.is_admin %}
    async loadUserChart(refresh = false) {
        const response = await fetch(`/api/analytics/hours-by-user?days=${this.timeRange}`);
        const data = await response.json();
        
        if (refresh && this.charts.user) {
            this.charts.user.destroy();
        }
        
        const ctx = document.getElementById('userChart').getContext('2d');
        this.charts.user = new Chart(ctx, {
            type: 'bar',
            data: data,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Hours'
                        }
                    }
                }
            }
        });
    }
    {% endif %}

    async updateSummaryCards() {
        try {
            // Get summary data from daily hours chart
            const response = await fetch(`/api/analytics/hours-by-day?days=${this.timeRange}`);
            const data = await response.json();
            
            const totalHours = data.datasets[0].data.reduce((sum, hours) => sum + hours, 0);
            const avgDailyHours = totalHours / data.datasets[0].data.length;
            
            document.getElementById('totalHours').textContent = totalHours.toFixed(1) + 'h';
            document.getElementById('avgDailyHours').textContent = avgDailyHours.toFixed(1) + 'h';
            
            // Get billable data
            const billableResponse = await fetch(`/api/analytics/billable-vs-nonbillable?days=${this.timeRange}`);
            const billableData = await billableResponse.json();
            const billableHours = billableData.datasets[0].data[0];
            document.getElementById('billableHours').textContent = billableHours.toFixed(1) + 'h';
            
            // Get project count
            const projectResponse = await fetch(`/api/analytics/hours-by-project?days=${this.timeRange}`);
            const projectData = await projectResponse.json();
            document.getElementById('activeProjects').textContent = projectData.labels.length;
            
        } catch (error) {
            console.error('Error updating summary cards:', error);
        }
    }

    showError(message) {
        // Create a simple error notification
        const errorDiv = document.createElement('div');
        errorDiv.className = 'alert alert-danger alert-dismissible fade show position-fixed';
        errorDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
        errorDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        document.body.appendChild(errorDiv);
        
        // Auto-remove after 5 seconds
        setTimeout(() => {
            if (errorDiv.parentNode) {
                errorDiv.parentNode.removeChild(errorDiv);
            }
        }, 5000);
    }
}

// Initialize dashboard when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    new AnalyticsDashboard();
});
</script>
{% endblock %}
