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

{% block title %}Reports Dashboard{% endblock %}

{% block extra_css %}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.min.js"></script>
<style>
    body {
        background-color: #f8f9fa;
        font-family: 'Inter', sans-serif;
    }

    .dashboard-container {
        padding: 20px;
    }

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

    .card-header {
        background: white;
        border-bottom: 1px solid #e9ecef;
        padding: 20px;
        border-radius: 12px 12px 0 0 !important;
    }

    .card-body {
        padding: 20px;
    }

    .metric-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        text-align: center;
        padding: 25px;
        border-radius: 12px;
        margin-bottom: 20px;
        transition: transform 0.2s ease;
        cursor: pointer;
    }

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

    .metric-value {
        font-size: 2.5rem;
        font-weight: bold;
        margin-bottom: 8px;
        color: white;
    }

    .metric-label {
        font-size: 1rem;
        opacity: 0.9;
        color: white;
    }

    .chart-container {
        position: relative;
        height: 400px;
        padding: 10px;
    }

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

    .btn-action {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: white !important;
        border: none;
        padding: 12px 24px;
        border-radius: 8px;
        margin: 8px;
        text-decoration: none;
        display: inline-block;
        font-weight: 500;
        transition: all 0.2s ease;
    }

    .btn-action:hover {
        background: linear-gradient(135deg, #059669 0%, #047857 100%);
        color: white !important;
        text-decoration: none;
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
    }

    .stats-card {
        background: white;
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
    }

    .stat-item {
        text-align: center;
        padding: 15px;
    }

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

    .stat-label {
        color: #6c757d;
        font-size: 0.9rem;
    }

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

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

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

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

    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
        color: #1f2937;
        font-weight: 600;
    }

    .page-header {
        background: white;
        padding: 20px;
        border-radius: 12px;
        margin-bottom: 20px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    }
</style>
{% endblock %}

{% block content %}
<div class="dashboard-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h2 class="mb-1">Reports & Analytics Dashboard</h2>
                <p class="text-muted mb-0">Comprehensive loan management reporting</p>
            </div>
            <div>
                <button class="btn btn-outline-primary" onclick="refreshDashboard()">
                    <span>🔄</span> Refresh
                </button>
            </div>
        </div>
    </div>

    <!-- Key Metrics -->
    <div class="row">
        <div class="col-md-3">
            <div class="metric-card">
                <div class="metric-value">{{ 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" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                <div class="metric-value">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" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                <div class="metric-value">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" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
                <div class="metric-value">{{ dashboard_data.summary_metrics.collection_rate|floatformat:1|default:0 }}%
                </div>
                <div class="metric-label">Collection Rate</div>
            </div>
        </div>
    </div>

    <!-- Charts -->
    <div class="row">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-1">Loan Performance</h5>
                    <small class="text-muted">Monthly disbursements vs collections</small>
                </div>
                <div class="card-body">
                    <div id="loanPerformanceLoading" class="chart-loading">
                        <span>⟳</span> Loading chart data...
                    </div>
                    <div class="chart-container" id="loanPerformanceContainer" style="display: none;">
                        <canvas id="loanPerformanceChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-1">Portfolio Distribution</h5>
                    <small class="text-muted">By loan product type</small>
                </div>
                <div class="card-body">
                    <div id="portfolioLoading" class="chart-loading">
                        <span>⟳</span> Loading chart data...
                    </div>
                    <div class="chart-container" id="portfolioContainer" style="display: none;">
                        <canvas id="portfolioChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Revenue Chart and Stats -->
    <div class="row">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-1">Revenue Breakdown</h5>
                    <small class="text-muted">Current month revenue sources</small>
                </div>
                <div class="card-body">
                    <div id="revenueLoading" class="chart-loading">
                        <span>⟳</span> Loading chart data...
                    </div>
                    <div class="chart-container" id="revenueContainer" style="display: none;">
                        <canvas id="revenueChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="stats-card">
                <h5 class="mb-3">Quick Stats</h5>
                <div class="row">
                    <div class="col-6">
                        <div class="stat-item">
                            <div class="stat-value text-warning">{{
                                dashboard_data.summary_metrics.loans_due_today|default:0 }}</div>
                            <div class="stat-label">Due Today</div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="stat-item">
                            <div class="stat-value text-danger">{{
                                dashboard_data.summary_metrics.overdue_loans|default:0 }}</div>
                            <div class="stat-label">Overdue</div>
                        </div>
                    </div>
                </div>
                <hr>
                <div class="row">
                    <div class="col-6">
                        <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="stat-label">Processing Fees</div>
                        </div>
                    </div>
                    <div class="col-6">
                        <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="stat-label">Interest Income</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5>Quick Actions</h5>
                </div>
                <div class="card-body">
                    <a href="{% url 'reports:loans_due_report' %}" class="btn-action">
                        <span>📅</span> Loans Due
                    </a>
                    <a href="{% url 'reports:delinquent_loans_report' %}" class="btn-action">
                        <span>⚠️</span> Delinquent Loans
                    </a>
                    <a href="{% url 'reports:processing_fees_report' %}" class="btn-action">
                        <span>💵</span> Processing Fees
                    </a>
                    <a href="{% url 'reports:interest_income_report' %}" class="btn-action">
                        <i class="fas fa-percentage"></i> Interest Income
                    </a>
                    <a href="{% url 'reports:registration_fees_report' %}" 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>
    </div>
</div>

<script>
    // Global chart instances
    let chartInstances = {};

    // Initialize charts when page loads - NO BUTTON CLICKS REQUIRED
    document.addEventListener('DOMContentLoaded', function () {
        console.log('Dashboard loaded - initializing charts automatically...');

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

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

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

        // Show loading
        if (loadingElement) loadingElement.style.display = 'flex';
        if (containerElement) containerElement.style.display = 'none';

        fetch(`/reports/api/simple-chart-data/?chart_type=${chartType}`)
            .then(response => {
                console.log(`${chartType} response status:`, response.status);
                return response.json();
            })
            .then(data => {
                console.log(`${chartType} data:`, 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(`Failed to load ${chartType} data`);
                }
            })
            .catch(error => {
                console.error(`Error loading ${chartType} chart:`, error);

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

                // Create chart with fallback data
                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 element ${canvasId} not found`);
            return;
        }

        // Destroy existing chart if it exists
        if (chartInstances[canvasId]) {
            chartInstances[canvasId].destroy();
        }

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

        // Add scales for line charts
        if (type === 'line') {
            chartConfig.options.scales = {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: 'Amount (KSh)'
                    }
                }
            };
        }

        // Create the chart
        chartInstances[canvasId] = new Chart(ctx.getContext('2d'), chartConfig);
    }

    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'
                }]
            };
        }

        // Default fallback
        return {
            labels: ['No Data'],
            datasets: [{
                label: 'No Data Available',
                data: [0],
                backgroundColor: '#e5e7eb'
            }]
        };
    }

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

    // Prevent any other scripts from interfering
    window.addEventListener('load', function () {
        console.log('Window fully loaded - charts should be visible now');
    });
</script>
{% endblock %}