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

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

{% block extra_css %}
<link href="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.min.css" rel="stylesheet">
<style>
    .dashboard-card {
        background: white;
        border-radius: 12px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        padding: 24px;
        margin-bottom: 24px;
        border: 1px solid #e5e7eb;
        transition: transform 0.2s ease, box-shadow 0.2s ease;
    }
    
    .dashboard-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    }
    
    .metric-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 12px;
        padding: 20px;
        text-align: center;
        margin-bottom: 20px;
        cursor: pointer;
        transition: transform 0.2s ease;
    }
    
    .metric-card:hover {
        transform: scale(1.05);
    }
    
    .metric-value {
        font-size: 2.5rem;
        font-weight: bold;
        margin-bottom: 8px;
        color: white !important;
    }
    
    .metric-label {
        font-size: 0.9rem;
        opacity: 0.9;
        color: white !important;
    }
    
    .chart-container {
        position: relative;
        height: 400px;
        margin: 20px 0;
        background: #f8fafc;
        border-radius: 8px;
        padding: 10px;
    }
    
    .chart-loading {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        color: #6b7280;
        font-size: 1.1rem;
    }
    
    .chart-error {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        color: #ef4444;
        font-size: 1rem;
        flex-direction: column;
    }
    
    .quick-action-btn {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: white !important;
        border: none;
        padding: 12px 24px;
        border-radius: 8px;
        font-weight: 500;
        margin: 4px;
        transition: all 0.2s ease;
        text-decoration: none;
        display: inline-block;
        text-align: center;
    }
    
    .quick-action-btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
        color: white !important;
        text-decoration: none;
    }
    
    .assign-clients-btn {
        background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
        color: white !important;
        border: none;
        padding: 12px 24px;
        border-radius: 8px;
        font-weight: 500;
        margin: 4px;
        transition: all 0.2s ease;
        text-decoration: none;
        display: inline-block;
        text-align: center;
    }
    
    .assign-clients-btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
        color: white !important;
        text-decoration: none;
    }
    
    .analytics-btn {
        background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
        color: white !important;
        border: none;
        padding: 12px 24px;
        border-radius: 8px;
        font-weight: 500;
        margin: 4px;
        transition: all 0.2s ease;
        text-decoration: none;
        display: inline-block;
        text-align: center;
    }
    
    .analytics-btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(139, 92, 246, 0.3);
        color: white !important;
        text-decoration: none;
    }
    
    .status-indicator {
        display: inline-flex;
        align-items: center;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 0.8rem;
        font-weight: 500;
    }
    
    .status-success {
        background: #dcfce7;
        color: #166534;
    }
    
    .status-warning {
        background: #fef3c7;
        color: #92400e;
    }
    
    .status-danger {
        background: #fef2f2;
        color: #991b1b;
    }
    
    .refresh-indicator {
        position: fixed;
        top: 20px;
        right: 20px;
        background: #3b82f6;
        color: white;
        padding: 8px 16px;
        border-radius: 20px;
        font-size: 0.9rem;
        z-index: 1000;
        display: none;
    }
    
    .performance-indicator {
        display: inline-block;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        margin-right: 8px;
    }
    
    .indicator-good {
        background: #10b981;
    }
    
    .indicator-warning {
        background: #f59e0b;
    }
    
    .indicator-poor {
        background: #ef4444;
    }
    
    /* Fix button text visibility */
    .btn, button, .quick-action-btn, .assign-clients-btn, .analytics-btn {
        color: white !important;
        text-shadow: none !important;
    }
    
    .btn:hover, button:hover, .quick-action-btn:hover, .assign-clients-btn:hover, .analytics-btn:hover {
        color: white !important;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- Refresh Indicator -->
    <div id="refreshIndicator" class="refresh-indicator">
        <span>🔄</span> Refreshing data...
    </div>

    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-0">Reports & Analytics Dashboard</h1>
            <p class="text-muted">Comprehensive loan management analytics and reporting</p>
        </div>
        <div>
            <button class="btn btn-outline-primary" onclick="refreshDashboard()">
                <span>🔄</span> Refresh
            </button>
            <button class="btn btn-primary" onclick="exportDashboard()">
                <span>⬇️</span> Export
            </button>
        </div>
    </div>

    <!-- Key Metrics -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="metric-card" onclick="navigateToReport('portfolio')">
                <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%);" onclick="navigateToReport('portfolio')">
                <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%);" onclick="navigateToReport('outstanding')">
                <div class="metric-value">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" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);" onclick="navigateToReport('collections')">
                <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>

    <!-- Performance Overview -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="dashboard-card">
                <h5 class="mb-3">
                    <span class="performance-indicator indicator-{% if dashboard_data.summary_metrics.collection_rate >= 80 %}good{% elif dashboard_data.summary_metrics.collection_rate >= 60 %}warning{% else %}poor{% endif %}"></span>
                    Performance Overview
                </h5>
                <div class="mb-3">
                    <div class="d-flex justify-content-between">
                        <span>Loans Due Today</span>
                        <strong class="text-warning">{{ dashboard_data.summary_metrics.loans_due_today|default:0 }}</strong>
                    </div>
                </div>
                <div class="mb-3">
                    <div class="d-flex justify-content-between">
                        <span>Overdue Loans</span>
                        <strong class="text-danger">{{ dashboard_data.summary_metrics.overdue_loans|default:0 }}</strong>
                    </div>
                </div>
                <div class="mb-3">
                    <div class="d-flex justify-content-between">
                        <span>Collection Rate</span>
                        <span class="status-indicator {% if dashboard_data.summary_metrics.collection_rate >= 80 %}status-success{% elif dashboard_data.summary_metrics.collection_rate >= 60 %}status-warning{% else %}status-danger{% endif %}">
                            {{ dashboard_data.summary_metrics.collection_rate|floatformat:1|default:0 }}%
                        </span>
                    </div>
                </div>
                <button class="quick-action-btn w-100" onclick="navigateToReport('loans-due')">
                    <span>📅</span> View Due Loans
                </button>
            </div>
        </div>
        <div class="col-md-8">
            <div class="dashboard-card">
                <h5 class="mb-3">Loan Performance</h5>
                <p class="text-muted mb-3">Monthly disbursements vs collections</p>
                <div class="chart-container">
                    <div id="loanPerformanceLoading" class="chart-loading">
                        <span>⟳</span> Loading chart data...
                    </div>
                    <canvas id="loanPerformanceChart" style="display: none;"></canvas>
                    <div id="loanPerformanceError" class="chart-error" style="display: none;">
                        <span>⚠️</span>
                        <span>Unable to load chart data</span>
                        <button class="btn btn-sm btn-outline-primary mt-2" onclick="retryChart('loanPerformance')">
                            <span>↷</span> Retry
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Revenue Analytics -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="dashboard-card">
                <h5 class="mb-3">Processing Fees</h5>
                <div class="mb-2">
                    <div class="d-flex justify-content-between">
                        <span>This Month</span>
                        <strong>KSh {{ dashboard_data.processing_fees_current_month.summary.total_processing_fees|floatformat:0|default:0 }}</strong>
                    </div>
                </div>
                <div class="mb-3">
                    <div class="d-flex justify-content-between">
                        <span>Loans Processed</span>
                        <strong>{{ dashboard_data.processing_fees_current_month.summary.total_loans_processed|default:0 }}</strong>
                    </div>
                </div>
                <button class="quick-action-btn w-100" onclick="navigateToReport('processing-fees')">
                    <span>📈</span> View Details
                </button>
            </div>
        </div>
        <div class="col-md-4">
            <div class="dashboard-card">
                <h5 class="mb-3">Interest Income</h5>
                <div class="mb-2">
                    <div class="d-flex justify-content-between">
                        <span>This Month</span>
                        <strong>KSh {{ dashboard_data.interest_income_current_month.summary.total_interest_income|floatformat:0|default:0 }}</strong>
                    </div>
                </div>
                <div class="mb-3">
                    <div class="d-flex justify-content-between">
                        <span>Interest Loans</span>
                        <strong>{{ dashboard_data.interest_income_current_month.summary.total_loans|default:0 }}</strong>
                    </div>
                </div>
                <button class="quick-action-btn w-100" onclick="navigateToReport('interest-income')">
                    <i class="fas fa-percentage"></i> View Details
                </button>
            </div>
        </div>
        <div class="col-md-4">
            <div class="dashboard-card">
                <h5 class="mb-3">Registration Fees</h5>
                <div class="mb-2">
                    <div class="d-flex justify-content-between">
                        <span>This Month</span>
                        <strong>KSh {{ dashboard_data.registration_fees_current_month.summary.total_registration_income|floatformat:0|default:0 }}</strong>
                    </div>
                </div>
                <div class="mb-3">
                    <div class="d-flex justify-content-between">
                        <span>Registrations</span>
                        <strong>{{ dashboard_data.registration_fees_current_month.summary.total_registrations|default:0 }}</strong>
                    </div>
                </div>
                <button class="quick-action-btn w-100" onclick="navigateToReport('registration-fees')">
                    <span>👤+</span> View Details
                </button>
            </div>
        </div>
    </div>

    <!-- Charts Row -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="dashboard-card">
                <h5 class="mb-3">Portfolio Distribution</h5>
                <div class="chart-container">
                    <div id="portfolioDistributionLoading" class="chart-loading">
                        <span>⟳</span> Loading chart data...
                    </div>
                    <canvas id="portfolioDistributionChart" style="display: none;"></canvas>
                    <div id="portfolioDistributionError" class="chart-error" style="display: none;">
                        <span>⚠️</span>
                        <span>Unable to load chart data</span>
                        <button class="btn btn-sm btn-outline-primary mt-2" onclick="retryChart('portfolioDistribution')">
                            <span>↷</span> Retry
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="dashboard-card">
                <h5 class="mb-3">Revenue Breakdown</h5>
                <div class="chart-container">
                    <div id="revenueBreakdownLoading" class="chart-loading">
                        <span>⟳</span> Loading chart data...
                    </div>
                    <canvas id="revenueBreakdownChart" style="display: none;"></canvas>
                    <div id="revenueBreakdownError" class="chart-error" style="display: none;">
                        <span>⚠️</span>
                        <span>Unable to load chart data</span>
                        <button class="btn btn-sm btn-outline-primary mt-2" onclick="retryChart('revenueBreakdown')">
                            <span>↷</span> Retry
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Delinquency Analysis -->
    <div class="row mb-4">
        <div class="col-md-8">
            <div class="dashboard-card">
                <h5 class="mb-3">Delinquency Trend</h5>
                <div class="chart-container">
                    <div id="delinquencyTrendLoading" class="chart-loading">
                        <span>⟳</span> Loading chart data...
                    </div>
                    <canvas id="delinquencyTrendChart" style="display: none;"></canvas>
                    <div id="delinquencyTrendError" class="chart-error" style="display: none;">
                        <span>⚠️</span>
                        <span>Unable to load chart data</span>
                        <button class="btn btn-sm btn-outline-primary mt-2" onclick="retryChart('delinquencyTrend')">
                            <span>↷</span> Retry
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="dashboard-card">
                <h5 class="mb-3">Delinquent Loans</h5>
                <div class="mb-3">
                    <div class="d-flex justify-content-between">
                        <span>Mild (1-30 days)</span>
                        <strong class="text-warning">{{ dashboard_data.delinquent_loans.summary.mild_delinquent_count|default:0 }}</strong>
                    </div>
                </div>
                <div class="mb-3">
                    <div class="d-flex justify-content-between">
                        <span>Moderate (31-60 days)</span>
                        <strong class="text-danger">{{ dashboard_data.delinquent_loans.summary.moderate_delinquent_count|default:0 }}</strong>
                    </div>
                </div>
                <div class="mb-3">
                    <div class="d-flex justify-content-between">
                        <span>Severe (60+ days)</span>
                        <strong class="text-dark">{{ dashboard_data.delinquent_loans.summary.severe_delinquent_count|default:0 }}</strong>
                    </div>
                </div>
                <button class="quick-action-btn w-100" onclick="navigateToReport('delinquent-loans')">
                    <span>⚠️</span> View All Delinquent
                </button>
            </div>
        </div>
    </div>

    <!-- Quick Actions with Fixed Button Text -->
    <div class="dashboard-card">
        <h5 class="mb-3">Quick Actions</h5>
        <div class="row">
            <div class="col-md-3">
                <a href="{% url 'loans:loans' %}" class="assign-clients-btn w-100">
                    <span>👥</span> Manage Clients
                </a>
            </div>
            <div class="col-md-3">
                <a href="{% url 'reports:loan_analytics_dashboard' %}" class="analytics-btn w-100">
                    <span>📊</span> Analytics
                </a>
            </div>
            <div class="col-md-3">
                <button class="quick-action-btn w-100" onclick="navigateToReport('loans-due')">
                    <span>📅</span> Loans Due Today
                </button>
            </div>
            <div class="col-md-3">
                <button class="quick-action-btn w-100" onclick="exportDashboard()">
                    <span>⬇️</span> Export Reports
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.min.js"></script>
<script>
// Global chart instances
let charts = {};

