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

{% block title %}Client Performance Ranking{% endblock %}

{% block extra_css %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
    .performance-card {
        transition: all 0.3s ease;
    }
    .performance-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 25px rgba(0,0,0,0.1);
    }
    .chart-container {
        position: relative;
        height: 300px;
    }
    .client-score-badge {
        display: inline-flex;
        align-items: center;
        padding: 0.25rem 0.75rem;
        border-radius: 9999px;
        font-size: 0.75rem;
        font-weight: 600;
    }
    .score-excellent { background-color: #dcfce7; color: #166534; }
    .score-good { background-color: #dbeafe; color: #1e40af; }
    .score-average { background-color: #fef3c7; color: #92400e; }
    .score-poor { background-color: #fee2e2; color: #991b1b; }
    .risk-low { background-color: #dcfce7; color: #166534; }
    .risk-medium { background-color: #fef3c7; color: #92400e; }
    .risk-high { background-color: #fee2e2; color: #991b1b; }
</style>
{% endblock %}

{% block content %}
<div class="min-h-screen bg-gray-50">
    <!-- Header -->
    <div class="bg-gradient-to-r from-indigo-600 to-purple-600 text-white py-8">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-4">
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <span>👥</span>
                    </div>
                    <div>
                        <h1 class="text-3xl font-bold">Client Performance Ranking</h1>
                        <p class="text-indigo-100 mt-1">Detailed analysis of client performance and risk assessment</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <!-- Date Range Filter -->
                    <div class="bg-purple-100 bg-opacity-20 rounded-lg p-3">
                        <select id="dateRange" class="bg-transparent text-white border-none focus:outline-none" onchange="updateClientData()">
                            <option value="7">Last 7 days</option>
                            <option value="30" {% if date_range_days == 30 %}selected{% endif %}>Last 30 days</option>
                            <option value="90" {% if date_range_days == 90 %}selected{% endif %}>Last 90 days</option>
                            <option value="365" {% if date_range_days == 365 %}selected{% endif %}>Last year</option>
                        </select>
                    </div>
                    <!-- Export Button -->
                    <button onclick="exportClientData()" class="bg-purple-100 bg-opacity-20 hover:bg-opacity-30 px-4 py-2 rounded-lg transition-all duration-200 flex items-center space-x-2">
                        <span>⬇️</span>
                        <span>Export</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="max-w-7xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
        <!-- Summary Statistics -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="performance-card bg-gradient-to-br from-blue-500 to-blue-600 text-white rounded-xl p-6 shadow-lg">
                <div class="flex items-center justify-between">
                    <div>
                        <div class="text-blue-100 text-sm font-medium">Total Clients</div>
                        <div class="text-2xl font-bold">{{ total_clients }}</div>
                        <div class="text-xs text-blue-200 mt-1">
                            <span class="inline-flex items-center">
                                <span>👥</span>Active portfolio
                            </span>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <span>👥</span>
                    </div>
                </div>
            </div>

            <div class="performance-card bg-gradient-to-br from-green-500 to-green-600 text-white rounded-xl p-6 shadow-lg">
                <div class="flex items-center justify-between">
                    <div>
                        <div class="text-green-100 text-sm font-medium">Avg Client Score</div>
                        <div class="text-2xl font-bold">{{ avg_client_score|floatformat:1 }}</div>
                        <div class="text-xs text-green-200 mt-1">
                            <span class="inline-flex items-center">
                                <span>⭐</span>Performance rating
                            </span>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <span>⭐</span>
                    </div>
                </div>
            </div>

            <div class="performance-card bg-gradient-to-br from-purple-500 to-purple-600 text-white rounded-xl p-6 shadow-lg">
                <div class="flex items-center justify-between">
                    <div>
                        <div class="text-purple-100 text-sm font-medium">Avg Repayment Rate</div>
                        <div class="text-2xl font-bold">{{ avg_repayment_rate|floatformat:1 }}%</div>
                        <div class="text-xs text-purple-200 mt-1">
                            <span class="inline-flex items-center">
                                <i class="fas fa-percentage mr-1"></i>Collection efficiency
                            </span>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <i class="fas fa-percentage text-xl"></i>
                    </div>
                </div>
            </div>

            <div class="performance-card bg-gradient-to-br from-orange-500 to-red-500 text-white rounded-xl p-6 shadow-lg">
                <div class="flex items-center justify-between">
                    <div>
                        <div class="text-orange-100 text-sm font-medium">Total Outstanding</div>
                        <div class="text-2xl font-bold">KES {{ total_outstanding|floatformat:0 }}</div>
                        <div class="text-xs text-orange-200 mt-1">
                            <span class="inline-flex items-center">
                                <span>💵</span>Portfolio value
                            </span>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <span>💵</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Performance Categories Overview -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            <!-- Performance Distribution Chart -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                        <span>📊</span>
                        Performance Distribution
                    </h3>
                </div>
                <div class="p-6">
                    <div class="chart-container">
                        <canvas id="performanceDistributionChart"></canvas>
                    </div>
                    <div class="grid grid-cols-2 gap-4 mt-4">
                        <div class="text-center">
                            <div class="text-2xl font-bold text-green-600">{{ performance_categories.excellent|length }}</div>
                            <div class="text-sm text-gray-600">Excellent (85+)</div>
                        </div>
                        <div class="text-center">
                            <div class="text-2xl font-bold text-blue-600">{{ performance_categories.good|length }}</div>
                            <div class="text-sm text-gray-600">Good (70-84)</div>
                        </div>
                        <div class="text-center">
                            <div class="text-2xl font-bold text-yellow-600">{{ performance_categories.average|length }}</div>
                            <div class="text-sm text-gray-600">Average (50-69)</div>
                        </div>
                        <div class="text-center">
                            <div class="text-2xl font-bold text-red-600">{{ performance_categories.poor|length }}</div>
                            <div class="text-sm text-gray-600">Poor (<50)</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Top Performers Chart -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                        <span>📊</span>
                        Top Performers Comparison
                    </h3>
                </div>
                <div class="p-6">
                    <div class="chart-container">
                        <canvas id="topPerformersChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- Top Performers Section -->
        {% if top_performers %}
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 mb-8">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-xl font-semibold text-gray-800 flex items-center">
                    <span>🏆</span>
                    Top Performing Clients
                </h2>
            </div>
            <div class="p-6">
                <div class="space-y-4">
                    {% for client in top_performers %}
                    <div class="flex items-center p-4 bg-gradient-to-r from-green-50 to-blue-50 rounded-lg hover:from-green-100 hover:to-blue-100 transition-colors">
                        <!-- Rank Badge -->
                        <div class="flex-shrink-0 mr-4">
                            {% if forloop.counter == 1 %}
                            <div class="w-12 h-12 bg-gradient-to-r from-yellow-400 to-yellow-500 rounded-full flex items-center justify-center text-white font-bold shadow-lg">
                                <i class="fas fa-crown text-lg"></i>
                            </div>
                            {% elif forloop.counter == 2 %}
                            <div class="w-12 h-12 bg-gradient-to-r from-gray-400 to-gray-500 rounded-full flex items-center justify-center text-white font-bold shadow-lg">
                                2
                            </div>
                            {% elif forloop.counter == 3 %}
                            <div class="w-12 h-12 bg-gradient-to-r from-orange-400 to-orange-500 rounded-full flex items-center justify-center text-white font-bold shadow-lg">
                                3
                            </div>
                            {% else %}
                            <div class="w-12 h-12 bg-gradient-to-r from-blue-400 to-blue-500 rounded-full flex items-center justify-center text-white font-bold shadow-lg">
                                {{ forloop.counter }}
                            </div>
                            {% endif %}
                        </div>

                        <!-- Client Info -->
                        <div class="flex-1">
                            <div class="flex items-center justify-between">
                                <div>
                                    <div class="flex items-center space-x-3">
                                        <h3 class="font-semibold text-gray-900">{{ client.client_name }}</h3>
                                        {% if client.client_score >= 85 %}
                                        <span class="client-score-badge score-excellent">Excellent</span>
                                        {% elif client.client_score >= 70 %}
                                        <span class="client-score-badge score-good">Good</span>
                                        {% elif client.client_score >= 50 %}
                                        <span class="client-score-badge score-average">Average</span>
                                        {% else %}
                                        <span class="client-score-badge score-poor">Poor</span>
                                        {% endif %}
                                        
                                        {% if client.risk_category == 'low' %}
                                        <span class="client-score-badge risk-low">Low Risk</span>
                                        {% elif client.risk_category == 'medium' %}
                                        <span class="client-score-badge risk-medium">Medium Risk</span>
                                        {% else %}
                                        <span class="client-score-badge risk-high">High Risk</span>
                                        {% endif %}
                                    </div>
                                    <p class="text-sm text-gray-600">
                                        <span>👔</span>
                                        Portfolio: {{ client.manager_name|default:client.manager.get_full_name }}
                                    </p>
                                </div>
                                <div class="text-right">
                                    <div class="text-2xl font-bold text-gray-900">{{ client.client_score|floatformat:1 }}</div>
                                    <div class="text-sm text-gray-600">Client Score</div>
                                </div>
                            </div>

                            <!-- Performance Metrics Grid -->
                            <div class="grid grid-cols-2 md:grid-cols-6 gap-4 mt-4">
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-blue-600">{{ client.total_loans }}</div>
                                    <div class="text-xs text-gray-600">Total Loans</div>
                                </div>
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-green-600">{{ client.active_loans }}</div>
                                    <div class="text-xs text-gray-600">Active</div>
                                </div>
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-purple-600">{{ client.repayment_rate|floatformat:1 }}%</div>
                                    <div class="text-xs text-gray-600">Repayment Rate</div>
                                </div>
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-indigo-600">KES {{ client.total_borrowed|floatformat:0 }}</div>
                                    <div class="text-xs text-gray-600">Total Borrowed</div>
                                </div>
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-orange-600">KES {{ client.outstanding_balance|floatformat:0 }}</div>
                                    <div class="text-xs text-gray-600">Outstanding</div>
                                </div>
                                <div class="text-center">
                                    <div class="text-lg font-semibold {% if client.days_since_payment > 30 %}text-red-600{% else %}text-green-600{% endif %}">{{ client.days_since_payment }}</div>
                                    <div class="text-xs text-gray-600">Days Since Payment</div>
                                </div>
                            </div>

                            <!-- Progress Bars -->
                            <div class="grid grid-cols-2 gap-4 mt-4">
                                <div>
                                    <div class="flex justify-between text-sm mb-1">
                                        <span class="text-gray-600">Repayment Rate</span>
                                        <span class="font-semibold">{{ client.repayment_rate|floatformat:1 }}%</span>
                                    </div>
                                    <div class="w-full bg-gray-200 rounded-full h-2">
                                        <div class="bg-green-500 h-2 rounded-full" style="width: {{ client.repayment_rate }}%"></div>
                                    </div>
                                </div>
                                <div>
                                    <div class="flex justify-between text-sm mb-1">
                                        <span class="text-gray-600">Client Score</span>
                                        <span class="font-semibold">{{ client.client_score|floatformat:1 }}</span>
                                    </div>
                                    <div class="w-full bg-gray-200 rounded-full h-2">
                                        <div class="bg-blue-500 h-2 rounded-full" style="width: {{ client.client_score }}%"></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Action Button -->
                        <div class="flex-shrink-0 ml-4">
                            <a href="{% url 'users:client_detail' client.client_id %}" 
                               class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-semibold transition-colors">
                                View Details
                            </a>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
        {% endif %}

        <!-- Bottom Performers Section -->
        {% if bottom_performers %}
        <div class="bg-white rounded-xl shadow-sm border border-gray-200">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-xl font-semibold text-gray-800 flex items-center">
                    <span>⚠️</span>
                    Clients Needing Attention
                </h2>
            </div>
            <div class="p-6">
                <div class="space-y-4">
                    {% for client in bottom_performers %}
                    <div class="flex items-center p-4 bg-gradient-to-r from-red-50 to-orange-50 rounded-lg hover:from-red-100 hover:to-orange-100 transition-colors">
                        <!-- Warning Icon -->
                        <div class="flex-shrink-0 mr-4">
                            <div class="w-12 h-12 bg-gradient-to-r from-red-400 to-red-500 rounded-full flex items-center justify-center text-white shadow-lg">
                                <span>⚠️</span>
                            </div>
                        </div>

                        <!-- Client Info -->
                        <div class="flex-1">
                            <div class="flex items-center justify-between">
                                <div>
                                    <div class="flex items-center space-x-3">
                                        <h3 class="font-semibold text-gray-900">{{ client.client_name }}</h3>
                                        <span class="client-score-badge score-poor">Needs Attention</span>
                                        <span class="client-score-badge risk-high">High Risk</span>
                                    </div>
                                    <p class="text-sm text-gray-600">
                                        <span>👔</span>
                                        Portfolio: {{ client.manager_name|default:client.manager.get_full_name }}
                                    </p>
                                </div>
                                <div class="text-right">
                                    <div class="text-2xl font-bold text-red-600">{{ client.client_score|floatformat:1 }}</div>
                                    <div class="text-sm text-gray-600">Client Score</div>
                                </div>
                            </div>

                            <!-- Key Issues -->
                            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-4">
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-red-600">{{ client.repayment_rate|floatformat:1 }}%</div>
                                    <div class="text-xs text-gray-600">Repayment Rate</div>
                                </div>
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-orange-600">KES {{ client.outstanding_balance|floatformat:0 }}</div>
                                    <div class="text-xs text-gray-600">Outstanding</div>
                                </div>
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-red-600">{{ client.days_since_payment }}</div>
                                    <div class="text-xs text-gray-600">Days Since Payment</div>
                                </div>
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-purple-600">{{ client.default_history }}</div>
                                    <div class="text-xs text-gray-600">Default History</div>
                                </div>
                            </div>
                        </div>

                        <!-- Action Button -->
                        <div class="flex-shrink-0 ml-4">
                            <a href="{% url 'users:client_detail' client.client_id %}" 
                               class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg text-sm font-semibold transition-colors">
                                Take Action
                            </a>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
        {% endif %}
    </div>
</div>

<script>
// Global chart instances
let performanceDistributionChart, topPerformersChart;

// Get real data from Django context
const clientChartData = {{ client_chart_data|safe }};
const performanceCategories = {
    excellent: {{ performance_categories.excellent|length }},
    good: {{ performance_categories.good|length }},
    average: {{ performance_categories.average|length }},
    poor: {{ performance_categories.poor|length }}
};

document.addEventListener('DOMContentLoaded', function() {
    initializeCharts();
});

function initializeCharts() {
    // Performance Distribution Chart
    const perfDistCtx = document.getElementById('performanceDistributionChart').getContext('2d');
    performanceDistributionChart = new Chart(perfDistCtx, {
        type: 'doughnut',
        data: {
            labels: ['Excellent', 'Good', 'Average', 'Poor'],
            datasets: [{
                data: [
                    performanceCategories.excellent,
                    performanceCategories.good,
                    performanceCategories.average,
                    performanceCategories.poor
                ],
                backgroundColor: [
                    'rgb(34, 197, 94)',
                    'rgb(59, 130, 246)',
                    'rgb(251, 191, 36)',
                    'rgb(239, 68, 68)'
                ],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });

    // Top Performers Chart
    const topPerfCtx = document.getElementById('topPerformersChart').getContext('2d');
    topPerformersChart = new Chart(topPerfCtx, {
        type: 'bar',
        data: {
            labels: clientChartData.client_names,
            datasets: [{
                label: 'Client Score',
                data: clientChartData.client_scores,
                backgroundColor: 'rgba(59, 130, 246, 0.8)',
                borderColor: 'rgb(59, 130, 246)',
                borderWidth: 1
            }, {
                label: 'Repayment Rate (%)',
                data: clientChartData.repayment_rates,
                backgroundColor: 'rgba(34, 197, 94, 0.8)',
                borderColor: 'rgb(34, 197, 94)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top'
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100
                }
            }
        }
    });
}

function updateClientData() {
    const dateRange = document.getElementById('dateRange').value;
    
    // Reload page with new date range
    const url = new URL(window.location);
    url.searchParams.set('days', dateRange);
    window.location.href = url.toString();
}

function exportClientData() {
    // Create export data
    const exportData = {
        timestamp: new Date().toISOString(),
        summary: {
            total_clients: {{ total_clients }},
            avg_client_score: {{ avg_client_score|floatformat:1 }},
            avg_repayment_rate: {{ avg_repayment_rate|floatformat:1 }},
            total_outstanding: {{ total_outstanding|floatformat:0 }}
        },
        performance_categories: performanceCategories,
        chart_data: clientChartData
    };
    
    // Download as JSON
    const dataStr = JSON.stringify(exportData, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `client_performance_ranking_${new Date().toISOString().split('T')[0]}.json`;
    link.click();
    URL.revokeObjectURL(url);
}
</script>
{% endblock %}