<!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">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">

    <style>
        body {
            background-color: #f8f9fa;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }

        .header-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 3rem 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: 2rem;
            border: none;
        }

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

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

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

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

        .loading-spinner {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 400px;
            color: #6c757d;
        }

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

        .btn-action:hover {
            color: white;
            text-decoration: none;
            transform: translateY(-2px);
        }

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

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

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

        .text-danger {
            color: #ef4444 !important;
        }
    </style>
</head>

<body>
    <!-- Header -->
    <div class="header-section">
        <div class="container">
            <h1 class="display-4 mb-2">Reports Dashboard</h1>
            <p class="lead mb-0">Comprehensive loan management analytics</p>
        </div>
    </div>

    <div class="container">
        <!-- Metrics Row -->
        <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</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 Row -->
        <div class="row">
            <div class="col-md-8">
                <div class="chart-card">
                    <h5>Loan Performance</h5>
                    <p class="text-muted">Monthly disbursements vs collections</p>

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

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

            <div class="col-md-4">
                <div class="chart-card">
                    <h5>Portfolio Distribution</h5>
                    <p class="text-muted">By loan type</p>

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

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

        <!-- Revenue Chart -->
        <div class="row">
            <div class="col-md-6">
                <div class="chart-card">
                    <h5>Revenue Breakdown</h5>
                    <p class="text-muted">Current month</p>

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

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

            <div class="col-md-6">
                <div class="chart-card">
                    <h5>Quick Stats</h5>
                    <div class="row text-center">
                        <div class="col-6">
                            <h4 class="text-warning">{{ dashboard_data.summary_metrics.loans_due_today|default:0 }}</h4>
                            <p class="text-muted">Due Today</p>
                        </div>
                        <div class="col-6">
                            <h4 class="text-danger">{{ dashboard_data.summary_metrics.overdue_loans|default:0 }}</h4>
                            <p class="text-muted">Overdue</p>
                        </div>
                    </div>
                    <hr>
                    <div class="row text-center">
                        <div class="col-6">
                            <h5 class="text-success">KSh {{
                                dashboard_data.processing_fees_current_month.summary.total_processing_fees|floatformat:0|default:0
                                }}</h5>
                            <p class="text-muted">Processing Fees</p>
                        </div>
                        <div class="col-6">
                            <h5 class="text-primary">KSh {{
                                dashboard_data.interest_income_current_month.summary.total_interest_income|floatformat:0|default:0
                                }}</h5>
                            <p class="text-muted">Interest Income</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="chart-card">
            <h5 class="mb-3">Quick Actions</h5>
            <div class="text-center">
                <a href="/reports/loans-due/" class="btn-action">
                    <span>📅</span> Loans Due
                </a>
                <a href="/reports/delinquent-loans/" class="btn-action">
                    <span>⚠️</span> Delinquent Loans
                </a>
                <a href="/reports/processing-fees/" class="btn-action">
                    <span>💵</span> Processing Fees
                </a>
                <a href="/reports/interest-income/" class="btn-action">
                    <i class="fas fa-percentage"></i> Interest Income
                </a>
                <a href="/reports/registration-fees/" class="btn-action">
                    <span>👤+</span> Registration Fees
                </a>
                <a href="{% url 'reports:loans_in_arrears_report' %}" class="btn-action">
                    <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>
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.min.js"></script>

    <script>
        console.log('🚀 Minimal Dashboard Loading...');

        // Load charts when page is ready
        document.addEventListener('DOMContentLoaded', function () {
            console.log('✅ DOM loaded - starting chart loading...');

            // Load charts with delay to ensure everything is ready
            setTimeout(() => {
                loadChart('loan_performance', 'performanceChart', 'line', 'performanceLoading', 'performanceContainer');
                loadChart('portfolio_distribution', 'portfolioChart', 'doughnut', 'portfolioLoading', 'portfolioContainer');
                loadChart('revenue_breakdown', 'revenueChart', 'pie', 'revenueLoading', 'revenueContainer');
            }, 1000);
        });

        function loadChart(chartType, canvasId, type, loadingId, containerId) {
            console.log(`📊 Loading ${chartType}...`);

            const loadingEl = document.getElementById(loadingId);
            const containerEl = document.getElementById(containerId);

            // Try to fetch chart data
            fetch(`/reports/api/simple-chart-data/?chart_type=${chartType}`)
                .then(response => {
                    console.log(`Response status for ${chartType}:`, response.status);

                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}`);
                    }

                    return response.text(); // Get as text first to debug
                })
                .then(text => {
                    console.log(`Raw response for ${chartType}:`, text.substring(0, 200));

                    try {
                        const data = JSON.parse(text);

                        if (data.success && data.data) {
                            console.log(`✅ ${chartType} data loaded successfully`);

                            // Hide loading, show chart
                            if (loadingEl) loadingEl.style.display = 'none';
                            if (containerEl) containerEl.style.display = 'block';

                            createChart(canvasId, type, data.data);
                        } else {
                            throw new Error('No data in response');
                        }
                    } catch (parseError) {
                        console.error(`JSON parse error for ${chartType}:`, parseError);
                        throw parseError;
                    }
                })
                .catch(error => {
                    console.log(`⚠️ ${chartType} error, using fallback:`, error);

                    // Hide loading, show chart with fallback
                    if (loadingEl) loadingEl.style.display = 'none';
                    if (containerEl) containerEl.style.display = 'block';

                    const fallbackData = getFallbackData(chartType);
                    createChart(canvasId, type, fallbackData);
                });
        }

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

            const ctx = canvas.getContext('2d');

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

            if (type === 'line') {
                config.options.scales = {
                    y: {
                        beginAtZero: true
                    }
                };
            }

            new Chart(ctx, config);
            console.log(`✅ Chart ${canvasId} created`);
        }

        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']
                    }]
                };
            } else if (chartType === 'revenue_breakdown') {
                return {
                    labels: ['Processing Fees', 'Interest Income', 'Registration Fees'],
                    datasets: [{
                        data: [50000, 75000, 25000],
                        backgroundColor: ['#3b82f6', '#10b981', '#f59e0b']
                    }]
                };
            }
        }
    </script>
</body>

</html>