// Initialize dashboard
document.addEventListener('DOMContentLoaded', function() {
    initializeCharts();
    
    // Auto-refresh every 5 minutes
    setInterval(refreshDashboard, 300000);
});

// Initialize all charts
function initializeCharts() {
    loadChart('loanPerformance', 'loan_performance');
    loadChart('portfolioDistribution', 'portfolio_distribution');
    loadChart('revenueBreakdown', 'revenue_breakdown');
    loadChart('delinquencyTrend', 'delinquency_trend');
}

// Load individual chart
function loadChart(chartName, chartType) {
    const loadingElement = document.getElementById(chartName + 'Loading');
    const canvasElement = document.getElementById(chartName + 'Chart');
    const errorElement = document.getElementById(chartName + 'Error');
    
    // Show loading state
    loadingElement.style.display = 'flex';
    canvasElement.style.display = 'none';
    errorElement.style.display = 'none';
    
    // Fetch chart data
    fetch(`/reports/api/v2/chart-data/?chart_type=${chartType}`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data && !data.data.error) {
                // Hide loading, show canvas
                loadingElement.style.display = 'none';
                canvasElement.style.display = 'block';
                errorElement.style.display = 'none';
                
                // Create chart
                createChart(chartName, data.data);
            } else {
                throw new Error(data.data?.error || 'Failed to load chart data');
            }
        })
        .catch(error => {
            console.error(`Error loading ${chartName} chart:`, error);
            
            // Show error state
            loadingElement.style.display = 'none';
            canvasElement.style.display = 'none';
            errorElement.style.display = 'flex';
        });
}

