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

{% block title %}Loans Management - Enhanced Dashboard{% endblock %}

{% block extra_css %}
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
    .dashboard-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 25px rgba(0, 0, 0, 0.08);
        padding: 28px;
        margin-bottom: 28px;
        transition: all 0.4s ease;
        border: 1px solid #f1f5f9;
        position: relative;
        overflow: hidden;
    }

    .dashboard-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, #3B82F6, #10B981, #F59E0B, #EF4444);
        opacity: 0;
        transition: opacity 0.3s ease;
    }

    .dashboard-card:hover::before {
        opacity: 1;
    }

    .dashboard-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
    }

    .metric-card {
        background: linear-gradient(135deg, #3B82F6 0%, #1D4ED8 100%);
        color: white;
        border-radius: 16px;
        padding: 24px;
        text-align: center;
        transition: all 0.4s ease;
        position: relative;
        overflow: hidden;
        cursor: pointer;
    }

    .metric-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
        transition: left 0.6s;
    }

    .metric-card:hover::before {
        left: 100%;
    }

    .metric-card:hover {
        transform: translateY(-6px) scale(1.03);
        box-shadow: 0 15px 35px rgba(59, 130, 246, 0.4);
    }

    .metric-card.success {
        background: linear-gradient(135deg, #10B981 0%, #059669 100%);
    }

    .metric-card.success:hover {
        box-shadow: 0 15px 35px rgba(16, 185, 129, 0.4);
    }

    .metric-card.warning {
        background: linear-gradient(135deg, #F59E0B 0%, #D97706 100%);
    }

    .metric-card.warning:hover {
        box-shadow: 0 15px 35px rgba(245, 158, 11, 0.4);
    }

    .metric-card.danger {
        background: linear-gradient(135deg, #EF4444 0%, #DC2626 100%);
    }

    .metric-card.danger:hover {
        box-shadow: 0 15px 35px rgba(239, 68, 68, 0.4);
    }

    .metric-card.info {
        background: linear-gradient(135deg, #06B6D4 0%, #0891B2 100%);
    }

    .metric-card.info:hover {
        box-shadow: 0 15px 35px rgba(6, 182, 212, 0.4);
    }

    .metric-card.purple {
        background: linear-gradient(135deg, #8B5CF6 0%, #7C3AED 100%);
    }

    .metric-card.purple:hover {
        box-shadow: 0 15px 35px rgba(139, 92, 246, 0.4);
    }

    .metric-value {
        font-size: 3rem;
        font-weight: 800;
        margin-bottom: 12px;
        text-shadow: 0 2px 4px rgba(0,0,0,0.1);
        line-height: 1;
    }

    .metric-label {
        font-size: 1rem;
        opacity: 0.95;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .metric-change {
        font-size: 0.85rem;
        margin-top: 8px;
        opacity: 0.9;
    }

    .export-buttons {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;
        margin-bottom: 24px;
    }

    .export-btn {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        color: white;
        padding: 12px 24px;
        border-radius: 10px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        display: inline-flex;
        align-items: center;
        gap: 10px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .export-btn:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
    }

    .export-btn.pdf { 
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); 
    }
    .export-btn.pdf:hover { 
        box-shadow: 0 8px 25px rgba(239, 68, 68, 0.4); 
    }

    .export-btn.excel { 
        background: linear-gradient(135deg, #10b981 0%, #059669 100%); 
    }
    .export-btn.excel:hover { 
        box-shadow: 0 8px 25px rgba(16, 185, 129, 0.4); 
    }

    .export-btn.csv { 
        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); 
    }
    .export-btn.csv:hover { 
        box-shadow: 0 8px 25px rgba(245, 158, 11, 0.4); 
    }

    .loan-table {
        background: white;
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 4px 25px rgba(0, 0, 0, 0.08);
    }

    .loan-table thead {
        background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
    }

    .loan-table thead th {
        color: white;
        font-weight: 700;
        padding: 20px 16px;
        text-align: left;
        border: none;
        font-size: 14px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .loan-table tbody tr {
        transition: all 0.3s ease;
        border-bottom: 1px solid #f1f5f9;
    }

    .loan-table tbody tr:hover {
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        transform: scale(1.01);
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    }

    .loan-table tbody td {
        padding: 16px;
        vertical-align: middle;
        font-size: 14px;
    }

    .status-badge {
        padding: 6px 16px;
        border-radius: 25px;
        font-size: 12px;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        display: inline-flex;
        align-items: center;
        gap: 6px;
    }

    .status-active {
        background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
        color: #065f46;
        border: 1px solid #10b981;
    }

    .status-completed {
        background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
        color: #1e40af;
        border: 1px solid #3b82f6;
    }

    .status-overdue {
        background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
        color: #991b1b;
        border: 1px solid #ef4444;
    }

    .status-defaulted {
        background: linear-gradient(135deg, #f3f4f6 0%, #e5e7eb 100%);
        color: #374151;
        border: 1px solid #6b7280;
    }

    .chart-container {
        background: white;
        border-radius: 16px;
        padding: 28px;
        box-shadow: 0 4px 25px rgba(0, 0, 0, 0.08);
        margin-bottom: 28px;
        border: 1px solid #f1f5f9;
    }

    .chart-tabs {
        display: flex;
        border-bottom: 3px solid #f1f5f9;
        margin-bottom: 24px;
        gap: 4px;
    }

    .chart-tab {
        padding: 16px 28px;
        cursor: pointer;
        border-bottom: 3px solid transparent;
        transition: all 0.3s ease;
        font-weight: 600;
        color: #64748b;
        border-radius: 8px 8px 0 0;
        position: relative;
    }

    .chart-tab.active {
        border-bottom-color: #3B82F6;
        color: #3B82F6;
        background: linear-gradient(135deg, rgba(59, 130, 246, 0.1) 0%, rgba(59, 130, 246, 0.05) 100%);
    }

    .chart-tab:hover {
        background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(59, 130, 246, 0.02) 100%);
        color: #3B82F6;
    }

    .action-btn {
        padding: 8px 12px;
        border-radius: 8px;
        font-size: 12px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        border: none;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        text-decoration: none;
    }

    .action-btn.view {
        background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
        color: white;
    }

    .action-btn.edit {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: white;
    }

    .action-btn.report {
        background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
        color: white;
    }

    .action-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    }

    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        display: none;
        justify-content: center;
        align-items: center;
        z-index: 9999;
    }

    .loading-content {
        background: white;
        padding: 40px;
        border-radius: 16px;
        text-align: center;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    }

    .loading-spinner {
        width: 60px;
        height: 60px;
        border: 6px solid #f3f3f3;
        border-top: 6px solid #3498db;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin: 0 auto 20px;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .quick-actions {
        display: flex;
        gap: 16px;
        flex-wrap: wrap;
        margin-bottom: 24px;
    }

    .quick-action-btn {
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        border: 2px solid #e2e8f0;
        color: #475569;
        padding: 16px 24px;
        border-radius: 12px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        display: inline-flex;
        align-items: center;
        gap: 12px;
        text-decoration: none;
    }

    .quick-action-btn:hover {
        background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
        color: white;
        border-color: #3b82f6;
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(59, 130, 246, 0.3);
    }
</style>
{% endblock %}

{% block content %}
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6">
    <!-- Page Header -->
    <div class="mb-8">
        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
            <div>
                <h1 class="text-4xl font-bold text-gray-900 mb-2">Loans Management Dashboard</h1>
                <p class="text-gray-600 text-lg">Comprehensive loan analytics and portfolio management</p>
            </div>
            <div class="flex gap-3">
                <a href="{% url 'loans:new_application' %}" 
                   class="bg-gradient-to-r from-blue-600 to-purple-600 text-white px-8 py-4 rounded-xl font-semibold hover:from-blue-700 hover:to-purple-700 transition-all transform hover:-translate-y-1 shadow-lg">
                    <span>+</span>New Loan Application
                </a>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="quick-actions">
        <a href="{% url 'loans:applications' %}" class="quick-action-btn">
            <span>📄</span>
            <span>Pending Applications</span>
        </a>
        <a href="{% url 'loans:loans' %}?status=overdue" class="quick-action-btn">
            <span>⚠️</span>
            <span>Overdue Loans</span>
        </a>
        <a href="{% url 'loans:repayments' %}" class="quick-action-btn">
            <span>💵</span>
            <span>Record Repayment</span>
        </a>
        <a href="{% url 'reports:loans_due_report' %}" class="quick-action-btn">
            <i class="fas fa-calendar-day"></i>
            <span>Due Today</span>
        </a>
    </div>

    <!-- Export Buttons -->
    <div class="export-buttons">
        <button onclick="exportLoans('pdf')" class="export-btn pdf">
            <span>📄</span> Export PDF
        </button>
        <button onclick="exportLoans('excel')" class="export-btn excel">
            <span>📊</span> Export Excel
        </button>
        <button onclick="exportLoans('csv')" class="export-btn csv">
            <i class="fas fa-file-csv"></i> Export CSV
        </button>
    </div>

    <!-- Loan Metrics -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-6 mb-8">
        <div class="metric-card" onclick="filterLoans('all')">
            <div class="metric-value">{{ total_loans|default:0 }}</div>
            <div class="metric-label">Total Loans</div>
            <div class="metric-change">
                <span>↑</span> +12% this month
            </div>
        </div>
        <div class="metric-card success" onclick="filterLoans('active')">
            <div class="metric-value">{{ active_loans|default:0 }}</div>
            <div class="metric-label">Active Loans</div>
            <div class="metric-change">
                <span>↑</span> +8% this month
            </div>
        </div>
        <div class="metric-card info" onclick="filterLoans('completed')">
            <div class="metric-value">{{ completed_loans|default:0 }}</div>
            <div class="metric-label">Completed</div>
            <div class="metric-change">
                <span>↑</span> +15% this month
            </div>
        </div>
        <div class="metric-card warning" onclick="filterLoans('overdue')">
            <div class="metric-value">{{ overdue_loans|default:0 }}</div>
            <div class="metric-label">Overdue</div>
            <div class="metric-change">
                <span>↓</span> -5% this month
            </div>
        </div>
        <div class="metric-card purple">
            <div class="metric-value">KES {{ total_disbursed|default:0|floatformat:0|intcomma }}</div>
            <div class="metric-label">Disbursed</div>
            <div class="metric-change">
                <span>↑</span> +22% this month
            </div>
        </div>
        <div class="metric-card danger">
            <div class="metric-value">{{ collection_rate|default:0|floatformat:1 }}%</div>
            <div class="metric-label">Collection Rate</div>
            <div class="metric-change">
                <span>↑</span> +3% this month
            </div>
        </div>
    </div>

    <!-- Interactive Charts -->
    <div class="chart-container">
        <div class="chart-tabs">
            <div class="chart-tab active" onclick="showChart('portfolio')">Portfolio Overview</div>
            <div class="chart-tab" onclick="showChart('performance')">Performance Analytics</div>
            <div class="chart-tab" onclick="showChart('risk')">Risk Analysis</div>
            <div class="chart-tab" onclick="showChart('trends')">Disbursement Trends</div>
            <div class="chart-tab" onclick="showChart('repayment')">Repayment Analysis</div>
        </div>
        
        <div id="chart-portfolio" class="chart-content">
            <div id="portfolio-chart" style="height: 500px;"></div>
        </div>
        
        <div id="chart-performance" class="chart-content" style="display: none;">
            <div id="performance-chart" style="height: 500px;"></div>
        </div>
        
        <div id="chart-risk" class="chart-content" style="display: none;">
            <div id="risk-chart" style="height: 500px;"></div>
        </div>
        
        <div id="chart-trends" class="chart-content" style="display: none;">
            <div id="trends-chart" style="height: 500px;"></div>
        </div>
        
        <div id="chart-repayment" class="chart-content" style="display: none;">
            <div id="repayment-chart" style="height: 500px;"></div>
        </div>
    </div>

    <!-- Loan Table -->
    <div class="dashboard-card">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold text-gray-900">Recent Loans</h2>
            <div class="flex gap-4 items-center">
                <input type="text" id="searchInput" placeholder="Search loans..." 
                       class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                <select id="statusFilter" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    <option value="">All Status</option>
                    <option value="active">Active</option>
                    <option value="completed">Completed</option>
                    <option value="overdue">Overdue</option>
                    <option value="defaulted">Defaulted</option>
                </select>
            </div>
        </div>
        
        <div class="overflow-x-auto">
            <table class="loan-table w-full">
                <thead>
                    <tr>
                        <th>Loan #</th>
                        <th>Borrower</th>
                        <th>Amount</th>
                        <th>Disbursed</th>
                        <th>Due Date</th>
                        <th>Status</th>
                        <th>Progress</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="loanTableBody">
                    {% for loan in recent_loans %}
                    <tr data-loan-id="{{ loan.id }}" data-status="{{ loan.status }}">
                        <td>
                            <div class="font-bold text-blue-600">#{{ loan.loan_number }}</div>
                            <div class="text-xs text-gray-500">{{ loan.application.loan_product.name|default:"Standard Loan" }}</div>
                        </td>
                        <td>
                            <div class="font-medium text-gray-900">{{ loan.borrower.get_full_name }}</div>
                            <div class="text-sm text-gray-500">{{ loan.borrower.phone_number|default:"N/A" }}</div>
                        </td>
                        <td>
                            <div class="font-bold text-lg">KES {{ loan.principal_amount|floatformat:0|intcomma }}</div>
                            <div class="text-xs text-gray-500">Principal</div>
                        </td>
                        <td>
                            <div class="text-sm">{{ loan.disbursement_date|date:"M d, Y"|default:"Pending" }}</div>
                        </td>
                        <td>
                            <div class="text-sm">{{ loan.due_date|date:"M d, Y"|default:"N/A" }}</div>
                            {% if loan.due_date and loan.due_date < today %}
                                <div class="text-xs text-red-600 font-medium">
                                    {{ loan.days_overdue }} days overdue
                                </div>
                            {% endif %}
                        </td>
                        <td>
                            <span class="status-badge status-{{ loan.status }}">
                                <i class="fas fa-circle text-xs"></i>
                                {{ loan.status|title }}
                            </span>
                        </td>
                        <td>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                {% with progress=loan.repayment_progress %}
                                <div class="bg-gradient-to-r from-blue-500 to-green-500 h-2 rounded-full" 
                                     style="width: {{ progress|default:0 }}%"></div>
                                {% endwith %}
                            </div>
                            <div class="text-xs text-gray-500 mt-1">
                                {{ loan.repayment_progress|default:0|floatformat:0 }}% repaid
                            </div>
                        </td>
                        <td>
                            <div class="flex space-x-2">
                                <a href="{% url 'loans:loan_detail' loan.id %}" class="action-btn view">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="{% url 'loans:edit_loan' loan.id %}" class="action-btn edit">
                                    <span>✏️</span>
                                </a>
                                <button onclick="generateLoanReport({{ loan.id }})" class="action-btn report">
                                    <span>📄</span>
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="8" class="text-center py-12 text-gray-500">
                            <span>💵</span>
                            <div class="text-xl font-medium">No loans found</div>
                            <div class="text-sm">Start by creating a new loan application</div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Loading Overlay -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-content">
        <div class="loading-spinner"></div>
        <h3 class="text-xl font-semibold text-gray-900 mb-2">Processing Request</h3>
        <p class="text-gray-600">Please wait while we generate your report...</p>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // Sample chart data (replace with actual data from Django context)
    const chartData = {
        portfolio: {
            loan_status: {
                'Active': {{ active_loans|default:0 }},
                'Completed': {{ completed_loans|default:0 }},
                'Overdue': {{ overdue_loans|default:0 }},
                'Defaulted': {{ defaulted_loans|default:0 }}
            },
            loan_products: {
                'Business Loans': 45,
                'Personal Loans': 32,
                'Emergency Loans': 18,
                'Agricultural Loans': 12
            },
            amount_distribution: {
                '< 50K': 35,
                '50K - 100K': 42,
                '100K - 200K': 28,
                '200K - 500K': 15,
                '500K+': 8
            }
        },
        performance: {
            monthly_disbursements: {
                months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                amounts: [1200000, 1500000, 1800000, 1600000, 2000000, 1900000],
                counts: [45, 52, 48, 55, 60, 58]
            },
            collection_rates: {
                months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                rates: [85, 88, 92, 87, 90, 89]
            },
            completion_rates: {
                months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                rates: [92, 89, 94, 91, 93, 95]
            }
        },
        risk: {
            par_buckets: {
                'Current': 85,
                '1-30 Days': 10,
                '31-60 Days': 3,
                '60+ Days': 2
            },
            risk_scores: [650, 720, 580, 690, 750, 620, 680, 710, 590, 640, 700, 660, 730, 610, 680],
            default_trend: {
                months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                rates: [3.2, 2.8, 2.1, 2.5, 1.9, 1.6]
            }
        },
        trends: {
            disbursement_trend: {
                months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                amounts: [1200000, 1500000, 1800000, 1600000, 2000000, 1900000],
                targets: [1000000, 1300000, 1600000, 1500000, 1800000, 1700000]
            },
            loan_size_trend: {
                months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                avg_sizes: [26667, 28846, 37500, 29091, 33333, 32759]
            }
        },
        repayment: {
            payment_methods: {
                'M-Pesa': 65,
                'Bank Transfer': 20,
                'Cash': 10,
                'Cheque': 5
            },
            repayment_timing: [-5, -3, -1, 0, 1, 2, 3, 5, 7, 10, 15, 20, 25, 30],
            daily_collections: {
                dates: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                amounts: [45000, 52000, 48000, 55000, 60000, 35000, 25000]
            }
        }
    };

    document.addEventListener('DOMContentLoaded', function() {
        initializeCharts();
        setupFilters();
    });

    function initializeCharts() {
        createPortfolioChart();
        createPerformanceChart();
        createRiskChart();
        createTrendsChart();
        createRepaymentChart();
    }

    function createPortfolioChart() {
        const data = chartData.portfolio;
        
        const fig = Plotly.subplots.make_subplots({
            rows: 2, cols: 2,
            subplot_titles: ['Loan Status Distribution', 'Loan Products', 'Amount Distribution', 'Portfolio Growth'],
            specs: [[{type: 'pie'}, {type: 'bar'}], [{type: 'pie'}, {type: 'scatter'}]]
        });

        // Loan status pie chart
        fig.add_trace({
            type: 'pie',
            labels: Object.keys(data.loan_status),
            values: Object.values(data.loan_status),
            hole: 0.4,
            marker: {colors: ['#3B82F6', '#10B981', '#F59E0B', '#EF4444']}
        }, 1, 1);

        // Loan products bar chart
        fig.add_trace({
            type: 'bar',
            x: Object.keys(data.loan_products),
            y: Object.values(data.loan_products),
            marker: {color: '#3B82F6'}
        }, 1, 2);

        // Amount distribution pie chart
        fig.add_trace({
            type: 'pie',
            labels: Object.keys(data.amount_distribution),
            values: Object.values(data.amount_distribution),
            hole: 0.3,
            marker: {colors: ['#10B981', '#3B82F6', '#F59E0B', '#EF4444', '#8B5CF6']}
        }, 2, 1);

        // Sample portfolio growth
        fig.add_trace({
            type: 'scatter',
            mode: 'lines+markers',
            x: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
            y: [15000000, 18000000, 22000000, 25000000, 28000000, 32000000],
            line: {color: '#10B981', width: 3},
            fill: 'tonexty'
        }, 2, 2);

        const layout = {
            title: 'Portfolio Overview Dashboard',
            height: 500,
            showlegend: false,
            template: 'plotly_white'
        };

        Plotly.newPlot('portfolio-chart', fig.data, layout);
    }

    function createPerformanceChart() {
        const data = chartData.performance;
        
        const fig = Plotly.subplots.make_subplots({
            rows: 2, cols: 2,
            subplot_titles: ['Monthly Disbursements', 'Loan Volume', 'Collection Rates', 'Completion Rates'],
            specs: [[{type: 'bar'}, {type: 'bar'}], [{type: 'scatter'}, {type: 'scatter'}]]
        });

        // Monthly disbursements
        fig.add_trace({
            type: 'bar',
            x: data.monthly_disbursements.months,
            y: data.monthly_disbursements.amounts,
            marker: {color: '#3B82F6'}
        }, 1, 1);

        // Loan volume
        fig.add_trace({
            type: 'bar',
            x: data.monthly_disbursements.months,
            y: data.monthly_disbursements.counts,
            marker: {color: '#10B981'}
        }, 1, 2);

        // Collection rates
        fig.add_trace({
            type: 'scatter',
            mode: 'lines+markers',
            x: data.collection_rates.months,
            y: data.collection_rates.rates,
            line: {color: '#F59E0B', width: 3}
        }, 2, 1);

        // Completion rates
        fig.add_trace({
            type: 'scatter',
            mode: 'lines+markers',
            x: data.completion_rates.months,
            y: data.completion_rates.rates,
            line: {color: '#10B981', width: 3}
        }, 2, 2);

        const layout = {
            title: 'Performance Analytics Dashboard',
            height: 500,
            showlegend: false,
            template: 'plotly_white'
        };

        Plotly.newPlot('performance-chart', fig.data, layout);
    }

    function createRiskChart() {
        const data = chartData.risk;
        
        const fig = Plotly.subplots.make_subplots({
            rows: 2, cols: 2,
            subplot_titles: ['Portfolio at Risk', 'Risk Score Distribution', 'Default Trend', 'Risk Heatmap'],
            specs: [[{type: 'bar'}, {type: 'histogram'}], [{type: 'scatter'}, {type: 'bar'}]]
        });

        // PAR buckets
        fig.add_trace({
            type: 'bar',
            x: Object.keys(data.par_buckets),
            y: Object.values(data.par_buckets),
            marker: {color: ['#10B981', '#F59E0B', '#EF4444', '#DC2626']}
        }, 1, 1);

        // Risk score distribution
        fig.add_trace({
            type: 'histogram',
            x: data.risk_scores,
            nbinsx: 10,
            marker: {color: '#06B6D4'}
        }, 1, 2);

        // Default trend
        fig.add_trace({
            type: 'scatter',
            mode: 'lines+markers',
            x: data.default_trend.months,
            y: data.default_trend.rates,
            line: {color: '#EF4444', width: 3}
        }, 2, 1);

        // Sample risk categories
        fig.add_trace({
            type: 'bar',
            x: ['Low Risk', 'Medium Risk', 'High Risk'],
            y: [70, 25, 5],
            marker: {color: ['#10B981', '#F59E0B', '#EF4444']}
        }, 2, 2);

        const layout = {
            title: 'Risk Analysis Dashboard',
            height: 500,
            showlegend: false,
            template: 'plotly_white'
        };

        Plotly.newPlot('risk-chart', fig.data, layout);
    }

    function createTrendsChart() {
        const data = chartData.trends;
        
        const trace1 = {
            x: data.disbursement_trend.months,
            y: data.disbursement_trend.amounts,
            type: 'bar',
            name: 'Actual Disbursements',
            marker: {color: '#3B82F6'}
        };

        const trace2 = {
            x: data.disbursement_trend.months,
            y: data.disbursement_trend.targets,
            type: 'scatter',
            mode: 'lines+markers',
            name: 'Target',
            line: {color: '#EF4444', width: 3, dash: 'dash'}
        };

        const trace3 = {
            x: data.loan_size_trend.months,
            y: data.loan_size_trend.avg_sizes,
            type: 'scatter',
            mode: 'lines+markers',
            name: 'Avg Loan Size',
            yaxis: 'y2',
            line: {color: '#10B981', width: 3}
        };

        const layout = {
            title: 'Disbursement Trends Analysis',
            xaxis: {title: 'Month'},
            yaxis: {title: 'Amount (KES)'},
            yaxis2: {
                title: 'Average Loan Size (KES)',
                overlaying: 'y',
                side: 'right'
            },
            height: 500,
            template: 'plotly_white'
        };

        Plotly.newPlot('trends-chart', [trace1, trace2, trace3], layout);
    }

    function createRepaymentChart() {
        const data = chartData.repayment;
        
        const fig = Plotly.subplots.make_subplots({
            rows: 2, cols: 2,
            subplot_titles: ['Payment Methods', 'Repayment Timing', 'Daily Collections', 'Collection Efficiency'],
            specs: [[{type: 'pie'}, {type: 'histogram'}], [{type: 'bar'}, {type: 'scatter'}]]
        });

        // Payment methods
        fig.add_trace({
            type: 'pie',
            labels: Object.keys(data.payment_methods),
            values: Object.values(data.payment_methods),
            hole: 0.4,
            marker: {colors: ['#10B981', '#3B82F6', '#F59E0B', '#8B5CF6']}
        }, 1, 1);

        // Repayment timing
        fig.add_trace({
            type: 'histogram',
            x: data.repayment_timing,
            nbinsx: 15,
            marker: {color: '#06B6D4'}
        }, 1, 2);

        // Daily collections
        fig.add_trace({
            type: 'bar',
            x: data.daily_collections.dates,
            y: data.daily_collections.amounts,
            marker: {color: '#10B981'}
        }, 2, 1);

        // Sample efficiency trend
        fig.add_trace({
            type: 'scatter',
            mode: 'lines+markers',
            x: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
            y: [78, 82, 85, 80, 88, 86],
            line: {color: '#3B82F6', width: 3}
        }, 2, 2);

        const layout = {
            title: 'Repayment Analysis Dashboard',
            height: 500,
            showlegend: false,
            template: 'plotly_white'
        };

        Plotly.newPlot('repayment-chart', fig.data, layout);
    }

    function showChart(chartType) {
        // Hide all chart contents
        document.querySelectorAll('.chart-content').forEach(content => {
            content.style.display = 'none';
        });
        
        // Remove active class from all tabs
        document.querySelectorAll('.chart-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        
        // Show selected chart
        document.getElementById(`chart-${chartType}`).style.display = 'block';
        event.target.classList.add('active');
    }

    function setupFilters() {
        const searchInput = document.getElementById('searchInput');
        const statusFilter = document.getElementById('statusFilter');
        
        searchInput.addEventListener('input', filterTable);
        statusFilter.addEventListener('change', filterTable);
    }

    function filterTable() {
        const searchTerm = document.getElementById('searchInput').value.toLowerCase();
        const statusFilter = document.getElementById('statusFilter').value;
        
        const rows = document.querySelectorAll('#loanTableBody tr');
        
        rows.forEach(row => {
            const loanNumber = row.querySelector('td:first-child').textContent.toLowerCase();
            const borrowerName = row.querySelector('td:nth-child(2)').textContent.toLowerCase();
            const loanStatus = row.dataset.status;
            
            let showRow = true;
            
            // Search filter
            if (searchTerm && !loanNumber.includes(searchTerm) && !borrowerName.includes(searchTerm)) {
                showRow = false;
            }
            
            // Status filter
            if (statusFilter && loanStatus !== statusFilter) {
                showRow = false;
            }
            
            row.style.display = showRow ? '' : 'none';
        });
    }

    function filterLoans(status) {
        const statusFilter = document.getElementById('statusFilter');
        statusFilter.value = status === 'all' ? '' : status;
        filterTable();
    }

    function exportLoans(format) {
        showLoading();
        
        setTimeout(() => {
            hideLoading();
            
            const link = document.createElement('a');
            link.href = `{% url 'loans:loans' %}?format=${format}`;
            link.download = `loans_report.${format}`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }, 2000);
    }

    function generateLoanReport(loanId) {
        showLoading();
        
        setTimeout(() => {
            hideLoading();
            window.open(`/loans/${loanId}/report/`, '_blank');
        }, 1500);
    }

    function showLoading() {
        document.getElementById('loadingOverlay').style.display = 'flex';
    }

    function hideLoading() {
        document.getElementById('loadingOverlay').style.display = 'none';
    }
</script>
{% endblock %}