<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reports Dashboard</title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.min.js"></script>

    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .dashboard-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
        }

        .metric-card {
            background: white;
            border-radius: 15px;
            padding: 2rem;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            margin-bottom: 1.5rem;
            transition: transform 0.3s ease;
        }

        .metric-card:hover {
            transform: translateY(-5px);
        }

        .metric-value {
            font-size: 2.5rem;
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 0.5rem;
        }

        .metric-label {
            color: #6c757d;
            font-size: 1rem;
            font-weight: 500;
        }

        .chart-card {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            margin-bottom: 2rem;
        }

        .chart-container {
            position: relative;
            height: 400px;
            margin-top: 1rem;
        }

        .chart-loading {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 400px;
            color: #6c757d;
            font-size: 1.2rem;
        }

        .btn-custom {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 500;
            margin: 0.25rem;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }

        .btn-custom:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(16, 185, 129, 0.4);
            color: white;
            text-decoration: none;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .stat-item {
            background: white;
            padding: 1.5rem;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .stat-value {
            font-size: 1.8rem;
            font-weight: bold;
            margin-bottom: 0.5rem;
        }

        .text-primary {
            color: #3b82f6 !important;
        }

        .text-success {
            color: #10b981 !important;
        }

        .text-warning {
            color: #f59e0b !important;
        }

        .text-danger {
            color: #ef4444 !important;
        }

        .spinner {
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            from {
                transform: rotate(0deg);
            }

            to {
                transform: rotate(360deg);
            }
        }
    </style>
</head>

<body>
    <!-- Dashboard Header -->
    <div class="dashboard-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1 class="mb-2">Reports & Analytics Dashboard</h1>
                    <p class="mb-0 opacity-75">Comprehensive loan management reporting and analytics</p>
                </div>
                <div class="col-md-4 text-end">
                    <button class="btn btn-light" onclick="refreshDashboard()">
                        <span>🔄</span> Refresh Data
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- Key Metrics -->
        <div class="row">
            <div class="col-md-3">
                <div class="metric-card">
                    <div class="metric-value text-primary">{{
                        dashboard_data.summary_metrics.total_active_loans|default:0 }}</div>
                    <div class="metric-label">Active Loans</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="metric-card">
                    <div class="metric-value text-success">KSh {{
                        dashboard_data.summary_metrics.total_portfolio_value|floatformat:0|default:0 }}</div>
                    <div class="metric-label">Portfolio Value</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="metric-card">
                    <div class="metric-value text-warning">KSh {{
                        dashboard_data.summary_metrics.total_outstanding|floatformat:0|default:0 }}</div>
                    <div class="metric-label">Outstanding Balance</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="metric-card">
                    <div class="metric-value text-danger">{{
                        dashboard_data.summary_metrics.collection_rate|floatformat:1|default:0 }}%</div>
                    <div class="metric-label">Collection Rate</div>
                </div>
            </div>
        </div>

        <!-- Charts Section -->
        <div class="row">
            <!-- Loan Performance Chart -->
            <div class="col-md-8">
                <div class="chart-card">
                    <h5 class="mb-0">Loan Performance</h5>
                    <small class="text-muted">Monthly disbursements vs collections - Auto-loading</small>

                    <div id="loanPerformanceLoading" class="chart-loading">
                        <span>⟳</span> Loading chart data automatically...
                    </div>

                    <div class="chart-container" id="loanPerformanceContainer" style="display: none;">
                        <canvas id="loanPerformanceChart"></canvas>
                    </div>
                </div>
            </div>

            <!-- Portfolio Distribution -->
            <div class="col-md-4">
                <div class="chart-card">
                    <h5 class="mb-0">Portfolio Distribution</h5>
                    <small class="text-muted">By loan product type</small>

                    <div id="portfolioLoading" class="chart-loading">
                        <span>⟳</span> Loading...
                    </div>

                    <div class="chart-container" id="portfolioContainer" style="display: none;">
                        <canvas id="portfolioChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- Revenue and Stats -->
        <div class="row">
            <!-- Revenue Breakdown -->
            <div class="col-md-6">
                <div class="chart-card">
                    <h5 class="mb-0">Revenue Breakdown</h5>
                    <small class="text-muted">Current month revenue sources</small>

                    <div id="revenueLoading" class="chart-loading">
                        <span>⟳</span> Loading...
                    </div>

                    <div class="chart-container" id="revenueContainer" style="display: none;">
                        <canvas id="revenueChart"></canvas>
                    </div>
                </div>
            </div>

            <!-- Quick Stats -->
            <div class="col-md-6">
                <div class="chart-card">
                    <h5 class="mb-3">Quick Statistics</h5>

                    <div class="stats-grid">
                        <div class="stat-item">
                            <div class="stat-value text-warning">{{
                                dashboard_data.summary_metrics.loans_due_today|default:0 }}</div>
                            <div class="text-muted">Due Today</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-value text-danger">{{
                                dashboard_data.summary_metrics.overdue_loans|default:0 }}</div>
                            <div class="text-muted">Overdue</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-value text-success">KSh {{
                                dashboard_data.processing_fees_current_month.summary.total_processing_fees|floatformat:0|default:0
                                }}</div>
                            <div class="text-muted">Processing Fees</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-value text-primary">KSh {{
                                dashboard_data.interest_income_current_month.summary.total_interest_income|floatformat:0|default:0
                                }}</div>
                            <div class="text-muted">Interest Income</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="chart-card">
            <h5 class="mb-3">Quick Actions</h5>
            <div class="text-center">
                <a href="{% url 'reports:loans_due_report' %}" class="btn-custom">
                    <span>📅</span> Loans Due
                </a>
                <a href="{% url 'reports:delinquent_loans_report' %}" class="btn-custom">
                    <span>⚠️</span> Delinquent Loans
                </a>
                <a href="{% url 'reports:disbursed_loans_report' %}" class="btn-custom">
                    <span>📊</span> Disbursed Loans
                </a>
                <a href="{% url 'reports:processing_fees_report' %}" class="btn-custom">
                    <span>💵</span> Processing Fees
                </a>
                <a href="{% url 'reports:interest_income_report' %}" class="btn-custom">
                    <i class="fas fa-percentage"></i> Interest Income
                </a>
                <a href="{% url 'reports:registration_fees_report' %}" class="btn-custom">
                    <span>👤+</span> Registration Fees
                </a>
                <a href="{% url 'reports:loans_in_arrears_report' %}" class="btn-custom">
                    <span>⏰</span> Loans in Arrears
                </a>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        console.log('🚀 Clean Dashboard Loading - NO BUTTON CLICKS REQUIRED!');

        // Auto-load all charts when page loads
        document.addEventListener('DOMContentLoaded', function () {
            console.log('✅ Page loaded - starting automatic chart loading...');

            // Start loading charts immediately
            setTimeout(() => {
                loadChart('loan_performance', 'loanPerformanceChart', 'line', 'loanPerformanceLoading', 'loanPerformanceContainer');
                loadChart('portfolio_distribution', 'portfolioChart', 'doughnut', 'portfolioLoading', 'portfolioContainer');
                loadChart('revenue_breakdown', 'revenueChart', 'pie', 'revenueLoading', 'revenueContainer');
            }, 100);
        });

        function loadChart(chartType, canvasId, type, loadingId, containerId) {
            console.log(`📊 Auto-loading ${chartType} chart...`);

            const loadingElement = document.getElementById(loadingId);
            const containerElement = document.getElementById(containerId);

            fetch(`/reports/api/simple-chart-data/?chart_type=${chartType}`)
                .then(response => response.json())
                .then(data => {
                    console.log(`✅ ${chartType} data loaded:`, data);

                    if (data.success && data.data) {
                        // Hide loading, show chart
                        if (loadingElement) loadingElement.style.display = 'none';
                        if (containerElement) containerElement.style.display = 'block';

                        createChart(canvasId, type, data.data);
                        console.log(`🎯 ${chartType} chart created successfully!`);
                    } else {
                        throw new Error('No data received');
                    }
                })
                .catch(error => {
                    console.log(`⚠️ ${chartType} using fallback data:`, error);

                    // Hide loading, show chart with fallback data
                    if (loadingElement) loadingElement.style.display = 'none';
                    if (containerElement) containerElement.style.display = 'block';

                    const fallbackData = getFallbackData(chartType);
                    createChart(canvasId, type, fallbackData);
                    console.log(`✅ ${chartType} chart created with fallback data`);
                });
        }

        function createChart(canvasId, type, data) {
            const ctx = document.getElementById(canvasId);
            if (!ctx) {
                console.error(`❌ Canvas ${canvasId} not found`);
                return;
            }

            const config = {
                type: type,
                data: data,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 20,
                                usePointStyle: true
                            }
                        }
                    }
                }
            };

            if (type === 'line') {
                config.options.scales = {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Amount (KSh)'
                        }
                    }
                };
            }

            new Chart(ctx.getContext('2d'), config);
        }

        function getFallbackData(chartType) {
            if (chartType === 'loan_performance') {
                return {
                    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                    datasets: [{
                        label: 'Disbursements',
                        data: [100000, 120000, 110000, 130000, 125000, 140000],
                        borderColor: '#3b82f6',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4
                    }, {
                        label: 'Collections',
                        data: [95000, 115000, 105000, 125000, 120000, 135000],
                        borderColor: '#10b981',
                        backgroundColor: 'rgba(16, 185, 129, 0.1)',
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4
                    }]
                };
            } else if (chartType === 'portfolio_distribution') {
                return {
                    labels: ['Personal Loans', 'Business Loans', 'Emergency Loans'],
                    datasets: [{
                        data: [500000, 300000, 200000],
                        backgroundColor: ['#3b82f6', '#ef4444', '#10b981'],
                        borderWidth: 2,
                        borderColor: '#fff'
                    }]
                };
            } else if (chartType === 'revenue_breakdown') {
                return {
                    labels: ['Processing Fees', 'Interest Income', 'Registration Fees'],
                    datasets: [{
                        data: [50000, 75000, 25000],
                        backgroundColor: ['#3b82f6', '#10b981', '#f59e0b'],
                        borderWidth: 2,
                        borderColor: '#fff'
                    }]
                };
            }
        }

        function refreshDashboard() {
            console.log('🔄 Refreshing dashboard...');
            location.reload();
        }

        console.log('🎉 Dashboard ready - charts will load automatically!');
    </script>
</body>

</html>