// Create chart instance
function createChart(chartName, chartData) {
    const ctx = document.getElementById(chartName + 'Chart').getContext('2d');
    
    // Destroy existing chart if it exists
    if (charts[chartName]) {
        charts[chartName].destroy();
    }
    
    // Determine chart type and options based on chart name
    let chartConfig = {
        data: chartData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        padding: 20,
                        usePointStyle: true
                    }
                }
            }
        }
    };
    
    // Customize based on chart type
    if (chartName === 'loanPerformance' || chartName === 'delinquencyTrend') {
        chartConfig.type = 'line';
        chartConfig.options.scales = {
            y: {
                beginAtZero: true,
                title: {
                    display: true,
                    text: 'Amount (KSh)'
                }
            }
        };
        
        if (chartName === 'delinquencyTrend') {
            chartConfig.options.scales.y1 = {
                type: 'linear',
                display: true,
                position: 'right',
                title: {
                    display: true,
                    text: 'Number of Loans'
                },
                grid: {
                    drawOnChartArea: false,
                }
            };
        }
    } else if (chartName === 'portfolioDistribution' || chartName === 'revenueBreakdown') {
        chartConfig.type = chartName === 'portfolioDistribution' ? 'doughnut' : 'pie';
        chartConfig.options.plugins.tooltip = {
            callbacks: {
                label: function(context) {
                    const value = context.parsed;
                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                    const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
                    return `${context.label}: KSh ${value.toLocaleString()} (${percentage}%)`;
                }
            }
        };
    }
    
    // Create the chart
    charts[chartName] = new Chart(ctx, chartConfig);
}

