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

{% block title %}Completed Loans - Haven Grazuri Investment Limited{% endblock %}

{% block content %}
<div>
    <!-- Summary Statistics -->
    <div class="mb-8 grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
        <div class="overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6">
            <dt class="truncate text-sm font-medium text-gray-500">Total Completed Loans</dt>
            <dd class="mt-1 text-3xl font-semibold tracking-tight text-gray-900">{{ total_loans }}</dd>
            <p class="mt-2 text-sm text-gray-600">Average Amount: KES {{ advanced_stats.avg_loan_amount|floatformat:2 }}</p>
        </div>
        <div class="overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6">
            <dt class="truncate text-sm font-medium text-gray-500">Total Principal</dt>
            <dd class="mt-1 text-3xl font-semibold tracking-tight text-gray-900">KES {{ total_principal|floatformat:2 }}</dd>
        </div>
        <div class="overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6">
            <dt class="truncate text-sm font-medium text-gray-500">Total Interest</dt>
            <dd class="mt-1 text-3xl font-semibold tracking-tight text-gray-900">KES {{ total_interest|floatformat:2 }}</dd>
        </div>
        <div class="overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6">
            <dt class="truncate text-sm font-medium text-gray-500">Total Collected</dt>
            <dd class="mt-1 text-3xl font-semibold tracking-tight text-gray-900">KES {{ total_collected|floatformat:2 }}</dd>
        </div>
    </div>

    <!-- Advanced Statistics -->
    <div class="mb-8 grid grid-cols-1 gap-5 lg:grid-cols-2">
        <!-- Loan Distribution by Product -->
        <div class="overflow-hidden rounded-lg bg-white shadow">
            <div class="p-6">
                <h3 class="text-lg font-medium text-gray-900">Completed Loans by Product</h3>
                <div class="mt-4">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead>
                            <tr>
                                <th class="px-4 py-2 text-left text-sm font-medium text-gray-500">Product Type</th>
                                <th class="px-4 py-2 text-right text-sm font-medium text-gray-500">Count</th>
                                <th class="px-4 py-2 text-right text-sm font-medium text-gray-500">Total Amount</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            {% for product in advanced_stats.loans_by_product %}
                            <tr>
                                <td class="px-4 py-2 text-sm text-gray-900">{{ product.loan_product__product_type }}</td>
                                <td class="px-4 py-2 text-right text-sm text-gray-900">{{ product.count }}</td>
                                <td class="px-4 py-2 text-right text-sm text-gray-900">KES {{ product.total_amount|floatformat:2 }}</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Top Borrowers -->
        <div class="overflow-hidden rounded-lg bg-white shadow">
            <div class="p-6">
                <h3 class="text-lg font-medium text-gray-900">Top Borrowers with Completed Loans</h3>
                <div class="mt-4">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead>
                            <tr>
                                <th class="px-4 py-2 text-left text-sm font-medium text-gray-500">Client</th>
                                <th class="px-4 py-2 text-right text-sm font-medium text-gray-500">Total Loans</th>
                                <th class="px-4 py-2 text-right text-sm font-medium text-gray-500">Total Amount</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            {% for client in advanced_stats.client_summary %}
                            <tr>
                                <td class="px-4 py-2 text-sm text-gray-900">{{ client.borrower__first_name }} {{ client.borrower__last_name }}</td>
                                <td class="px-4 py-2 text-right text-sm text-gray-900">{{ client.total_loans }}</td>
                                <td class="px-4 py-2 text-right text-sm text-gray-900">KES {{ client.total_amount|floatformat:2 }}</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="sm:flex sm:items-center">
        <div class="sm:flex-auto">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-2xl font-semibold text-text-dark">Completed Loans</h1>
                    <p class="mt-2 text-sm text-gray-700">
                        View and analyze all completed (paid) loans in the system.
                    </p>
                </div>
                <div class="flex gap-4">
                    <a href="?{{ request.GET.urlencode }}&generate_report=true" 
                       class="inline-flex items-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50">
                        <span>⬇️</span> Download Report
                    </a>
                </div>
            </div>
        </div>
    </div>
    <!-- Filters and Search -->
    <div class="mt-6">
        <form method="get" class="space-y-4">
            <div class="flex flex-col sm:flex-row gap-4">
                <!-- Search Input -->
                <div class="relative flex-1">
                    <div class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
                        <span>🔍</span>
                    </div>
                    <input
                        type="text"
                        name="search"
                        id="loans-search"
                        value="{{ request.GET.search|default:'' }}"
                        class="block w-full rounded-md border-0 py-1.5 pl-10 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6"
                        placeholder="Search by client name, loan number, or business..."
                    />
                </div>
                
                <div class="flex flex-wrap items-center gap-4">
                    <!-- Product Type Filter -->
                    <div class="flex items-center gap-2">
                        <span>💵</span>
                        <select
                            name="product_type"
                            id="loans-product-type"
                            class="rounded-md border-0 py-1.5 pl-3 pr-10 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-primary sm:text-sm sm:leading-6"
                        >
                            <option value="">All Products</option>
                            <option value="boost" {% if request.GET.product_type == 'boost' %}selected{% endif %}>Boost</option>
                            <option value="boost_plus" {% if request.GET.product_type == 'boost_plus' %}selected{% endif %}>Boost Plus</option>
                            <option value="mwamba" {% if request.GET.product_type == 'mwamba' %}selected{% endif %}>Mwamba</option>
                            <option value="imara" {% if request.GET.product_type == 'imara' %}selected{% endif %}>Imara</option>
                        </select>
                    </div>

                    <!-- Date Range Filters -->
                    <div class="flex items-center gap-2">
                        <span>📅</span>
                        <input
                            type="date"
                            name="date_from"
                            id="loans-date-from"
                            value="{{ request.GET.date_from|default:'' }}"
                            class="rounded-md border-0 py-1.5 pl-3 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-primary sm:text-sm sm:leading-6"
                            placeholder="From Date"
                        />
                        <span class="text-gray-500">to</span>
                        <input
                            type="date"
                            name="date_to"
                            id="loans-date-to"
                            value="{{ request.GET.date_to|default:'' }}"
                            class="rounded-md border-0 py-1.5 pl-3 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-primary sm:text-sm sm:leading-6"
                            placeholder="To Date"
                        />
                    </div>

                    <!-- Search Button -->
                    <button type="submit" 
                            class="rounded-md bg-primary px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-primary-dark focus:ring-2 focus:ring-primary focus:ring-offset-2 flex items-center gap-2">
                        <span>🔍</span>
                        Search
                    </button>

                    <!-- Clear Filters -->
                    <a href="{% url 'loans:completed_loans' %}" 
                       class="rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 flex items-center gap-2">
                        <span>✕</span>
                        Clear Filters
                    </a>
                </div>
            </div>
        </form>

        <!-- Active Filters Display -->
        {% if request.GET.search or request.GET.product_type or request.GET.date_from or request.GET.date_to %}
        <div class="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-md">
            <div class="flex items-center justify-between">
                <div class="text-sm text-blue-700">
                    <span>🔍</span>
                    <span>
                        {% if request.GET.search %}Search: "{{ request.GET.search }}"{% endif %}
                        {% if request.GET.product_type %}{% if request.GET.search %}, {% endif %}Product: {{ request.GET.product_type|title }}{% endif %}
                        {% if request.GET.date_from or request.GET.date_to %}{% if request.GET.search or request.GET.product_type %}, {% endif %}Date Range: {{ request.GET.date_from|default:"Start" }} to {{ request.GET.date_to|default:"End" }}{% endif %}
                    </span>
                </div>
                <a href="{% url 'loans:completed_loans' %}" class="text-blue-600 hover:text-blue-800 text-sm">
                    <span>✕</span>Clear all
                </a>
            </div>
        </div>
        {% endif %}
    </div>
    </div>

    <!-- Loans Table -->
    <div class="mt-8 flow-root">
        <div class="-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
            <div class="inline-block min-w-full py-2 align-middle sm:px-6 lg:px-8">
                <div class="overflow-hidden shadow ring-1 ring-black ring-opacity-5 sm:rounded-lg">
                    <div id="loans-table-container">
                        {% include 'loans/loans_table.html' %}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Pagination -->
    {% if loans.paginator.num_pages > 1 %}
    <div class="mt-4 flex items-center justify-between border-t border-gray-200 bg-white px-4 py-3 sm:px-6">
        <div class="flex flex-1 justify-between sm:hidden">
            {% if loans.has_previous %}
            <a href="?page={{ loans.previous_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if selected_product_type %}&product_type={{ selected_product_type }}{% endif %}{% if date_from %}&date_from={{ date_from }}{% endif %}{% if date_to %}&date_to={{ date_to }}{% endif %}" 
               class="relative inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">
                Previous
            </a>
            {% endif %}
            {% if loans.has_next %}
            <a href="?page={{ loans.next_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if selected_product_type %}&product_type={{ selected_product_type }}{% endif %}{% if date_from %}&date_from={{ date_from }}{% endif %}{% if date_to %}&date_to={{ date_to }}{% endif %}" 
               class="relative ml-3 inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">
                Next
            </a>
            {% endif %}
        </div>
        <div class="hidden sm:flex sm:flex-1 sm:items-center sm:justify-between">
            <div>
                <p class="text-sm text-gray-700">
                    Showing <span class="font-medium">{{ loans.start_index }}</span> to
                    <span class="font-medium">{{ loans.end_index }}</span> of
                    <span class="font-medium">{{ loans.paginator.count }}</span> results
                </p>
            </div>
            <div>
                <nav class="isolate inline-flex -space-x-px rounded-md shadow-sm" aria-label="Pagination">
                    {% if loans.has_previous %}
                    <a href="?page={{ loans.previous_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if selected_product_type %}&product_type={{ selected_product_type }}{% endif %}{% if date_from %}&date_from={{ date_from }}{% endif %}{% if date_to %}&date_to={{ date_to }}{% endif %}"
                       class="relative inline-flex items-center rounded-l-md px-2 py-2 text-gray-400 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0">
                        <span class="sr-only">Previous</span>
                        <span>‹</span>
                    </a>
                    {% endif %}
                    
                    {% for i in loans.paginator.page_range %}
                        {% if loans.number == i %}
                        <span class="relative z-10 inline-flex items-center bg-primary px-4 py-2 text-sm font-semibold text-white focus:z-20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary">
                            {{ i }}
                        </span>
                        {% else %}
                        <a href="?page={{ i }}{% if search_query %}&search={{ search_query }}{% endif %}{% if selected_product_type %}&product_type={{ selected_product_type }}{% endif %}{% if date_from %}&date_from={{ date_from }}{% endif %}{% if date_to %}&date_to={{ date_to }}{% endif %}"
                           class="relative inline-flex items-center px-4 py-2 text-sm font-semibold text-gray-900 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0">
                            {{ i }}
                        </a>
                        {% endif %}
                    {% endfor %}
                    
                    {% if loans.has_next %}
                    <a href="?page={{ loans.next_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if selected_product_type %}&product_type={{ selected_product_type }}{% endif %}{% if date_from %}&date_from={{ date_from }}{% endif %}{% if date_to %}&date_to={{ date_to }}{% endif %}"
                       class="relative inline-flex items-center rounded-r-md px-2 py-2 text-gray-400 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0">
                        <span class="sr-only">Next</span>
                        <span>›</span>
                    </a>
                    {% endif %}
                </nav>
            </div>
        </div>
    </div>
    {% endif %}
</div>
{% endblock %}