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

{% block title %}Credit Scores Management{% endblock %}

{% block extra_css %}
<style>
    .score-card {
        transition: transform 0.2s;
    }
    .score-card:hover {
        transform: translateY(-2px);
    }
    .score-excellent { border-left: 4px solid #10b981; }
    .score-good { border-left: 4px solid #3b82f6; }
    .score-fair { border-left: 4px solid #f59e0b; }
    .score-poor { border-left: 4px solid #ef4444; }
    
    .risk-low { background-color: #d1fae5; color: #065f46; }
    .risk-medium { background-color: #fef3c7; color: #92400e; }
    .risk-high { background-color: #fee2e2; color: #991b1b; }
</style>
{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <!-- Header -->
    <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-900 mb-2">Credit Scores Management</h1>
        <p class="text-gray-600">Monitor and manage borrower credit scores</p>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="bg-white rounded-lg shadow p-6">
            <div class="flex items-center">
                <div class="p-2 bg-green-100 rounded-lg">
                    <span>👥</span>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Total Borrowers</p>
                    <p class="text-2xl font-semibold text-gray-900">{{ stats.total_borrowers }}</p>
                </div>
            </div>
        </div>

        <div class="bg-white rounded-lg shadow p-6">
            <div class="flex items-center">
                <div class="p-2 bg-green-100 rounded-lg">
                    <i class="fas fa-shield-alt text-green-600"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Low Risk</p>
                    <p class="text-2xl font-semibold text-green-600">{{ stats.low_risk }}</p>
                </div>
            </div>
        </div>

        <div class="bg-white rounded-lg shadow p-6">
            <div class="flex items-center">
                <div class="p-2 bg-yellow-100 rounded-lg">
                    <span>⚠️</span>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Medium Risk</p>
                    <p class="text-2xl font-semibold text-yellow-600">{{ stats.medium_risk }}</p>
                </div>
            </div>
        </div>

        <div class="bg-white rounded-lg shadow p-6">
            <div class="flex items-center">
                <div class="p-2 bg-red-100 rounded-lg">
                    <span>⚠️</span>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">High Risk</p>
                    <p class="text-2xl font-semibold text-red-600">{{ stats.high_risk }}</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Actions -->
    <div class="bg-white rounded-lg shadow mb-8">
        <div class="px-6 py-4 border-b border-gray-200">
            <h2 class="text-lg font-semibold text-gray-900">Actions</h2>
        </div>
        <div class="p-6">
            <div class="flex flex-wrap gap-4">
                <button onclick="updateAllScores()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg">
                    <span>🔄</span>Update All Scores
                </button>
                <button onclick="updateRecentActivity()" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg">
                    <span>⏰</span>Update Recent Activity
                </button>
                <button onclick="exportScores()" class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg">
                    <span>⬇️</span>Export Scores
                </button>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-lg shadow mb-8">
        <div class="px-6 py-4 border-b border-gray-200">
            <h2 class="text-lg font-semibold text-gray-900">Filters</h2>
        </div>
        <div class="p-6">
            <form method="GET" class="flex flex-wrap gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Risk Level</label>
                    <select name="risk_level" class="border border-gray-300 rounded-md px-3 py-2">
                        <option value="">All Risk Levels</option>
                        <option value="low" {% if request.GET.risk_level == 'low' %}selected{% endif %}>Low Risk</option>
                        <option value="medium" {% if request.GET.risk_level == 'medium' %}selected{% endif %}>Medium Risk</option>
                        <option value="high" {% if request.GET.risk_level == 'high' %}selected{% endif %}>High Risk</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Score Range</label>
                    <select name="score_range" class="border border-gray-300 rounded-md px-3 py-2">
                        <option value="">All Scores</option>
                        <option value="80-100" {% if request.GET.score_range == '80-100' %}selected{% endif %}>80-100 (Excellent)</option>
                        <option value="60-79" {% if request.GET.score_range == '60-79' %}selected{% endif %}>60-79 (Good)</option>
                        <option value="40-59" {% if request.GET.score_range == '40-59' %}selected{% endif %}>40-59 (Fair)</option>
                        <option value="0-39" {% if request.GET.score_range == '0-39' %}selected{% endif %}>0-39 (Poor)</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Search</label>
                    <input type="text" name="search" value="{{ request.GET.search }}" 
                           placeholder="Search by name..." 
                           class="border border-gray-300 rounded-md px-3 py-2">
                </div>
                <div class="flex items-end">
                    <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md">
                        <span>🔍</span>Filter
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Credit Scores List -->
    <div class="bg-white rounded-lg shadow">
        <div class="px-6 py-4 border-b border-gray-200">
            <h2 class="text-lg font-semibold text-gray-900">Credit Scores</h2>
        </div>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Borrower
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Credit Score
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Risk Level
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Credit Limit
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Last Updated
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Actions
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {% for score in credit_scores %}
                    <tr class="hover:bg-gray-50">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="flex-shrink-0 h-10 w-10">
                                    {% if score.user.profile_image %}
                                        <img class="h-10 w-10 rounded-full object-cover" 
                                             src="{{ score.user.profile_image.url }}" 
                                             alt="{{ score.user.get_full_name }}">
                                    {% else %}
                                        <div class="h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center">
                                            <span class="text-sm font-medium text-gray-700">
                                                {{ score.user.first_name|first }}{{ score.user.last_name|first }}
                                            </span>
                                        </div>
                                    {% endif %}
                                </div>
                                <div class="ml-4">
                                    <div class="text-sm font-medium text-gray-900">
                                        {{ score.user.get_full_name }}
                                    </div>
                                    <div class="text-sm text-gray-500">
                                        {{ score.user.email }}
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="text-2xl font-bold 
                                    {% if score.total_score >= 80 %}text-green-600
                                    {% elif score.total_score >= 60 %}text-blue-600
                                    {% elif score.total_score >= 40 %}text-yellow-600
                                    {% else %}text-red-600{% endif %}">
                                    {{ score.total_score }}
                                </div>
                                <div class="ml-2 text-sm text-gray-500">/100</div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                                {% if score.risk_level == 'low' %}risk-low
                                {% elif score.risk_level == 'medium' %}risk-medium
                                {% else %}risk-high{% endif %}">
                                {{ score.get_risk_level_display }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                            KES {{ score.credit_limit|floatformat:0 }}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ score.updated_at|date:"M d, Y H:i" }}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <button onclick="updateSingleScore('{{ score.user.id }}')" 
                                    class="text-blue-600 hover:text-blue-900 mr-3">
                                <span>🔄</span> Update
                            </button>
                            <a href="{% url 'client_detail' score.user.id %}" 
                               class="text-green-600 hover:text-green-900">
                                <i class="fas fa-eye"></i> View
                            </a>
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="6" class="px-6 py-4 text-center text-gray-500">
                            No credit scores found.
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        {% if credit_scores.has_other_pages %}
        <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
            <div class="flex-1 flex justify-between sm:hidden">
                {% if credit_scores.has_previous %}
                    <a href="?page={{ credit_scores.previous_page_number }}" 
                       class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                        Previous
                    </a>
                {% endif %}
                {% if credit_scores.has_next %}
                    <a href="?page={{ credit_scores.next_page_number }}" 
                       class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                        Next
                    </a>
                {% endif %}
            </div>
            <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                <div>
                    <p class="text-sm text-gray-700">
                        Showing {{ credit_scores.start_index }} to {{ credit_scores.end_index }} of {{ credit_scores.paginator.count }} results
                    </p>
                </div>
                <div>
                    <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                        {% if credit_scores.has_previous %}
                            <a href="?page={{ credit_scores.previous_page_number }}" 
                               class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                                <span>‹</span>
                            </a>
                        {% endif %}
                        
                        {% for num in credit_scores.paginator.page_range %}
                            {% if credit_scores.number == num %}
                                <span class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-blue-50 text-sm font-medium text-blue-600">
                                    {{ num }}
                                </span>
                            {% else %}
                                <a href="?page={{ num }}" 
                                   class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">
                                    {{ num }}
                                </a>
                            {% endif %}
                        {% endfor %}
                        
                        {% if credit_scores.has_next %}
                            <a href="?page={{ credit_scores.next_page_number }}" 
                               class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                                <span>›</span>
                            </a>
                        {% endif %}
                    </nav>
                </div>
            </div>
        </div>
        {% endif %}
    </div>
</div>

<!-- Loading Modal -->
<div id="loadingModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-lg p-6 max-w-sm mx-auto">
        <div class="flex items-center">
            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            <div class="ml-4">
                <h3 class="text-lg font-medium text-gray-900">Updating Credit Scores</h3>
                <p class="text-sm text-gray-500">Please wait...</p>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
function showLoading() {
    document.getElementById('loadingModal').classList.remove('hidden');
    document.getElementById('loadingModal').classList.add('flex');
}

function hideLoading() {
    document.getElementById('loadingModal').classList.add('hidden');
    document.getElementById('loadingModal').classList.remove('flex');
}

function updateAllScores() {
    if (confirm('This will update credit scores for all borrowers. This may take a while. Continue?')) {
        showLoading();
        fetch('/utils/api/update-credit-scores/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({action: 'update_all'})
        })
        .then(response => response.json())
        .then(data => {
            hideLoading();
            if (data.success) {
                alert(`Successfully updated ${data.updated_count} credit scores`);
                location.reload();
            } else {
                alert('Error updating credit scores: ' + data.error);
            }
        })
        .catch(error => {
            hideLoading();
            alert('Error: ' + error);
        });
    }
}

function updateRecentActivity() {
    showLoading();
    fetch('/utils/api/update-credit-scores/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({action: 'update_recent'})
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.success) {
            alert(`Successfully updated ${data.updated_count} credit scores`);
            location.reload();
        } else {
            alert('Error updating credit scores: ' + data.error);
        }
    })
    .catch(error => {
        hideLoading();
        alert('Error: ' + error);
    });
}

function updateSingleScore(userId) {
    showLoading();
    fetch('/utils/api/update-credit-scores/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({action: 'update_single', user_id: userId})
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.success) {
            alert('Credit score updated successfully');
            location.reload();
        } else {
            alert('Error updating credit score: ' + data.error);
        }
    })
    .catch(error => {
        hideLoading();
        alert('Error: ' + error);
    });
}

function exportScores() {
    window.open('/utils/api/export-credit-scores/', '_blank');
}
</script>
{% endblock %}