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

{% block title %}Comprehensive Analytics Dashboard{% endblock %}

{% block extra_css %}
<style>
    .dashboard-card {
        background: white;
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        padding: 20px;
        margin-bottom: 20px;
        transition: transform 0.2s;
    }
    
    .dashboard-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    }
    
    .metric-card {
        text-align: center;
        padding: 15px;
        border-radius: 8px;
        color: white;
        margin-bottom: 15px;
    }
    
    .metric-card.primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
    .metric-card.success { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
    .metric-card.warning { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
    .metric-card.danger { background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%); }
    .metric-card.info { background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); }
    .metric-card.boost { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
    .metric-card.imara { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
    .metric-card.mwamba { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
    .metric-card.boost_plus { background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); }
    
    .metric-value {
        font-size: 2rem;
        font-weight: bold;
        margin-bottom: 5px;
    }
    
    .metric-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }
    
    .product-breakdown {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 15px;
        margin-bottom: 20px;
    }
    
    .product-card {
        background: white;
        border: 1px solid #e9ecef;
        border-radius: 8px;
        padding: 15px;
        transition: all 0.3s;
    }
    
    .product-card:hover {
        border-color: #667eea;
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
    }
    
    .product-header {
        display: flex;
        justify-content: between;
        align-items: center;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #f8f9fa;
    }
    
    .product-name {
        font-weight: 600;
        color: #2c3e50;
        text-transform: capitalize;
    }
    
    .product-metrics {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 10px;
    }
    
    .mini-metric {
        text-align: center;
        padding: 8px;
        background: #f8f9fa;
        border-radius: 5px;
    }
    
    .mini-metric-value {
        font-size: 1.1rem;
        font-weight: bold;
        color: #2c3e50;
    }
    
    .mini-metric-label {
        font-size: 0.75rem;
        color: #6c757d;
        margin-top: 2px;
    }
    
    .summary-stats {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 15px;
        margin-bottom: 20px;
    }
    
    .collection-breakdown {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        margin-top: 15px;
    }
    
    .collection-item {
        display: flex;
        justify-content: between;
        align-items: center;
        padding: 8px 0;
        border-bottom: 1px solid #e9ecef;
    }
    
    .collection-item:last-child {
        border-bottom: none;
    }
    
    .collection-product {
        font-weight: 500;
        text-transform: capitalize;
    }
    
    .collection-rate {
        font-weight: bold;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 0.85rem;
    }
    
    .rate-excellent { background: #d4edda; color: #155724; }
    .rate-good { background: #d1ecf1; color: #0c5460; }
    .rate-fair { background: #fff3cd; color: #856404; }
    .rate-poor { background: #f8d7da; color: #721c24; }
    
    .outstanding-breakdown {
        margin-top: 15px;
    }
    
    .outstanding-item {
        display: flex;
        justify-content: between;
        align-items: center;
        padding: 10px;
        margin-bottom: 8px;
        background: white;
        border-radius: 6px;
        border-left: 4px solid #667eea;
    }
    
    .tabs-container {
        margin-bottom: 20px;
    }
    
    .nav-tabs .nav-link {
        border: none;
        color: #6c757d;
        font-weight: 500;
    }
    
    .nav-tabs .nav-link.active {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 5px 5px 0 0;
    }
    
    .tab-content {
        background: white;
        border-radius: 0 8px 8px 8px;
        padding: 20px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- Page Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="h3 mb-0">Comprehensive Analytics Dashboard</h1>
                    <p class="text-muted">Detailed analytics with product breakdowns and comprehensive metrics</p>
                </div>
                <div>
                    <span class="badge badge-info">Last Updated: {{ dashboard_data.generated_at|date:"M d, Y H:i" }}</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Enhanced Summary Metrics -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="dashboard-card">
                <h5 class="mb-3">Portfolio Overview</h5>
                <div class="summary-stats">
                    <div class="metric-card primary">
                        <div class="metric-value">{{ dashboard_data.summary_metrics.total_active_loans|floatformat:0 }}</div>
                        <div class="metric-label">Total Loans</div>
                    </div>
                    <div class="metric-card success">
                        <div class="metric-value">KES {{ dashboard_data.summary_metrics.avg_loan_amount|floatformat:0|intcomma }}</div>
                        <div class="metric-label">Average Amount</div>
                    </div>
                    <div class="metric-card info">
                        <div class="metric-value">{{ dashboard_data.summary_metrics.total_active_loans|floatformat:0 }}</div>
                        <div class="metric-label">Active Loans</div>
                    </div>
                    <div class="metric-card warning">
                        <div class="metric-value">{{ dashboard_data.summary_metrics.overdue_loans|floatformat:0 }}</div>
                        <div class="metric-label">Overdue</div>
                    </div>
                    <div class="metric-card success">
                        <div class="metric-value">KES {{ dashboard_data.summary_metrics.total_disbursed|floatformat:0|intcomma }}</div>
                        <div class="metric-label">Total Disbursed</div>
                    </div>
                    <div class="metric-card danger">
                        <div class="metric-value">{{ dashboard_data.summary_metrics.default_rate|floatformat:1 }}%</div>
                        <div class="metric-label">Default Rate</div>
                    </div>
                    <div class="metric-card info">
                        <div class="metric-value">KES {{ dashboard_data.summary_metrics.total_collected|floatformat:0|intcomma }}</div>
                        <div class="metric-label">Total Collected</div>
                    </div>
                    <div class="metric-card primary">
                        <div class="metric-value">{{ dashboard_data.summary_metrics.collection_rate|floatformat:1 }}%</div>
                        <div class="metric-label">Collection Rate</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Product Breakdown Section -->
    {% if dashboard_data.summary_metrics.product_breakdown %}
    <div class="row mb-4">
        <div class="col-12">
            <div class="dashboard-card">
                <h5 class="mb-3">
                    <span>📊</span>
                    Loan Products Breakdown
                </h5>
                <div class="product-breakdown">
                    {% for product in dashboard_data.summary_metrics.product_breakdown %}
                    <div class="product-card">
                        <div class="product-header">
                            <div class="product-name">{{ product.application__loan_product__product_type|title }}</div>
                            <span class="badge badge-primary">{{ product.count }} loans</span>
                        </div>
                        <div class="product-metrics">
                            <div class="mini-metric">
                                <div class="mini-metric-value">KES {{ product.total_amount|floatformat:0|intcomma }}</div>
                                <div class="mini-metric-label">Total Amount</div>
                            </div>
                            <div class="mini-metric">
                                <div class="mini-metric-value">KES {{ product.avg_amount|floatformat:0|intcomma }}</div>
                                <div class="mini-metric-label">Avg Amount</div>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
    {% endif %}

    <!-- Collection Rates by Product -->
    {% if dashboard_data.summary_metrics.collection_by_product %}
    <div class="row mb-4">
        <div class="col-12">
            <div class="dashboard-card">
                <h5 class="mb-3">
                    <span>💳</span>
                    Collection Performance by Product
                </h5>
                <div class="collection-breakdown">
                    {% for product_type, data in dashboard_data.summary_metrics.collection_by_product.items %}
                    <div class="collection-item">
                        <div class="collection-product">{{ product_type|title }} - {{ data.product_name }}</div>
                        <div>
                            <span class="collection-rate {% if data.collection_rate >= 90 %}rate-excellent{% elif data.collection_rate >= 75 %}rate-good{% elif data.collection_rate >= 50 %}rate-fair{% else %}rate-poor{% endif %}">
                                {{ data.collection_rate }}%
                            </span>
                            <small class="text-muted ml-2">
                                KES {{ data.collected_amount|floatformat:0|intcomma }} / KES {{ data.disbursed_amount|floatformat:0|intcomma }}
                            </small>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
    {% endif %}

    <!-- Outstanding Loans by Product -->
    {% if dashboard_data.summary_metrics.outstanding_by_product %}
    <div class="row mb-4">
        <div class="col-12">
            <div class="dashboard-card">
                <h5 class="mb-3">
                    <span>⚠️</span>
                    Outstanding Loans by Product
                </h5>
                <div class="outstanding-breakdown">
                    {% for product in dashboard_data.summary_metrics.outstanding_by_product %}
                    <div class="outstanding-item">
                        <div>
                            <strong>{{ product.product_type|title }}</strong>
                            <br>
                            <small class="text-muted">{{ product.count }} loans</small>
                        </div>
                        <div class="text-right">
                            <strong>KES {{ product.outstanding_amount|floatformat:0|intcomma }}</strong>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
    {% endif %}

    <!-- Comprehensive Product Analytics -->
    {% if dashboard_data.comprehensive_analytics %}
    <div class="row mb-4">
        <div class="col-12">
            <div class="dashboard-card">
                <h5 class="mb-3">
                    <span>📊</span>
                    Comprehensive Product Analytics
                </h5>
                
                <div class="tabs-container">
                    <ul class="nav nav-tabs" id="analyticsTab" role="tablist">
                        {% for product_type, analytics in dashboard_data.comprehensive_analytics.product_analytics.items %}
                        <li class="nav-item" role="presentation">
                            <a class="nav-link {% if forloop.first %}active{% endif %}" 
                               id="{{ product_type }}-tab" 
                               data-toggle="tab" 
                               href="#{{ product_type }}" 
                               role="tab">
                                {{ product_type|title }}
                            </a>
                        </li>
                        {% endfor %}
                    </ul>
                    
                    <div class="tab-content" id="analyticsTabContent">
                        {% for product_type, analytics in dashboard_data.comprehensive_analytics.product_analytics.items %}
                        <div class="tab-pane fade {% if forloop.first %}show active{% endif %}" 
                             id="{{ product_type }}" 
                             role="tabpanel">
                            
                            <!-- Product Summary -->
                            <div class="row mb-3">
                                <div class="col-md-3">
                                    <div class="mini-metric">
                                        <div class="mini-metric-value">{{ analytics.active_loans.count }}</div>
                                        <div class="mini-metric-label">Active Loans</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="mini-metric">
                                        <div class="mini-metric-value">KES {{ analytics.active_loans.total_amount|floatformat:0|intcomma }}</div>
                                        <div class="mini-metric-label">Portfolio Value</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="mini-metric">
                                        <div class="mini-metric-value">{{ analytics.collection_metrics.collection_rate }}%</div>
                                        <div class="mini-metric-label">Collection Rate</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="mini-metric">
                                        <div class="mini-metric-value">{{ analytics.risk_metrics.default_rate }}%</div>
                                        <div class="mini-metric-label">Default Rate</div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Detailed Metrics -->
                            <div class="row">
                                <div class="col-md-6">
                                    <h6>Collection Metrics</h6>
                                    <ul class="list-unstyled">
                                        <li><strong>Collected:</strong> KES {{ analytics.collection_metrics.collected_amount|floatformat:0|intcomma }}</li>
                                        <li><strong>Outstanding:</strong> KES {{ analytics.collection_metrics.outstanding_amount|floatformat:0|intcomma }}</li>
                                        <li><strong>Disbursed:</strong> KES {{ analytics.collection_metrics.disbursed_amount|floatformat:0|intcomma }}</li>
                                    </ul>
                                </div>
                                <div class="col-md-6">
                                    <h6>Risk Metrics</h6>
                                    <ul class="list-unstyled">
                                        <li><strong>Due Today:</strong> {{ analytics.risk_metrics.due_today }} loans</li>
                                        <li><strong>Overdue:</strong> {{ analytics.risk_metrics.overdue }} loans</li>
                                        <li><strong>Defaulted:</strong> {{ analytics.risk_metrics.defaulted_count }} loans</li>
                                    </ul>
                                </div>
                            </div>
                            
                            <!-- Revenue Metrics -->
                            <div class="row mt-3">
                                <div class="col-12">
                                    <h6>Revenue Metrics (Current Month)</h6>
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="mini-metric">
                                                <div class="mini-metric-value">KES {{ analytics.revenue_metrics.monthly_processing_fees|floatformat:0|intcomma }}</div>
                                                <div class="mini-metric-label">Processing Fees</div>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="mini-metric">
                                                <div class="mini-metric-value">KES {{ analytics.revenue_metrics.monthly_interest|floatformat:0|intcomma }}</div>
                                                <div class="mini-metric-label">Interest Income</div>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="mini-metric">
                                                <div class="mini-metric-value">KES {{ analytics.revenue_metrics.total_monthly_revenue|floatformat:0|intcomma }}</div>
                                                <div class="mini-metric-label">Total Revenue</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% endif %}

    <!-- Due Today and Overdue by Product -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="dashboard-card">
                <h5 class="mb-3">
                    <i class="fas fa-calendar-day text-danger mr-2"></i>
                    Due Today by Product
                </h5>
                {% if dashboard_data.summary_metrics.due_today_by_product %}
                    {% for product in dashboard_data.summary_metrics.due_today_by_product %}
                    {% if product.due_today_count > 0 %}
                    <div class="collection-item">
                        <div class="collection-product">{{ product.product_type|title }}</div>
                        <span class="badge badge-danger">{{ product.due_today_count }} loans</span>
                    </div>
                    {% endif %}
                    {% endfor %}
                {% else %}
                <div class="text-center text-muted py-3">
                    <span>✓</span>
                    <p>No loans due today</p>
                </div>
                {% endif %}
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="dashboard-card">
                <h5 class="mb-3">
                    <span>⚠️</span>
                    Overdue by Product
                </h5>
                {% if dashboard_data.summary_metrics.overdue_by_product %}
                    {% for product in dashboard_data.summary_metrics.overdue_by_product %}
                    {% if product.overdue_count > 0 %}
                    <div class="collection-item">
                        <div class="collection-product">{{ product.product_type|title }}</div>
                        <span class="badge badge-warning">{{ product.overdue_count }} loans</span>
                    </div>
                    {% endif %}
                    {% endfor %}
                {% else %}
                <div class="text-center text-muted py-3">
                    <span>✓</span>
                    <p>No overdue loans</p>
                </div>
                {% endif %}
            </div>
        </div>
    </div>

    <!-- Processing Fees and Interest Breakdown -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="dashboard-card">
                <h5 class="mb-3">
                    <span>🪙</span>
                    Processing Fees by Product
                </h5>
                {% if dashboard_data.processing_fees_current_month.product_breakdown %}
                    {% for product in dashboard_data.processing_fees_current_month.product_breakdown %}
                    <div class="collection-item">
                        <div>
                            <div class="collection-product">{{ product.application__loan_product__product_type|title }}</div>
                            <small class="text-muted">{{ product.loan_count }} loans</small>
                        </div>
                        <div class="text-right">
                            <strong>KES {{ product.total_fees|floatformat:0|intcomma }}</strong>
                            <br>
                            <small class="text-muted">{{ product.percentage_of_total_fees|floatformat:1 }}%</small>
                        </div>
                    </div>
                    {% endfor %}
                {% endif %}
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="dashboard-card">
                <h5 class="mb-3">
                    <i class="fas fa-percentage text-primary mr-2"></i>
                    Interest Income by Product
                </h5>
                {% if dashboard_data.interest_income_current_month.product_breakdown %}
                    {% for product in dashboard_data.interest_income_current_month.product_breakdown %}
                    <div class="collection-item">
                        <div>
                            <div class="collection-product">{{ product.application__loan_product__product_type|title }}</div>
                            <small class="text-muted">{{ product.loan_count }} loans</small>
                        </div>
                        <div class="text-right">
                            <strong>KES {{ product.total_interest|floatformat:0|intcomma }}</strong>
                            <br>
                            <small class="text-muted">{{ product.percentage_of_total_interest|floatformat:1 }}%</small>
                        </div>
                    </div>
                    {% endfor %}
                {% endif %}
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="row">
        <div class="col-12">
            <div class="dashboard-card">
                <h5 class="mb-3">Quick Actions</h5>
                <div class="row">
                    <div class="col-md-3 mb-2">
                        <a href="{% url 'reports:enhanced_loans_due_report' %}" class="btn btn-outline-primary btn-block">
                            <i class="fas fa-calendar-check"></i> View All Due Loans
                        </a>
                    </div>
                    <div class="col-md-3 mb-2">
                        <a href="{% url 'reports:delinquent_loans_report' %}" class="btn btn-outline-warning btn-block">
                            <span>⚠️</span> Delinquent Loans
                        </a>
                    </div>
                    <div class="col-md-3 mb-2">
                        <a href="{% url 'reports:disbursed_loans_report' %}" class="btn btn-outline-primary btn-block">
                            <span>📊</span> Disbursed Loans
                        </a>
                    </div>
                    <div class="col-md-3 mb-2">
                        <a href="{% url 'reports:processing_fees_report' %}" class="btn btn-outline-success btn-block">
                            <span>🪙</span> Processing Fees Report
                        </a>
                    </div>
                    <div class="col-md-3 mb-2">
                        <a href="{% url 'reports:interest_income_report' %}" class="btn btn-outline-info btn-block">
                            <i class="fas fa-percentage"></i> Interest Income Report
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // Initialize tabs
    $('#analyticsTab a').on('click', function (e) {
        e.preventDefault();
        $(this).tab('show');
    });
    
    // Auto-refresh dashboard every 10 minutes
    setInterval(function() {
        location.reload();
    }, 600000);
    
    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();
    
    // Animate metric cards on load
    $('.metric-card').each(function(index) {
        $(this).delay(index * 100).animate({
            opacity: 1,
            transform: 'translateY(0)'
        }, 500);
    });
});
</script>
{% endblock %}