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

{% block title %}Disbursed Loans 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%); }

.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;
}

.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;
    position: sticky;
    top: 0;
    z-index: 10;
}

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

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

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

.status-active { background-color: #dbeafe; color: #1e40af; }
.status-paid { background-color: #d1fae5; color: #065f46; }
.status-defaulted { background-color: #fee2e2; color: #991b1b; }
.status-rolled_over { background-color: #fef3c7; color: #92400e; }
.status-written_off { background-color: #f3f4f6; color: #6b7280; }

.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; }

.sort-icon {
    display: inline-block;
    margin-left: 0.25rem;
    font-size: 0.75rem;
}

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

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

.filter-group select,
.filter-group input {
    padding: 0.5rem;
    border: 1px solid #d1d5db;
    border-radius: 6px;
    font-size: 0.875rem;
}

.filter-group select:focus,
.filter-group input:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.period-tabs {
    display: flex;
    gap: 0.5rem;
    margin-bottom: 1rem;
}

.period-tab {
    padding: 0.5rem 1rem;
    border-radius: 6px;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    border: 1px solid #d1d5db;
    background: white;
    transition: all 0.2s;
}

.period-tab:hover {
    background: #f3f4f6;
}

.period-tab.active {
    background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);
    color: white;
    border-color: #1e40af;
}
</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">
                    <span>📊</span>
                    Disbursed Loans Report
                </h1>
                <p class="text-gray-600 dark:text-gray-400 mt-2">
                    Track loan disbursements and analyze lending patterns
                </p>
            </div>
            <div class="flex gap-3">
                <a href="?{{ request.GET.urlencode }}&export=pdf" class="action-btn danger">
                    <i class="fas fa-file-pdf"></i>
                    Export PDF
                </a>
                <a href="?{{ request.GET.urlencode }}&export=excel" class="action-btn success">
                    <i class="fas fa-file-excel"></i>
                    Export Excel
                </a>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div class="metric-card">
            <div class="text-sm opacity-90 mb-1">Total Loans</div>
            <div class="text-3xl font-bold">{{ summary.total_loans|intcomma }}</div>
        </div>
        <div class="metric-card success">
            <div class="text-sm opacity-90 mb-1">Total Disbursed</div>
            <div class="text-2xl font-bold">KES {{ summary.total_principal|floatformat:2|intcomma }}</div>
        </div>
        <div class="metric-card info">
            <div class="text-sm opacity-90 mb-1">Total Paid</div>
            <div class="text-2xl font-bold">KES {{ summary.total_paid|floatformat:2|intcomma }}</div>
        </div>
        <div class="metric-card warning">
            <div class="text-sm opacity-90 mb-1">Total Outstanding</div>
            <div class="text-2xl font-bold">KES {{ summary.total_outstanding|floatformat:2|intcomma }}</div>
        </div>
    </div>

    <!-- Filters Section -->
    <div class="filter-card mb-8">
        <h2 class="text-xl font-bold text-gray-900 mb-4">Filters</h2>
        
        <form method="get" action="{% url 'reports:disbursed_loans_report' %}" id="filterForm">
            <!-- Period Tabs -->
            <div class="period-tabs">
                <button type="button" class="period-tab {% if period == 'today' %}active{% endif %}" onclick="setPeriod('today')">
                    Today
                </button>
                <button type="button" class="period-tab {% if period == 'this_week' %}active{% endif %}" onclick="setPeriod('this_week')">
                    This Week
                </button>
                <button type="button" class="period-tab {% if period == 'total' %}active{% endif %}" onclick="setPeriod('total')">
                    All Time
                </button>
            </div>
            <input type="hidden" name="period" id="periodInput" value="{{ period }}">
            
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
                <!-- Status Filter -->
                <div class="filter-group">
                    <label for="status">Status</label>
                    <select name="status" id="status" onchange="document.getElementById('filterForm').submit()">
                        <option value="">All Statuses</option>
                        {% for status in disbursed_statuses %}
                        <option value="{{ status }}" {% if status_filter == status %}selected{% endif %}>
                            {{ status|title }}
                        </option>
                        {% endfor %}
                    </select>
                </div>

                <!-- Branch Filter -->
                <div class="filter-group">
                    <label for="branch_id">Branch</label>
                    <select name="branch_id" id="branch_id" onchange="document.getElementById('filterForm').submit()">
                        <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>

                <!-- Loan Product Filter -->
                <div class="filter-group">
                    <label for="loan_product_id">Loan Product</label>
                    <select name="loan_product_id" id="loan_product_id" onchange="document.getElementById('filterForm').submit()">
                        <option value="">All Products</option>
                        {% for product in loan_products %}
                        <option value="{{ product.id }}" {% if loan_product_id == product.id|stringformat:"s" %}selected{% endif %}>
                            {{ product.name }}
                        </option>
                        {% endfor %}
                    </select>
                </div>

                <!-- Sort By -->
                <div class="filter-group">
                    <label for="sort_by">Sort By</label>
                    <select name="sort_by" id="sort_by" onchange="document.getElementById('filterForm').submit()">
                        <option value="disbursement_date" {% if sort_by == 'disbursement_date' %}selected{% endif %}>Disbursement Date</option>
                        <option value="loan_number" {% if sort_by == 'loan_number' %}selected{% endif %}>Loan Number</option>
                        <option value="borrower_name" {% if sort_by == 'borrower_name' %}selected{% endif %}>Borrower Name</option>
                        <option value="principal_amount" {% if sort_by == 'principal_amount' %}selected{% endif %}>Principal Amount</option>
                        <option value="outstanding_amount" {% if sort_by == 'outstanding_amount' %}selected{% endif %}>Outstanding Amount</option>
                    </select>
                </div>
            </div>

            <!-- Date Range Filters -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                <div class="filter-group">
                    <label for="from_date">From Date</label>
                    <input type="date" name="from_date" id="from_date" value="{{ from_date }}" class="w-full">
                </div>

                <div class="filter-group">
                    <label for="to_date">To Date</label>
                    <input type="date" name="to_date" id="to_date" value="{{ to_date }}" class="w-full">
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <!-- Amount Range -->
                <div class="filter-group">
                    <label for="amount_min">Min Amount</label>
                    <input type="number" name="amount_min" id="amount_min" value="{{ amount_min }}" placeholder="0" step="100">
                </div>

                <div class="filter-group">
                    <label for="amount_max">Max Amount</label>
                    <input type="number" name="amount_max" id="amount_max" value="{{ amount_max }}" placeholder="No limit" step="100">
                </div>

                <!-- Sort Order -->
                <div class="filter-group">
                    <label for="sort_order">Sort Order</label>
                    <select name="sort_order" id="sort_order" onchange="document.getElementById('filterForm').submit()">
                        <option value="desc" {% if sort_order == 'desc' %}selected{% endif %}>Descending</option>
                        <option value="asc" {% if sort_order == 'asc' %}selected{% endif %}>Ascending</option>
                    </select>
                </div>
            </div>

            <div class="mt-4 flex gap-3">
                <button type="submit" class="action-btn primary">
                    <i class="fas fa-filter"></i>
                    Apply Filters
                </button>
                <a href="{% url 'reports:disbursed_loans_report' %}" class="action-btn" style="background: #6b7280; color: white;">
                    <i class="fas fa-redo"></i>
                    Reset
                </a>
            </div>
        </form>
    </div>

    <!-- Data Table -->
    <div class="data-table">
        <table class="w-full">
            <thead>
                <tr>
                    <th>Loan Number</th>
                    <th>Borrower Name</th>
                    <th>Phone Number</th>
                    <th>Disbursement Date</th>
                    <th class="text-right">Principal</th>
                    <th class="text-right">Interest</th>
                    <th class="text-right">Fee</th>
                    <th class="text-right">Total</th>
                    <th class="text-right">Paid</th>
                    <th class="text-right">Outstanding</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                {% if report_data %}
                    {% for loan in report_data %}
                    <tr>
                        <td class="font-medium">{{ loan.loan_number }}</td>
                        <td>{{ loan.borrower_name }}</td>
                        <td>{{ loan.phone_number|default:"N/A" }}</td>
                        <td>{{ loan.disbursement_date|date:"Y-m-d" }}</td>
                        <td class="text-right">{{ loan.principal_amount|floatformat:2|intcomma }}</td>
                        <td class="text-right">{{ loan.interest_amount|floatformat:2|intcomma }}</td>
                        <td class="text-right">{{ loan.processing_fee|floatformat:2|intcomma }}</td>
                        <td class="text-right font-medium">{{ loan.total_amount|floatformat:2|intcomma }}</td>
                        <td class="text-right">{{ loan.amount_paid|floatformat:2|intcomma }}</td>
                        <td class="text-right font-medium">{{ loan.outstanding_amount|floatformat:2|intcomma }}</td>
                        <td>
                            <span class="status-badge status-{{ loan.status|lower|cut:' ' }}">
                                {{ loan.status }}
                            </span>
                        </td>
                        <td>
                            <a href="{% url 'loans:loan_detail' loan.loan_id %}" class="text-blue-600 hover:text-blue-800">
                                <i class="fas fa-eye"></i>
                            </a>
                        </td>
                    </tr>
                    {% endfor %}
                {% else %}
                    <tr>
                        <td colspan="12" class="text-center py-8 text-gray-500">
                            No loans found matching the selected filters.
                        </td>
                    </tr>
                {% endif %}
            </tbody>
        </table>
    </div>

    <!-- Summary Footer -->
    {% if report_data %}
    <div class="mt-6 p-4 bg-gray-50 rounded-lg">
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
            <div>
                <span class="text-gray-600">Total Principal:</span>
                <span class="font-bold ml-2">KES {{ summary.total_principal|floatformat:2|intcomma }}</span>
            </div>
            <div>
                <span class="text-gray-600">Total Interest:</span>
                <span class="font-bold ml-2">KES {{ summary.total_interest|floatformat:2|intcomma }}</span>
            </div>
            <div>
                <span class="text-gray-600">Total Fees:</span>
                <span class="font-bold ml-2">KES {{ summary.total_processing_fee|floatformat:2|intcomma }}</span>
            </div>
            <div>
                <span class="text-gray-600">Total Amount:</span>
                <span class="font-bold ml-2">KES {{ summary.total_amount|floatformat:2|intcomma }}</span>
            </div>
        </div>
    </div>
    {% endif %}
</div>

<script>
function setPeriod(period) {
    document.getElementById('periodInput').value = period;
    document.getElementById('filterForm').submit();
}
</script>
{% endblock %}
