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

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

{% block extra_css %}
<style>
    * {
        box-sizing: border-box;
    }

    body {
        background: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #334155 100%);
        min-height: 100vh;
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    }

    .main-container {
        background: rgba(255, 255, 255, 0.98);
        backdrop-filter: blur(20px);
        border-radius: 24px;
        margin: 2rem;
        padding: 2.5rem;
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.4);
    }

    .page-header {
        text-align: center;
        margin-bottom: 3rem;
        padding: 3rem 2rem;
        background: linear-gradient(135deg, #6366f1 0%, #4f46e5 50%, #4338ca 100%);
        color: white;
        border-radius: 20px;
        position: relative;
        overflow: hidden;
    }

    .page-header::before {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: repeating-linear-gradient(
            45deg,
            transparent,
            transparent 10px,
            rgba(255, 255, 255, 0.03) 10px,
            rgba(255, 255, 255, 0.03) 20px
        );
        animation: slide 20s linear infinite;
    }

    @keyframes slide {
        0% { transform: translate(0, 0); }
        100% { transform: translate(50%, 50%); }
    }

    .page-title {
        font-size: 3rem;
        font-weight: 900;
        margin-bottom: 0.5rem;
        position: relative;
        z-index: 1;
        text-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    }

    .page-subtitle {
        font-size: 1.2rem;
        opacity: 0.95;
        position: relative;
        z-index: 1;
        font-weight: 500;
    }

    .metrics-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 1.5rem;
        margin-bottom: 3rem;
    }

    .metric-card {
        background: white;
        border: 2px solid #e5e7eb;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        color: #1f2937;
        border-radius: 16px;
        padding: 2rem;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .metric-card::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 4px;
        background: linear-gradient(90deg, #6366f1, #8b5cf6);
    }

    .metric-card.info::after {
        background: linear-gradient(90deg, #06b6d4, #0891b2);
    }

    .metric-card.warning::after {
        background: linear-gradient(90deg, #f59e0b, #d97706);
    }

    .metric-card.success::after {
        background: linear-gradient(90deg, #10b981, #059669);
    }

    .metric-card.danger::after {
        background: linear-gradient(90deg, #ef4444, #dc2626);
    }

    .metric-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.15);
        border-color: #d1d5db;
    }

    .metric-value {
        font-size: 2.5rem;
        font-weight: 800;
        margin-bottom: 0.5rem;
        background: linear-gradient(135deg, #1f2937 0%, #374151 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }

    .metric-label {
        font-size: 0.95rem;
        color: #6b7280;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

    .metric-icon {
        position: absolute;
        top: 1.5rem;
        right: 1.5rem;
        width: 48px;
        height: 48px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 12px;
        font-size: 1.5rem;
    }

    .metric-card.info .metric-icon {
        background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
        color: #0369a1;
    }

    .metric-card.warning .metric-icon {
        background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
        color: #b45309;
    }

    .metric-card.success .metric-icon {
        background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%);
        color: #047857;
    }

    .metric-card.danger .metric-icon {
        background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
        color: #b91c1c;
    }

    .analytics-section {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 2rem;
        margin-bottom: 3rem;
    }

    .chart-container {
        background: white;
        border-radius: 16px;
        padding: 2rem;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        border: 1px solid #e5e7eb;
    }

    .chart-header {
        margin-bottom: 1.5rem;
    }

    .chart-title {
        font-size: 1.25rem;
        font-weight: 700;
        color: #1f2937;
        margin-bottom: 0.25rem;
    }

    .chart-subtitle {
        font-size: 0.875rem;
        color: #6b7280;
    }

    .chart-canvas {
        width: 100%;
        height: 300px;
    }

    .filter-section {
        background: white;
        border-radius: 16px;
        padding: 2rem;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        border: 1px solid #e5e7eb;
        margin-bottom: 2rem;
    }

    .filter-title {
        font-size: 1.25rem;
        font-weight: 700;
        color: #1f2937;
        margin-bottom: 1.5rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .filter-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
        align-items: end;
    }

    .filter-group {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }

    .filter-label {
        font-size: 0.875rem;
        font-weight: 600;
        color: #374151;
    }

    .filter-select, .filter-input {
        padding: 0.75rem;
        border: 2px solid #e5e7eb;
        border-radius: 10px;
        font-size: 0.875rem;
        transition: all 0.2s;
        background: white;
    }

    .filter-select:focus, .filter-input:focus {
        outline: none;
        border-color: #6366f1;
        box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
    }

    .data-table-container {
        background: white;
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        border: 1px solid #e5e7eb;
    }

    .table-header {
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        padding: 1.5rem 2rem;
        border-bottom: 2px solid #e5e7eb;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .table-title {
        font-size: 1.5rem;
        font-weight: 700;
        color: #1f2937;
    }

    .table-subtitle {
        color: #6b7280;
        font-size: 0.875rem;
    }

    .data-table {
        width: 100%;
        border-collapse: collapse;
    }

    .data-table th {
        background: #f8fafc;
        padding: 1rem 1.5rem;
        text-align: left;
        font-weight: 700;
        color: #374151;
        border-bottom: 2px solid #e5e7eb;
        font-size: 0.8rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

    .data-table td {
        padding: 1.25rem 1.5rem;
        border-bottom: 1px solid #f3f4f6;
        vertical-align: middle;
    }

    .data-table tbody tr {
        transition: all 0.2s;
    }

    .data-table tbody tr:hover {
        background: #f9fafb;
        transform: scale(1.001);
    }

    .priority-badge {
        padding: 0.5rem 1rem;
        border-radius: 9999px;
        font-size: 0.7rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        display: inline-block;
    }

    .priority-overdue {
        background: #fee2e2;
        color: #991b1b;
    }

    .priority-due-today {
        background: #fef3c7;
        color: #92400e;
    }

    .priority-due-this-week {
        background: #dbeafe;
        color: #1e40af;
    }

    .priority-due-later {
        background: #dcfce7;
        color: #166534;
    }

    .action-btn {
        padding: 0.5rem 1rem;
        border-radius: 8px;
        font-size: 0.75rem;
        font-weight: 600;
        transition: all 0.2s;
        border: none;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 0.25rem;
    }

    .action-btn.primary {
        background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
        color: white;
    }

    .action-btn.primary:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(99, 102, 241, 0.4);
    }

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

    .action-btn.success:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
    }

    .action-btn.warning {
        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        color: white;
    }

    .action-btn.warning:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(245, 158, 11, 0.4);
    }

    .amount-cell {
        font-weight: 700;
        font-size: 1.1rem;
    }

    .days-until-due {
        font-weight: 600;
        padding: 0.4rem 0.9rem;
        border-radius: 9999px;
        font-size: 0.75rem;
    }

    .days-until-due.overdue {
        background: #fee2e2;
        color: #991b1b;
    }

    .days-until-due.due-today {
        background: #fef3c7;
        color: #92400e;
    }

    .days-until-due.due-soon {
        background: #dbeafe;
        color: #1e40af;
    }

    .days-until-due.due-later {
        background: #dcfce7;
        color: #166534;
    }

    .no-data {
        text-align: center;
        padding: 4rem;
        color: #6b7280;
    }

    .no-data-icon {
        font-size: 4rem;
        margin-bottom: 1rem;
        opacity: 0.3;
    }

    .export-buttons {
        display: flex;
        gap: 1rem;
        margin-bottom: 2rem;
        justify-content: flex-end;
    }

    .export-btn {
        padding: 0.75rem 1.5rem;
        border-radius: 10px;
        font-weight: 600;
        transition: all 0.2s;
        border: none;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
    }

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

    .export-btn.pdf {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        color: white;
    }

    .export-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
    }

    .priority-breakdown {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 1rem;
        margin-top: 1.5rem;
    }

    .priority-item {
        padding: 1rem;
        border-radius: 12px;
        border: 2px solid #e5e7eb;
        transition: all 0.2s;
    }

    .priority-item:hover {
        border-color: #d1d5db;
        transform: translateY(-2px);
    }

    .priority-item-label {
        font-size: 0.75rem;
        font-weight: 600;
        color: #6b7280;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        margin-bottom: 0.5rem;
    }

    .priority-item-value {
        font-size: 1.5rem;
        font-weight: 800;
        color: #1f2937;
    }

    @media (max-width: 1024px) {
        .analytics-section {
            grid-template-columns: 1fr;
        }
    }

    @media (max-width: 768px) {
        .main-container {
            margin: 1rem;
            padding: 1.5rem;
        }
        
        .page-title {
            font-size: 2rem;
        }
        
        .metrics-grid {
            grid-template-columns: 1fr;
        }
        
        .filter-grid {
            grid-template-columns: 1fr;
        }
        
        .data-table {
            font-size: 0.75rem;
        }
        
        .data-table th,
        .data-table td {
            padding: 0.75rem;
        }

        .analytics-section {
            grid-template-columns: 1fr;
        }

        .priority-breakdown {
            grid-template-columns: 1fr;
        }
    }

    /* Enhanced Alert Animations */
    @keyframes pulse {
        0% { transform: scale(1); opacity: 1; }
        50% { transform: scale(1.05); opacity: 0.8; }
        100% { transform: scale(1); opacity: 1; }
    }

    @keyframes blink {
        0%, 50% { opacity: 1; }
        51%, 100% { opacity: 0.3; }
    }

    .alert-badge.critical {
        animation: pulse 2s infinite;
        box-shadow: 0 0 20px rgba(239, 68, 68, 0.5);
    }

    .alert-badge.high {
        animation: blink 3s infinite;
    }

    /* Product-specific styling */
    .product-info {
        text-align: center;
    }

    .repayment-method-info {
        text-align: center;
    }

    .payment-schedule-info {
        text-align: center;
    }

    .days-until-due-info {
        text-align: center;
    }

    .priority-container {
        text-align: center;
        min-width: 120px;
    }
</style>
{% endblock %}

{% block content %}
<div class="main-container">
    <!-- Page Header -->
    <div class="page-header">
        <h1 class="page-title">
            <i class="fas fa-calendar-check"></i>
            Loans Due Dashboard
        </h1>
        <p class="page-subtitle">Track upcoming loan payments and analyze due date patterns</p>
    </div>

    <!-- Summary Metrics -->
    <div class="metrics-grid">
        <div class="metric-card info">
            <div class="metric-icon">
                <i class="fas fa-calendar-check"></i>
            </div>
            <div class="metric-value">{{ report_data.summary.total_loans_due|intcomma }}</div>
            <div class="metric-label">Total Loans Due</div>
        </div>
        
        <div class="metric-card warning">
            <div class="metric-icon">
                <span>$</span>
            </div>
            <div class="metric-value">KSh {{ report_data.summary.total_amount_due|intcomma }}</div>
            <div class="metric-label">Total Amount Due</div>
        </div>
        
        <div class="metric-card success">
            <div class="metric-icon">
                <span>📈</span>
            </div>
            <div class="metric-value">KSh {{ report_data.summary.average_due_amount|intcomma }}</div>
            <div class="metric-label">Average Due Amount</div>
        </div>
        
        <div class="metric-card danger">
            <div class="metric-icon">
                <span>⚠️</span>
            </div>
            <div class="metric-value">{{ report_data.priority_breakdown.overdue_count|intcomma }}</div>
            <div class="metric-label">Overdue Loans</div>
        </div>
    </div>

    <!-- Analytics Section -->
    <div class="analytics-section">
        <!-- Priority Breakdown Chart -->
        <div class="chart-container">
            <div class="chart-header">
                <h3 class="chart-title">Priority Distribution</h3>
                <p class="chart-subtitle">Breakdown by urgency level</p>
            </div>
            <canvas id="priorityChart" class="chart-canvas"></canvas>
            <div class="priority-breakdown">
                <div class="priority-item">
                    <div class="priority-item-label">Overdue</div>
                    <div class="priority-item-value" style="color: #dc2626;">{{ report_data.priority_breakdown.overdue_count|default:0 }}</div>
                </div>
                <div class="priority-item">
                    <div class="priority-item-label">Due Today</div>
                    <div class="priority-item-value" style="color: #d97706;">{{ report_data.priority_breakdown.due_today_count|default:0 }}</div>
                </div>
                <div class="priority-item">
                    <div class="priority-item-label">Due This Week</div>
                    <div class="priority-item-value" style="color: #1e40af;">{{ report_data.priority_breakdown.due_this_week_count|default:0 }}</div>
                </div>
                <div class="priority-item">
                    <div class="priority-item-label">Due Later</div>
                    <div class="priority-item-value" style="color: #059669;">{{ report_data.priority_breakdown.due_later_count|default:0 }}</div>
                </div>
            </div>
        </div>

        <!-- Repayment Method Distribution -->
        <div class="chart-container">
            <div class="chart-header">
                <h3 class="chart-title">Repayment Methods</h3>
                <p class="chart-subtitle">Distribution by payment frequency</p>
            </div>
            <canvas id="repaymentChart" class="chart-canvas"></canvas>
        </div>
    </div>

    <!-- Filters -->
    <div class="filter-section">
        <h3 class="filter-title">
            <span>🔍</span>
            Filter & Search
        </h3>
        <form method="GET" class="filter-grid">
            <div class="filter-group">
                <label class="filter-label">Priority Level</label>
                <select name="priority_filter" class="filter-select">
                    <option value="">All Priorities</option>
                    <option value="overdue" {% if request.GET.priority_filter == 'overdue' %}selected{% endif %}>Overdue</option>
                    <option value="due_today" {% if request.GET.priority_filter == 'due_today' %}selected{% endif %}>Due Today</option>
                    <option value="due_this_week" {% if request.GET.priority_filter == 'due_this_week' %}selected{% endif %}>Due This Week</option>
                    <option value="due_later" {% if request.GET.priority_filter == 'due_later' %}selected{% endif %}>Due Later</option>
                </select>
            </div>
            
            <div class="filter-group">
                <label class="filter-label">Sort By</label>
                <select name="sort_by" class="filter-select">
                    <option value="due_date_asc" {% if request.GET.sort_by == 'due_date_asc' %}selected{% endif %}>Due Date (Earliest First)</option>
                    <option value="due_date_desc" {% if request.GET.sort_by == 'due_date_desc' %}selected{% endif %}>Due Date (Latest First)</option>
                    <option value="amount_desc" {% if request.GET.sort_by == 'amount_desc' %}selected{% endif %}>Amount (High to Low)</option>
                    <option value="amount_asc" {% if request.GET.sort_by == 'amount_asc' %}selected{% endif %}>Amount (Low to High)</option>
                </select>
            </div>
            
            <div class="filter-group">
                <label class="filter-label">Start Date</label>
                <input type="date" name="start_date" class="filter-input" value="{{ request.GET.start_date }}">
            </div>
            
            <div class="filter-group">
                <label class="filter-label">End Date</label>
                <input type="date" name="end_date" class="filter-input" value="{{ request.GET.end_date }}">
            </div>
            
            <div class="filter-group">
                <button type="submit" class="action-btn primary" style="width: 100%; padding: 0.875rem;">
                    <span>🔍</span>
                    Apply Filters
                </button>
            </div>
        </form>
    </div>

    <!-- Export Buttons -->
    <div class="export-buttons">
        <a href="?export=excel" class="export-btn excel">
            <span>📊</span>
            Export to Excel
        </a>
        <a href="?export=pdf" class="export-btn pdf">
            <span>📄</span>
            Export to PDF
        </a>
    </div>

    <!-- Data Table -->
    <div class="data-table-container">
        <div class="table-header">
            <div>
                <h3 class="table-title">Due Date Details</h3>
                <p class="table-subtitle">{{ report_data.loans|length }} loan{{ report_data.loans|length|pluralize }} found</p>
            </div>
        </div>
        
        {% if report_data.loans %}
        <table class="data-table">
                    <thead>
                        <tr>
                            <th>Loan Details</th>
                            <th>Product</th>
                            <th>Repayment Method</th>
                            <th>Payment Schedule</th>
                            <th>Expected Payment</th>
                            <th>Outstanding Balance</th>
                            <th>Days Until Due</th>
                            <th>Priority</th>
                            <th>Last Payment</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
            <tbody>
                {% for loan in report_data.loans %}
                <tr>
                    <td>
                        <div style="font-weight: 700; color: #111827; margin-bottom: 0.25rem;">{{ loan.loan_number }}</div>
                        <div style="font-size: 0.875rem; color: #6b7280;">{{ loan.borrower_name }}</div>
                        <div style="font-size: 0.875rem; color: #6b7280;">{{ loan.borrower_phone }}</div>
                        <div style="font-size: 0.875rem; color: #9ca3af; margin-top: 0.25rem;">Due: {{ loan.due_date|date:"M d, Y" }}</div>
                    </td>
                    <td style="text-align: center;">
                        <div class="product-info">
                            <span class="product-badge product-{{ loan.product_type|default:'unknown' }}" 
                                  style="display: block; margin-bottom: 0.25rem; padding: 0.3rem 0.6rem; border-radius: 8px; font-size: 0.7rem; font-weight: 700;"
                                  title="{{ loan.loan_product|default:'Unknown' }}">
                                {{ loan.loan_product|default:'Unknown' }}
                            </span>
                            <div style="font-size: 0.7rem; color: #6b7280; font-weight: 500;">
                                {% if loan.product_type == 'boost' %}
                                    <span>⚡</span> 1 Month
                                {% elif loan.product_type == 'boost_plus' %}
                                    <i class="fas fa-rocket" style="color: #f59e0b;"></i> 2 Months
                                {% elif loan.product_type == 'mwamba' %}
                                    <i class="fas fa-mountain" style="color: #3b82f6;"></i> 3 Months
                                {% elif loan.product_type == 'imara' %}
                                    <i class="fas fa-shield-alt" style="color: #8b5cf6;"></i> 6 Months
                                {% endif %}
                            </div>
                        </div>
                    </td>
                    <td style="text-align: center;">
                        <div class="repayment-method-info">
                            <span class="priority-badge" 
                                  style="background: {% if loan.repayment_method == 'daily' %}#dcfce7{% elif loan.repayment_method == 'weekly' %}#fef3c7{% else %}#dbeafe{% endif %}; 
                                         color: {% if loan.repayment_method == 'daily' %}#166534{% elif loan.repayment_method == 'weekly' %}#92400e{% else %}#1e40af{% endif %}; 
                                         padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem;"
                                  title="Repayment frequency">
                                {{ loan.repayment_method|default:'Monthly'|title }}
                            </span>
                            <div style="font-size: 0.7rem; color: #6b7280; font-weight: 500;">
                                {% if loan.repayment_method == 'daily' %}
                                    <i class="fas fa-calendar-day" style="color: #10b981;"></i> Every Day
                                {% elif loan.repayment_method == 'weekly' %}
                                    <i class="fas fa-calendar-week" style="color: #f59e0b;"></i> Every Week
                                {% else %}
                                    <span>📅</span> Every Month
                                {% endif %}
                            </div>
                        </div>
                    </td>
                    <td style="text-align: center;">
                        <div class="payment-schedule-info" style="padding: 0.5rem; background: rgba(99, 102, 241, 0.05); border-radius: 8px; border: 1px solid rgba(99, 102, 241, 0.1);">
                            <div style="font-size: 0.75rem; font-weight: 600; color: #374151; margin-bottom: 0.25rem;">
                                {% if loan.repayment_method == 'daily' %}
                                    Daily: KES {{ loan.expected_payment_amount|floatformat:0 }}
                                {% elif loan.repayment_method == 'weekly' %}
                                    Weekly: KES {{ loan.expected_payment_amount|floatformat:0 }}
                                {% else %}
                                    Monthly: KES {{ loan.expected_payment_amount|floatformat:0 }}
                                {% endif %}
                            </div>
                            <div style="font-size: 0.7rem; color: #6b7280;">
                                {% if loan.repayment_method == 'daily' %}
                                    <span>⏰</span> Due Every Day
                                {% elif loan.repayment_method == 'weekly' %}
                                    <span>⏰</span> Due Every 7 Days
                                {% else %}
                                    <span>⏰</span> Due Every 30 Days
                                {% endif %}
                            </div>
                        </div>
                    </td>
                    <td class="amount-cell" style="color: #6366f1; font-weight: 700;">
                        KSh {{ loan.expected_payment_amount|floatformat:0|intcomma }}
                    </td>
                    <td class="amount-cell" style="color: #1f2937; font-weight: 600;">
                        KSh {{ loan.outstanding_balance|floatformat:0|intcomma }}
                    </td>
                    <td style="text-align: center;">
                        <div class="days-until-due-info">
                            <span class="days-until-due {{ loan.priority|default:'due-later' }}" style="display: block; margin-bottom: 0.25rem;">
                                {% if loan.days_until_due < 0 %}
                                    {{ loan.days_until_due|abs }} days overdue
                                {% elif loan.days_until_due == 0 %}
                                    Due today
                                {% else %}
                                    {{ loan.days_until_due }} days
                                {% endif %}
                            </span>
                            <div style="font-size: 0.7rem; color: #6b7280;">
                                {% if loan.repayment_method == 'daily' %}
                                    {% if loan.days_until_due == 0 %}
                                        <span>⚠️</span> Due Today!
                                    {% elif loan.days_until_due <= 1 %}
                                        <span>⚠️</span> Due Tomorrow
                                    {% else %}
                                        <i class="fas fa-calendar-day" style="color: #10b981;"></i> Daily Payment
                                    {% endif %}
                                {% elif loan.repayment_method == 'weekly' %}
                                    {% if loan.days_until_due == 0 %}
                                        <span>⚠️</span> Due Today!
                                    {% elif loan.days_until_due <= 3 %}
                                        <span>⚠️</span> Due Soon
                                    {% else %}
                                        <i class="fas fa-calendar-week" style="color: #f59e0b;"></i> Weekly Payment
                                    {% endif %}
                                {% else %}
                                    {% if loan.days_until_due == 0 %}
                                        <span>⚠️</span> Due Today!
                                    {% elif loan.days_until_due <= 7 %}
                                        <span>⚠️</span> Due This Week
                                    {% else %}
                                        <span>📅</span> Monthly Payment
                                    {% endif %}
                                {% endif %}
                            </div>
                        </div>
                    </td>
                    <td style="text-align: center;">
                        <div class="priority-container">
                            {% if loan.repayment_method == 'daily' %}
                                {% if loan.days_until_due == 0 %}
                                    <span class="priority-badge critical" style="background: #ef4444; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem; animation: pulse 2s infinite;">
                                        <span>🔥</span> CRITICAL
                                    </span>
                                    <div style="font-size: 0.7rem; color: #ef4444; font-weight: 600;">
                                        Daily Payment Due!
                                    </div>
                                {% elif loan.days_until_due <= 1 %}
                                    <span class="priority-badge high" style="background: #f59e0b; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem;">
                                        <span>⚠️</span> HIGH
                                    </span>
                                    <div style="font-size: 0.7rem; color: #f59e0b; font-weight: 600;">
                                        Daily Payment Soon
                                    </div>
                                {% else %}
                                    <span class="priority-badge medium" style="background: #3b82f6; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem;">
                                        <i class="fas fa-calendar-day"></i> DAILY
                                    </span>
                                    <div style="font-size: 0.7rem; color: #3b82f6; font-weight: 600;">
                                        Daily Schedule
                                    </div>
                                {% endif %}
                            {% elif loan.repayment_method == 'weekly' %}
                                {% if loan.days_until_due == 0 %}
                                    <span class="priority-badge critical" style="background: #ef4444; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem; animation: pulse 2s infinite;">
                                        <span>🔥</span> CRITICAL
                                    </span>
                                    <div style="font-size: 0.7rem; color: #ef4444; font-weight: 600;">
                                        Weekly Payment Due!
                                    </div>
                                {% elif loan.days_until_due <= 3 %}
                                    <span class="priority-badge high" style="background: #f59e0b; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem;">
                                        <span>⚠️</span> HIGH
                                    </span>
                                    <div style="font-size: 0.7rem; color: #f59e0b; font-weight: 600;">
                                        Weekly Payment Soon
                                    </div>
                                {% else %}
                                    <span class="priority-badge medium" style="background: #3b82f6; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem;">
                                        <i class="fas fa-calendar-week"></i> WEEKLY
                                    </span>
                                    <div style="font-size: 0.7rem; color: #3b82f6; font-weight: 600;">
                                        Weekly Schedule
                                    </div>
                                {% endif %}
                            {% else %}
                                {% if loan.days_until_due == 0 %}
                                    <span class="priority-badge critical" style="background: #ef4444; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem; animation: pulse 2s infinite;">
                                        <span>🔥</span> CRITICAL
                                    </span>
                                    <div style="font-size: 0.7rem; color: #ef4444; font-weight: 600;">
                                        Monthly Payment Due!
                                    </div>
                                {% elif loan.days_until_due <= 7 %}
                                    <span class="priority-badge high" style="background: #f59e0b; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem;">
                                        <span>⚠️</span> HIGH
                                    </span>
                                    <div style="font-size: 0.7rem; color: #f59e0b; font-weight: 600;">
                                        Monthly Payment Soon
                                    </div>
                                {% else %}
                                    <span class="priority-badge medium" style="background: #3b82f6; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem;">
                                        <span>📅</span> MONTHLY
                                    </span>
                                    <div style="font-size: 0.7rem; color: #3b82f6; font-weight: 600;">
                                        Monthly Schedule
                                    </div>
                                {% endif %}
                            {% endif %}
                        </div>
                    </td>
                    <td>
                        {% if loan.last_payment_date %}
                        <div style="font-size: 0.875rem; color: #111827; font-weight: 600;">{{ loan.last_payment_date|date:"M d, Y" }}</div>
                        <div style="font-size: 0.875rem; color: #6b7280;">KSh {{ loan.last_payment_amount|floatformat:0|intcomma }}</div>
                        {% else %}
                        <span style="font-size: 0.875rem; color: #9ca3af;">No payments</span>
                        {% endif %}
                    </td>
                    <td>
                        <div style="display: flex; justify-content: center; gap: 0.5rem;">
                            <button onclick="contactBorrower('{{ loan.id }}')" class="action-btn primary" title="Contact">
                                <span>📞</span>
                            </button>
                            <button onclick="schedulePayment('{{ loan.id }}')" class="action-btn success" title="Schedule Payment">
                                <i class="fas fa-calendar-plus"></i>
                            </button>
                            <button onclick="viewDetails('{{ loan.id }}')" class="action-btn warning" title="View Details">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        {% else %}
        <div class="no-data">
            <div class="no-data-icon">
                <i class="fas fa-calendar-check"></i>
            </div>
            <h3 style="font-size: 1.5rem; margin-bottom: 0.5rem; color: #374151;">No Loans Due</h3>
            <p style="font-size: 1rem;">No loans are due in the selected period.</p>
        </div>
        {% endif %}
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<script>
// Priority Distribution Chart
const priorityCtx = document.getElementById('priorityChart');
if (priorityCtx) {
    new Chart(priorityCtx, {
        type: 'doughnut',
        data: {
            labels: ['Overdue', 'Due Today', 'Due This Week', 'Due Later'],
            datasets: [{
                data: [
                    {{ report_data.priority_breakdown.overdue_count|default:0 }},
                    {{ report_data.priority_breakdown.due_today_count|default:0 }},
                    {{ report_data.priority_breakdown.due_this_week_count|default:0 }},
                    {{ report_data.priority_breakdown.due_later_count|default:0 }}
                ],
                backgroundColor: [
                    '#ef4444',
                    '#f59e0b',
                    '#3b82f6',
                    '#10b981'
                ],
                borderWidth: 0,
                hoverOffset: 8
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        padding: 15,
                        font: {
                            size: 12,
                            weight: '600'
                        },
                        usePointStyle: true,
                        pointStyle: 'circle'
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    padding: 12,
                    titleFont: {
                        size: 14,
                        weight: 'bold'
                    },
                    bodyFont: {
                        size: 13
                    },
                    borderColor: 'rgba(255, 255, 255, 0.1)',
                    borderWidth: 1
                }
            }
        }
    });
}

// Repayment Method Distribution Chart
const repaymentCtx = document.getElementById('repaymentChart');
if (repaymentCtx) {
    // Calculate repayment method counts from loans
    const repaymentCounts = {
        daily: 0,
        weekly: 0,
        monthly: 0
    };
    
    {% for loan in report_data.loans %}
        const method = '{{ loan.repayment_method|default:"monthly" }}'.toLowerCase();
        if (repaymentCounts.hasOwnProperty(method)) {
            repaymentCounts[method]++;
        } else {
            repaymentCounts.monthly++;
        }
    {% endfor %}
    
    new Chart(repaymentCtx, {
        type: 'bar',
        data: {
            labels: ['Daily', 'Weekly', 'Monthly'],
            datasets: [{
                label: 'Number of Loans',
                data: [
                    repaymentCounts.daily,
                    repaymentCounts.weekly,
                    repaymentCounts.monthly
                ],
                backgroundColor: [
                    '#10b981',
                    '#f59e0b',
                    '#6366f1'
                ],
                borderRadius: 8,
                borderSkipped: false
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    padding: 12,
                    titleFont: {
                        size: 14,
                        weight: 'bold'
                    },
                    bodyFont: {
                        size: 13
                    },
                    borderColor: 'rgba(255, 255, 255, 0.1)',
                    borderWidth: 1
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1,
                        font: {
                            size: 11,
                            weight: '600'
                        },
                        color: '#6b7280'
                    },
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)',
                        drawBorder: false
                    }
                },
                x: {
                    ticks: {
                        font: {
                            size: 12,
                            weight: '600'
                        },
                        color: '#374151'
                    },
                    grid: {
                        display: false,
                        drawBorder: false
                    }
                }
            }
        }
    });
}

function contactBorrower(loanId) {
    alert('Contact borrower functionality will be implemented soon for loan: ' + loanId);
}

function schedulePayment(loanId) {
    alert('Schedule payment functionality will be implemented soon for loan: ' + loanId);
}

function viewDetails(loanId) {
    alert('View details functionality will be implemented soon for loan: ' + loanId);
}
</script>
{% endblock %}