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

{% block title %}Interest Income Analytics - Enhanced Report{% endblock %}

{% block extra_css %}
<style>
.metric-card {
    background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    color: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.metric-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 25px rgba(59, 130, 246, 0.3);
}

.metric-card.success { background: linear-gradient(135deg, #10b981 0%, #059669 100%); }
.metric-card.warning { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); }
.metric-card.danger { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); }
.metric-card.info { background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%); }
.metric-card.purple { background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); }

.filter-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    border: 1px solid #e5e7eb;
}

.chart-container {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    border: 1px solid #e5e7eb;
    height: 400px;
}

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

.data-table th {
    background: #f9fafb;
    padding: 1rem;
    text-align: left;
    font-weight: 600;
    color: #374151;
    border-bottom: 1px solid #e5e7eb;
}

.data-table td {
    padding: 1rem;
    border-bottom: 1px solid #f3f4f6;
}

.data-table tr:hover {
    background: #f9fafb;
}

.clickable {
    cursor: pointer;
    transition: all 0.2s;
}

.clickable:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

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

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

.action-btn.primary { background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%); color: white; }
.action-btn.success { background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; }
.action-btn.warning { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white; }
.action-btn.danger { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); color: white; }

.interest-rate-badge {
    padding: 0.25rem 0.75rem;
    border-radius: 9999px;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

.rate-low { background-color: #dcfce7; color: #166534; }
.rate-medium { background-color: #fef3c7; color: #92400e; }
.rate-high { background-color: #fee2e2; color: #991b1b; }
</style>
{% endblock %}

{% block content %}
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6">
    <!-- Header Section -->
    <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-3xl font-bold text-gray-900 dark:text-white">
                    <i class="fas fa-percentage text-blue-500 mr-3"></i>
                    Interest Income Analytics
                </h1>
                <p class="text-gray-600 dark:text-gray-400 mt-2">
                    Comprehensive analysis of interest income and loan profitability
                </p>
            </div>
            <div class="flex gap-3">
                <a href="?export=excel{% if start_date %}&start_date={{ start_date|date:'Y-m-d' }}{% endif %}{% if end_date %}&end_date={{ end_date|date:'Y-m-d' }}{% endif %}{% if product_id %}&product_id={{ product_id }}{% endif %}{% if branch_id %}&branch_id={{ branch_id }}{% endif %}" class="action-btn success">
                    <span>📊</span>
                    Export Excel
                </a>
                <a href="?export=pdf{% if start_date %}&start_date={{ start_date|date:'Y-m-d' }}{% endif %}{% if end_date %}&end_date={{ end_date|date:'Y-m-d' }}{% endif %}{% if product_id %}&product_id={{ product_id }}{% endif %}{% if branch_id %}&branch_id={{ branch_id }}{% endif %}" class="action-btn danger">
                    <span>📄</span>
                    Export PDF
                </a>
                <a href="{% url 'reports:reports_dashboard' %}" class="action-btn primary">
                    <span>←</span>
                    Back to Dashboard
                </a>
            </div>
        </div>
    </div>

    <!-- Filters Section -->
    <div class="filter-card mb-8">
        <h3 class="text-lg font-semibold text-gray-900 mb-4">
            <span>🔍</span>
            Report Filters
        </h3>
        <form method="GET" class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Start Date</label>
                <input type="date" name="start_date" value="{{ start_date|date:'Y-m-d' }}" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">End Date</label>
                <input type="date" name="end_date" value="{{ end_date|date:'Y-m-d' }}" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Loan Product</label>
                <select name="product_id" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    <option value="">All Products</option>
                    {% for product in loan_products %}
                    <option value="{{ product.id }}" {% if product_id == product.id|stringformat:"s" %}selected{% endif %}>
                        {{ product.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Branch</label>
                <select name="branch_id" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    <option value="">All Branches</option>
                    {% for branch in branches %}
                    <option value="{{ branch.id }}" {% if branch_id == branch.id|stringformat:"s" %}selected{% endif %}>
                        {{ branch.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="flex items-end">
                <button type="submit" class="action-btn primary w-full">
                    <span>🔍</span>
                    Apply Filters
                </button>
            </div>
        </form>
    </div>

    <!-- Key Metrics Row -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-6 mb-8">
        <div class="metric-card success clickable" onclick="showTotalInterest()">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-xl font-bold mb-2">
                        KSh {{ report_data.summary.total_interest_income|default:0|floatformat:0|intcomma }}
                    </h3>
                    <p class="text-sm opacity-90">Total Interest Income</p>
                </div>
                <span>💵</span>
            </div>
        </div>

        <div class="metric-card info clickable" onclick="showInterestBearingLoans()">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-xl font-bold mb-2">
                        {{ report_data.summary.total_loans|default:0 }}
                    </h3>
                    <p class="text-sm opacity-90">Interest Bearing Loans</p>
                </div>
                <span>🧾</span>
            </div>
        </div>

        <div class="metric-card warning clickable" onclick="showAverageRate()">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-xl font-bold mb-2">
                        {{ report_data.summary.average_interest_rate|default:0|floatformat:1 }}%
                    </h3>
                    <p class="text-sm opacity-90">Average Interest Rate</p>
                </div>
                <i class="fas fa-percentage text-2xl opacity-75"></i>
            </div>
        </div>

        <div class="metric-card purple clickable" onclick="showYieldRate()">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-xl font-bold mb-2">
                        {{ report_data.summary.portfolio_yield|default:0|floatformat:1 }}%
                    </h3>
                    <p class="text-sm opacity-90">Portfolio Yield</p>
                </div>
                <span>📈</span>
            </div>
        </div>

        <div class="metric-card clickable" onclick="showProjectedIncome()">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-xl font-bold mb-2">
                        KSh {{ report_data.summary.projected_monthly_income|default:0|floatformat:0|intcomma }}
                    </h3>
                    <p class="text-sm opacity-90">Projected Monthly</p>
                </div>
                <i class="fas fa-crystal-ball text-2xl opacity-75"></i>
            </div>
        </div>
    </div>

    <!-- Interest Rate Distribution -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="metric-card success clickable" onclick="filterByRate('low')">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-lg font-semibold mb-2">
                        {{ report_data.rate_distribution.low_rate_count|default:0 }}
                    </h3>
                    <p class="text-sm opacity-90">Low Rate (< 15%)</p>
                    <p class="text-xs opacity-75">KSh {{ report_data.rate_distribution.low_rate_income|default:0|floatformat:0|intcomma }}</p>
                </div>
                <span>↓</span>
            </div>
        </div>

        <div class="metric-card warning clickable" onclick="filterByRate('medium')">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-lg font-semibold mb-2">
                        {{ report_data.rate_distribution.medium_rate_count|default:0 }}
                    </h3>
                    <p class="text-sm opacity-90">Medium Rate (15-25%)</p>
                    <p class="text-xs opacity-75">KSh {{ report_data.rate_distribution.medium_rate_income|default:0|floatformat:0|intcomma }}</p>
                </div>
                <span>−</span>
            </div>
        </div>

        <div class="metric-card danger clickable" onclick="filterByRate('high')">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-lg font-semibold mb-2">
                        {{ report_data.rate_distribution.high_rate_count|default:0 }}
                    </h3>
                    <p class="text-sm opacity-90">High Rate (> 25%)</p>
                    <p class="text-xs opacity-75">KSh {{ report_data.rate_distribution.high_rate_income|default:0|floatformat:0|intcomma }}</p>
                </div>
                <span>↑</span>
            </div>
        </div>

        <div class="metric-card info clickable" onclick="showCompoundInterest()">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-lg font-semibold mb-2">
                        {{ report_data.summary.compound_loans|default:0 }}
                    </h3>
                    <p class="text-sm opacity-90">Compound Interest</p>
                    <p class="text-xs opacity-75">KSh {{ report_data.summary.compound_income|default:0|floatformat:0|intcomma }}</p>
                </div>
                <i class="fas fa-layer-group text-2xl opacity-75"></i>
            </div>
        </div>
    </div>


    <!-- Detailed Interest Income Table -->
    <div class="data-table mb-8">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-900">
                <i class="fas fa-table text-blue-500 mr-2"></i>
                Detailed Interest Income Breakdown
            </h3>
        </div>
        
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr>
                        <th class="text-left">Loan Number</th>
                        <th class="text-left">Borrower</th>
                        <th class="text-left">Product Type</th>
                        <th class="text-right">Principal Amount</th>
                        <th class="text-center">Interest Rate</th>
                        <th class="text-right">Interest Earned</th>
                        <th class="text-right">Outstanding Interest</th>
                        <th class="text-left">Loan Term</th>
                        <th class="text-center">Status</th>
                        <th class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {% if report_data.loans %}
                        {% for loan in report_data.loans %}
                        <tr class="clickable" onclick="viewLoanDetails('{{ loan.id }}')">
                            <td class="font-medium text-blue-600">{{ loan.loan_number }}</td>
                            <td>
                                <div class="font-medium text-gray-900">{{ loan.borrower_name }}</div>
                                <div class="text-sm text-gray-500">{{ loan.borrower_phone }}</div>
                            </td>
                            <td>
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                    {{ loan.product_name|default:"Standard Loan" }}
                                </span>
                            </td>
                            <td class="text-right font-medium">
                                KSh {{ loan.principal_amount|floatformat:0|intcomma }}
                            </td>
                            <td class="text-center">
                                <span class="interest-rate-badge {% if loan.interest_rate < 15 %}rate-low{% elif loan.interest_rate <= 25 %}rate-medium{% else %}rate-high{% endif %}">
                                    {{ loan.interest_rate|floatformat:1 }}%
                                </span>
                            </td>
                            <td class="text-right font-medium text-green-600">
                                KSh {{ loan.interest_earned|floatformat:0|intcomma }}
                            </td>
                            <td class="text-right font-medium text-blue-600">
                                KSh {{ loan.outstanding_interest|floatformat:0|intcomma }}
                            </td>
                            <td>
                                <div class="text-sm text-gray-900">{{ loan.loan_term }} {{ loan.term_unit|default:"months" }}</div>
                                <div class="text-sm text-gray-500">{{ loan.payment_frequency|default:"Monthly" }}</div>
                            </td>
                            <td class="text-center">
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {% if loan.status == 'active' %}bg-green-100 text-green-800{% elif loan.status == 'completed' %}bg-blue-100 text-blue-800{% else %}bg-yellow-100 text-yellow-800{% endif %}">
                                    {{ loan.status|title }}
                                </span>
                            </td>
                            <td class="text-center">
                                <div class="flex justify-center gap-2">
                                    <button onclick="viewLoanDetails('{{ loan.id }}')" class="action-btn primary" title="View Details">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <button onclick="viewInterestSchedule('{{ loan.id }}')" class="action-btn success" title="Interest Schedule">
                                        <span>📅</span>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    {% else %}
                        <tr>
                            <td colspan="10" class="text-center py-8 text-gray-500">
                                <span>ℹ️</span>
                                <h3 class="text-lg font-medium mb-2">No Interest Income Found</h3>
                                <p>No interest income found for the selected period and filters.</p>
                            </td>
                        </tr>
                    {% endif %}
                </tbody>
            </table>
        </div>
    </div>

    <!-- Summary Statistics -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div class="filter-card">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">
                <span>📊</span>
                Income Collection Summary
            </h3>
            <div class="space-y-3">
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Interest Collected:</span>
                    <span class="font-semibold text-green-600">KSh {{ report_data.summary.interest_collected|default:0|floatformat:0|intcomma }}</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Interest Outstanding:</span>
                    <span class="font-semibold text-yellow-600">KSh {{ report_data.summary.interest_outstanding|default:0|floatformat:0|intcomma }}</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Collection Rate:</span>
                    <span class="font-semibold text-blue-600">{{ report_data.summary.collection_rate|default:0|floatformat:1 }}%</span>
                </div>
            </div>
        </div>

        <div class="filter-card">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">
                <i class="fas fa-trending-up text-green-500 mr-2"></i>
                Performance Metrics
            </h3>
            <div class="space-y-3">
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Growth vs Last Period:</span>
                    <span class="font-semibold {% if report_data.summary.growth_rate >= 0 %}text-green-600{% else %}text-red-600{% endif %}">
                        {{ report_data.summary.growth_rate|default:0|floatformat:1 }}%
                    </span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Highest Earning Loan:</span>
                    <span class="font-semibold text-blue-600">KSh {{ report_data.summary.highest_earning|default:0|floatformat:0|intcomma }}</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Most Profitable Product:</span>
                    <span class="font-semibold text-purple-600">{{ report_data.summary.top_product|default:"N/A" }}</span>
                </div>
            </div>
        </div>

        <div class="filter-card">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">
                <span>🧮</span>
                Interest Calculations
            </h3>
            <div class="space-y-3">
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Simple Interest:</span>
                    <span class="font-semibold text-blue-600">KSh {{ report_data.summary.simple_interest|default:0|floatformat:0|intcomma }}</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Compound Interest:</span>
                    <span class="font-semibold text-green-600">KSh {{ report_data.summary.compound_interest|default:0|floatformat:0|intcomma }}</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Effective Rate:</span>
                    <span class="font-semibold text-purple-600">{{ report_data.summary.effective_rate|default:0|floatformat:2 }}%</span>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Scripts -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    initializeCharts();
});

function initializeCharts() {
    // All charts removed
}

// Interactive Functions
function showTotalInterest() {
    alert('Total Interest Income: KSh {{ report_data.summary.total_interest_income|default:0|floatformat:0|intcomma }}');
}

function showInterestBearingLoans() {
    alert('Interest Bearing Loans: {{ report_data.summary.total_loans|default:0 }}');
}

function showAverageRate() {
    alert('Average Interest Rate: {{ report_data.summary.average_interest_rate|default:0|floatformat:1 }}%');
}

function showYieldRate() {
    alert('Portfolio Yield: {{ report_data.summary.portfolio_yield|default:0|floatformat:1 }}%');
}

function showProjectedIncome() {
    alert('Projected Monthly Income: KSh {{ report_data.summary.projected_monthly_income|default:0|floatformat:0|intcomma }}');
}

function filterByRate(rate) {
    alert(`Filtering by ${rate} interest rate loans`);
}

function showCompoundInterest() {
    alert('Compound Interest Loans: {{ report_data.summary.compound_loans|default:0 }}');
}

function viewLoanDetails(loanId) {
    window.open(`/loans/${loanId}/`, '_blank');
}

function viewInterestSchedule(loanId) {
    window.open(`/loans/${loanId}/interest-schedule/`, '_blank');
}

function exportToExcel() {
    window.location.href = '{% url "reports:interest_income_report" %}?export=excel&{{ request.GET.urlencode }}';
}

function exportToPDF() {
    window.location.href = '{% url "reports:interest_income_report" %}?export=pdf&{{ request.GET.urlencode }}';
}
</script>
{% endblock %}