// Retry loading a specific chart
function retryChart(chartName) {
    const chartTypeMap = {
        'loanPerformance': 'loan_performance',
        'portfolioDistribution': 'portfolio_distribution',
        'revenueBreakdown': 'revenue_breakdown',
        'delinquencyTrend': 'delinquency_trend'
    };
    
    loadChart(chartName, chartTypeMap[chartName]);
}

// Refresh entire dashboard
function refreshDashboard() {
    const indicator = document.getElementById('refreshIndicator');
    indicator.style.display = 'block';
    
    // Refresh all charts
    initializeCharts();
    
    // Refresh dashboard data
    fetch('/reports/api/v2/real-time-refresh/')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update metrics if needed
                console.log('Dashboard refreshed successfully');
            }
        })
        .catch(error => {
            console.error('Error refreshing dashboard:', error);
        })
        .finally(() => {
            setTimeout(() => {
                indicator.style.display = 'none';
            }, 2000);
        });
}

// Navigation functions
function navigateToReport(reportType) {
    const reportUrls = {
        'portfolio': '/reports/portfolio-details/',
        'outstanding': '/reports/outstanding-loans/',
        'collections': '/reports/collection-details/',
        'loans-due': '/reports/loans-due/',
        'loans-in-arrears': '{% url "reports:loans_in_arrears_report" %}',
        'delinquent-loans': '/reports/delinquent-loans/',
        'processing-fees': '/reports/processing-fees/',
        'interest-income': '/reports/interest-income/',
        'registration-fees': '/reports/registration-fees/'
    };
    
    if (reportUrls[reportType]) {
        window.location.href = reportUrls[reportType];
    }
}

// Export dashboard
function exportDashboard() {
    // Create export options modal or direct export
    const exportUrl = '/reports/export/dashboard/?format=excel';
    window.open(exportUrl, '_blank');
}

// Error handling for failed chart loads
window.addEventListener('error', function(e) {
    console.error('Global error:', e.error);
});

// Handle chart.js errors gracefully
Chart.defaults.plugins.legend.onClick = function(e, legendItem, legend) {
    try {
        Chart.defaults.plugins.legend.onClick.call(this, e, legendItem, legend);
    } catch (error) {
        console.error('Chart legend click error:', error);
    }
};
</script>
{% endblock %}