{% extends 'base.html' %}
{% load static %}

{% block title %}Date Filter Charts Demo{% endblock %}

{% block extra_css %}
<link href="{% static 'css/date-filter-charts.css' %}" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet">
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- Page Header -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Real-time Date Filtering Demo</h1>
        <div class="btn-group" role="group">
            <button type="button" class="btn btn-primary btn-sm" onclick="window.print()">
                <span>🖨️</span> Print
            </button>
            <button type="button" class="btn btn-success btn-sm" onclick="exportToPDF()">
                <span>📄</span> Export PDF
            </button>
        </div>
    </div>

    <!-- Error Container -->
    <div id="error-container"></div>

    <!-- Date Filter Widget -->
    <div id="date-filter-container"></div>
    
    <!-- Help Section -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="alert alert-info alert-dismissible fade show" role="alert">
                <h6><i class="fas fa-keyboard"></i> Keyboard Shortcuts</h6>
                <div class="row">
                    <div class="col-md-6">
                        <small>
                            <strong>Ctrl+Enter:</strong> Apply filters<br>
                            <strong>Ctrl+R:</strong> Reset filters<br>
                            <strong>Alt+1-5:</strong> Quick date ranges
                        </small>
                    </div>
                    <div class="col-md-6">
                        <small>
                            <strong>Ctrl+P:</strong> Print report<br>
                            <strong>Ctrl+E:</strong> Export to PDF<br>
                            <strong>F5:</strong> Refresh charts
                        </small>
                    </div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        </div>
    </div>

    <!-- Loading Overlay -->
    <div id="loading-overlay">
        <div class="spinner">
            <span>⟳</span>
            <div class="mt-2">Updating charts...</div>
        </div>
    </div>

    <!-- Summary Cards Row -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card">
                <div class="card-body">
                    <div class="card-title">Total Loans Due</div>
                    <div class="card-text" id="summary-total_loans">0</div>
                    <div class="comparison-data" style="display: none;">
                        <div class="comparison-title">Previous Period</div>
                        <div class="comparison-value" id="comparison-total_loans">0</div>
                        <span class="comparison-change" id="change-total_loans">0%</span>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card success">
                <div class="card-body">
                    <div class="card-title">Total Amount Due</div>
                    <div class="card-text" id="summary-total_amount">KES 0</div>
                    <div class="comparison-data" style="display: none;">
                        <div class="comparison-title">Previous Period</div>
                        <div class="comparison-value" id="comparison-total_amount">KES 0</div>
                        <span class="comparison-change" id="change-total_amount">0%</span>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card warning">
                <div class="card-body">
                    <div class="card-title">Delinquent Loans</div>
                    <div class="card-text" id="summary-delinquent_count">0</div>
                    <div class="comparison-data" style="display: none;">
                        <div class="comparison-title">Previous Period</div>
                        <div class="comparison-value" id="comparison-delinquent_count">0</div>
                        <span class="comparison-change" id="change-delinquent_count">0%</span>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card info">
                <div class="card-body">
                    <div class="card-title">Collection Rate</div>
                    <div class="card-text" id="summary-collection_rate">0%</div>
                    <div class="comparison-data" style="display: none;">
                        <div class="comparison-title">Previous Period</div>
                        <div class="comparison-value" id="comparison-collection_rate">0%</div>
                        <span class="comparison-change" id="change-collection_rate">0%</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row -->
    <div class="row">
        <!-- Due Amounts Chart -->
        <div class="col-xl-6 col-lg-6">
            <div class="chart-container">
                <div class="chart-title">Loan Amounts Due by Urgency</div>
                <div id="due_amounts_urgency" class="chartjs-chart">
                    <div class="chart-loading">
                        <span>⟳</span>
                        Loading chart...
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Count Distribution Chart -->
        <div class="col-xl-6 col-lg-6">
            <div class="chart-container">
                <div class="chart-title">Distribution of Loans Due by Count</div>
                <div id="due_count_distribution" class="chartjs-chart">
                    <div class="chart-loading">
                        <span>⟳</span>
                        Loading chart...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Second Charts Row -->
    <div class="row">
        <!-- Aging Analysis Chart -->
        <div class="col-xl-6 col-lg-6">
            <div class="chart-container">
                <div class="chart-title">Delinquent Loans Aging Analysis</div>
                <div id="aging_analysis" class="chartjs-chart">
                    <div class="chart-loading">
                        <span>⟳</span>
                        Loading chart...
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Portfolio Overview Chart -->
        <div class="col-xl-6 col-lg-6">
            <div class="chart-container">
                <div class="chart-title">Portfolio Overview</div>
                <div id="portfolio_overview" class="chartjs-chart">
                    <div class="chart-loading">
                        <span>⟳</span>
                        Loading chart...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Trend Analysis Row -->
    <div class="row">
        <div class="col-12">
            <div class="chart-container">
                <div class="chart-title">Revenue Trend Analysis</div>
                <div id="revenue_trend" class="chartjs-chart">
                    <div class="chart-loading">
                        <span>⟳</span>
                        Loading chart...
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>

<!-- Flatpickr for better date picking -->
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<!-- Date Filter Charts -->
<script src="{% static 'js/date-filter-charts.js' %}"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize date filter charts with specific configuration
    window.dateFilterCharts = new DateFilterCharts({
        apiEndpoint: '{% url "reports:filtered_data_api" %}',
        chartContainers: {
            'due_amounts_urgency': {
                type: 'chartjs',
                chartType: 'bar'
            },
            'due_count_distribution': {
                type: 'chartjs',
                chartType: 'doughnut'
            },
            'aging_analysis': {
                type: 'chartjs',
                chartType: 'bar'
            },
            'portfolio_overview': {
                type: 'chartjs',
                chartType: 'doughnut'
            },
            'revenue_trend': {
                type: 'chartjs',
                chartType: 'line'
            }
        }
    });
    
    // Load initial data
    setTimeout(() => {
        window.dateFilterCharts.applyFilter();
    }, 500);
});

// Export to PDF function
function exportToPDF() {
    const dateRange = window.dateFilterCharts.getDateRange();
    const params = new URLSearchParams({
        start_date: dateRange.start.toISOString().split('T')[0],
        end_date: dateRange.end.toISOString().split('T')[0],
        format: 'pdf',
        include_charts: 'true'
    });
    
    window.open(`{% url "reports:export_report" "dashboard" %}?${params}`, '_blank');
}

// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Ctrl+R or F5 to refresh charts
    if ((e.ctrlKey && e.key === 'r') || e.key === 'F5') {
        e.preventDefault();
        window.dateFilterCharts.refreshCharts();
    }
    
    // Ctrl+P to print
    if (e.ctrlKey && e.key === 'p') {
        e.preventDefault();
        window.print();
    }
    
    // Ctrl+E to export
    if (e.ctrlKey && e.key === 'e') {
        e.preventDefault();
        exportToPDF();
    }
});

// Auto-refresh every 5 minutes
setInterval(() => {
    if (document.visibilityState === 'visible') {
        window.dateFilterCharts.refreshCharts();
    }
}, 5 * 60 * 1000);
</script>
{% endblock %}