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

{% block title %}Edit Loan - Haven Grazuri Investment Limited{% endblock %}

{% block content %}
<div class="max-w-4xl mx-auto">
    <!-- Display Messages -->
    {% if messages %}
    <div class="mb-6">
        {% for message in messages %}
        <div class="rounded-md p-4 {% if message.tags == 'error' %}bg-red-50 text-red-800{% elif message.tags == 'success' %}bg-green-50 text-green-800{% elif message.tags == 'warning' %}bg-yellow-50 text-yellow-800{% else %}bg-blue-50 text-blue-800{% endif %}">
            <div class="flex">
                <div class="flex-shrink-0">
                    {% if message.tags == 'error' %}
                    <span>❌</span>
                    {% elif message.tags == 'success' %}
                    <span>✅</span>
                    {% elif message.tags == 'warning' %}
                    <span>⚠️</span>
                    {% else %}
                    <span>ℹ️</span>
                    {% endif %}
                </div>
                <div class="ml-3">
                    <p class="text-sm font-medium">{{ message }}</p>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
    {% endif %}
    
    <!-- Header -->
    <div class="mb-8">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-semibold text-gray-900">Edit Loan</h1>
                <p class="mt-2 text-sm text-gray-700">
                    Modify loan details for {{ loan.loan_number }}
                </p>
            </div>
            <div class="flex gap-3">
                <a href="{% url 'loans:loan_detail' pk=loan.pk %}"
                    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>
                    Back to Loan
                </a>
            </div>
        </div>
    </div>

    <!-- Warning Notice -->
    <div class="mb-6 rounded-md bg-yellow-50 p-4">
        <div class="flex">
            <div class="flex-shrink-0">
                <span>⚠️</span>
            </div>
            <div class="ml-3">
                <h3 class="text-sm font-medium text-yellow-800">
                    Important Notice
                </h3>
                <div class="mt-2 text-sm text-yellow-700">
                    <p>Editing loan details will affect calculations and may impact existing repayments. Please ensure
                        all changes are accurate.</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Current Loan Info -->
    <div class="mb-6 overflow-hidden rounded-lg bg-white shadow">
        <div class="px-4 py-5 sm:p-6">
            <h3 class="text-lg font-medium text-gray-900 mb-4">Current Loan Information</h3>
            <div class="grid grid-cols-1 gap-6 sm:grid-cols-3">
                <div>
                    <dt class="text-sm font-medium text-gray-500">Borrower</dt>
                    <dd class="mt-1 text-sm text-gray-900">{{ loan.borrower.get_full_name }}</dd>
                </div>
                <div>
                    <dt class="text-sm font-medium text-gray-500">Loan Number</dt>
                    <dd class="mt-1 text-sm text-gray-900">{{ loan.loan_number }}</dd>
                </div>
                <div>
                    <dt class="text-sm font-medium text-gray-500">Status</dt>
                    <dd class="mt-1">
                        <span class="inline-flex rounded-full px-2 text-xs font-semibold leading-5 
                            {% if loan.status == 'active' %}bg-green-100 text-green-800
                            {% elif loan.status == 'paid' %}bg-blue-100 text-blue-800
                            {% elif loan.status == 'defaulted' %}bg-red-100 text-red-800
                            {% elif loan.status == 'written_off' %}bg-gray-100 text-gray-800
                            {% elif loan.status == 'rolled_over' %}bg-green-100 text-green-800
                            {% endif %}">
                            {{ loan.get_status_display }}
                        </span>
                    </dd>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Form -->
    <div class="overflow-hidden rounded-lg bg-white shadow">
        <form method="post" class="space-y-6 px-4 py-5 sm:p-6">
            {% csrf_token %}

            <div class="grid grid-cols-1 gap-6 sm:grid-cols-2">
                <!-- Principal Amount -->
                <div>
                    <label for="principal_amount" class="block text-sm font-medium text-gray-700">
                        Principal Amount (KES)
                    </label>
                    <div class="mt-1">
                        <input type="number" name="principal_amount" id="principal_amount" step="0.01" min="0"
                            value="{{ loan.principal_amount }}" required
                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm 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">
                    </div>
                    <p class="mt-1 text-xs text-gray-500">Current: KES {{ loan.principal_amount|floatformat:2 }}</p>
                </div>

                <!-- Interest Amount -->
                <div>
                    <label for="interest_amount" class="block text-sm font-medium text-gray-700">
                        Interest Amount (KES)
                    </label>
                    <div class="mt-1">
                        <input type="number" name="interest_amount" id="interest_amount" step="0.01" min="0"
                            value="{{ loan.interest_amount }}" required
                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm 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">
                    </div>
                    <p class="mt-1 text-xs text-gray-500">Current: KES {{ loan.interest_amount|floatformat:2 }}</p>
                </div>

                <!-- Processing Fee -->
                <div>
                    <label for="processing_fee" class="block text-sm font-medium text-gray-700">
                        Processing Fee (KES)
                    </label>
                    <div class="mt-1">
                        <input type="number" name="processing_fee" id="processing_fee" step="0.01" min="0"
                            value="{{ loan.processing_fee }}" required
                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm 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">
                    </div>
                    <p class="mt-1 text-xs text-gray-500">Current: KES {{ loan.processing_fee|floatformat:2 }}</p>
                </div>

                <!-- Duration -->
                <div>
                    <label for="duration_days" class="block text-sm font-medium text-gray-700">
                        Duration (Days)
                    </label>
                    <div class="mt-1">
                        <input type="number" name="duration_days" id="duration_days" min="1"
                            value="{{ loan.duration_days }}" required
                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm 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">
                    </div>
                    <p class="mt-1 text-xs text-gray-500">Current: {{ loan.duration_days }} days</p>
                </div>

                <!-- Disbursement Date -->
                <div>
                    <label for="disbursement_date" class="block text-sm font-medium text-gray-700">
                        Disbursement Date
                    </label>
                    <div class="mt-1">
                        <input type="date" name="disbursement_date" id="disbursement_date"
                            value="{{ loan.disbursement_date|date:'Y-m-d' }}"
                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm 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">
                    </div>
                    <p class="mt-1 text-xs text-gray-500">Current: {{ loan.disbursement_date|date:"Y-m-d" }}</p>
                </div>

                <!-- Due Date -->
                <div>
                    <label for="due_date" class="block text-sm font-medium text-gray-700">
                        Due Date
                    </label>
                    <div class="mt-1">
                        <input type="date" name="due_date" id="due_date"
                            value="{{ loan.due_date|date:'Y-m-d' }}"
                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm 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">
                    </div>
                    <p class="mt-1 text-xs text-gray-500">Current: {{ loan.due_date|date:"Y-m-d" }}</p>
                </div>

                <!-- Status Dropdown -->
                <div class="sm:col-span-2">
                    <label for="status" class="block text-sm font-medium text-gray-700">
                        Loan Status
                    </label>
                    <div class="mt-1">
                        <select name="status" id="status"
                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6">
                            {% for value, label in status_choices %}
                            <option value="{{ value }}" {% if loan.status == value %}selected{% endif %}>
                                {{ label }}
                            </option>
                            {% endfor %}
                        </select>
                    </div>
                    <p class="mt-1 text-xs text-gray-500">
                        Current: {{ loan.get_status_display }}
                        <br>
                        <span class="text-yellow-600">⚠️ Status transitions are validated. Not all transitions are allowed.</span>
                    </p>
                </div>

                <!-- Calculated Fields (Read-only display) -->
                <div class="sm:col-span-2">
                    <label class="block text-sm font-medium text-gray-700">
                        Current Totals
                    </label>
                    <div class="mt-1 space-y-1">
                        <p class="text-sm text-gray-600">Total Amount: KES {{ loan.total_amount|floatformat:2 }}</p>
                        <p class="text-sm text-gray-600">Amount Paid: KES {{ loan.amount_paid|floatformat:2 }}</p>
                        <p class="text-sm text-gray-600">Outstanding: KES {{ loan.outstanding_amount|floatformat:2 }}</p>
                        <p class="text-sm text-gray-600">Total Penalties: KES {{ loan.total_penalties|floatformat:2 }}</p>
                    </div>
                </div>
            </div>

            <!-- Repayment Impact Warning -->
            {% if loan.repayments.exists %}
            <div class="rounded-md bg-red-50 p-4">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <span>⚠️</span>
                    </div>
                    <div class="ml-3">
                        <h3 class="text-sm font-medium text-red-800">
                            Repayment Impact
                        </h3>
                        <div class="mt-2 text-sm text-red-700">
                            <p>This loan has {{ loan.repayments.count }} existing repayment(s). Changing the loan amount
                                or interest rate may affect the outstanding balance calculations.</p>
                        </div>
                    </div>
                </div>
            </div>
            {% endif %}

            <!-- Action Buttons -->
            <div class="flex justify-end space-x-3 pt-6 border-t border-gray-200">
                <a href="{% url 'loans:loan_detail' pk=loan.pk %}"
                    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">
                    Cancel
                </a>
                <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-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary">
                    <span>💾</span>
                    Update Loan
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    // Real-time calculation preview
    document.addEventListener('DOMContentLoaded', function () {
        const principalInput = document.getElementById('principal_amount');
        const interestAmountInput = document.getElementById('interest_amount');
        const processingFeeInput = document.getElementById('processing_fee');
        const durationInput = document.getElementById('duration_days');
        const form = document.querySelector('form');

        function updateCalculations() {
            const principal = parseFloat(principalInput.value) || 0;
            const interestAmount = parseFloat(interestAmountInput.value) || 0;
            const processingFee = parseFloat(processingFeeInput.value) || 0;
            const duration = parseInt(durationInput.value) || 0;

            const totalAmount = principal + interestAmount + processingFee;

            // Update display (you could add preview elements here)
            console.log('Preview - Principal:', principal, 'Interest:', interestAmount, 'Processing Fee:', processingFee, 'Total:', totalAmount);
        }

        principalInput.addEventListener('input', updateCalculations);
        interestAmountInput.addEventListener('input', updateCalculations);
        processingFeeInput.addEventListener('input', updateCalculations);
        durationInput.addEventListener('input', updateCalculations);
        
        // Log form submission
        form.addEventListener('submit', function(e) {
            console.log('Form submitting...');
            console.log('Principal:', principalInput.value);
            console.log('Interest:', interestAmountInput.value);
            console.log('Processing Fee:', processingFeeInput.value);
            console.log('Status:', document.getElementById('status').value);
        });
    });
</script>
{% endblock %}