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

{% block title %}Portfolio Analytics{% endblock %}

{% block extra_css %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
    .metric-card {
        transition: all 0.3s ease;
    }
    .metric-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 25px rgba(0,0,0,0.1);
    }
    .chart-container {
        position: relative;
        height: 300px;
    }
</style>
{% endblock %}

{% block content %}
<div class="min-h-screen bg-gray-50">
    <!-- Enhanced Header -->
    <div class="bg-gradient-to-r from-purple-600 to-blue-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">Portfolio Analytics</h1>
                        <p class="text-purple-100 mt-1">Comprehensive performance analysis and insights</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <!-- Date Range Filter -->
                    <div class="bg-blue-100 bg-opacity-20 rounded-lg p-3">
                        <select id="dateRange" class="bg-transparent text-white border-none focus:outline-none">
                            <option value="7">Last 7 days</option>
                            <option value="30" selected>Last 30 days</option>
                            <option value="90">Last 90 days</option>
                            <option value="365">Last year</option>
                        </select>
                    </div>
                    <!-- Export Button -->
                    <button onclick="exportAnalytics()" class="bg-blue-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>
                    <!-- Refresh Button -->
                    <button onclick="refreshData()" class="bg-blue-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>Refresh</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="max-w-7xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
        <!-- Enhanced Key Metrics Overview -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="metric-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 Portfolio Value</div>
                        <div class="text-2xl font-bold" id="portfolioValue">KES {{ total_portfolio_value|floatformat:0|default:"0" }}</div>
                        <div class="text-xs text-blue-200 mt-1">
                            <span id="portfolioChange" class="inline-flex items-center">
                                <span>↑</span>+12.5% vs last month
                            </span>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <span>💵</span>
                    </div>
                </div>
            </div>

            <div class="metric-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">Active Managers</div>
                        <div class="text-2xl font-bold" id="totalManagers">{{ total_managers|default:"0" }}</div>
                        <div class="text-xs text-green-200 mt-1">
                            <span class="inline-flex items-center">
                                <span>👤+</span>{{ total_managers|default:"0" }} active
                            </span>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <span>👥</span>
                    </div>
                </div>
            </div>

            <div class="metric-card bg-gradient-to-br from-yellow-500 to-orange-500 text-white rounded-xl p-6 shadow-lg">
                <div class="flex items-center justify-between">
                    <div>
                        <div class="text-yellow-100 text-sm font-medium">Avg Collection Rate</div>
                        <div class="text-2xl font-bold" id="collectionRate">{{ avg_collection_rate|floatformat:1|default:"0" }}%</div>
                        <div class="text-xs text-yellow-200 mt-1">
                            <span id="collectionTrend" class="inline-flex items-center">
                                <span>↑</span>+2.3% improvement
                            </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="metric-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">Total Clients</div>
                        <div class="text-2xl font-bold" id="totalClients">{{ total_clients|default:"0" }}</div>
                        <div class="text-xs text-purple-200 mt-1">
                            <span class="inline-flex items-center">
                                <i class="fas fa-user-friends mr-1"></i>Across all managers
                            </span>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <i class="fas fa-user-friends text-xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Performance Rankings -->
        <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>
                    Portfolio Manager Rankings
                </h2>
            </div>
            <div class="p-6">
                {% if manager_rankings %}
                <div class="space-y-4">
                    {% for manager in manager_rankings %}
                    <div class="flex items-center p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                        <!-- Rank Badge -->
                        <div class="flex-shrink-0 mr-4">
                            {% if forloop.counter == 1 %}
                            <div class="w-10 h-10 bg-gradient-to-r from-yellow-400 to-yellow-500 rounded-full flex items-center justify-center text-white font-bold">
                                <i class="fas fa-crown"></i>
                            </div>
                            {% elif forloop.counter == 2 %}
                            <div class="w-10 h-10 bg-gradient-to-r from-gray-400 to-gray-500 rounded-full flex items-center justify-center text-white font-bold">
                                2
                            </div>
                            {% elif forloop.counter == 3 %}
                            <div class="w-10 h-10 bg-gradient-to-r from-orange-400 to-orange-500 rounded-full flex items-center justify-center text-white font-bold">
                                3
                            </div>
                            {% else %}
                            <div class="w-10 h-10 bg-gradient-to-r from-blue-400 to-blue-500 rounded-full flex items-center justify-center text-white font-bold">
                                {{ forloop.counter }}
                            </div>
                            {% endif %}
                        </div>

                        <!-- Manager Info -->
                        <div class="flex-1">
                            <div class="flex items-center justify-between">
                                <div>
                                    <h3 class="font-semibold text-gray-900">{{ manager.manager.get_full_name }}</h3>
                                    <p class="text-sm text-gray-600">{{ manager.manager.get_role_display }}</p>
                                </div>
                                <div class="text-right">
                                    <div class="text-lg font-bold text-gray-900">{{ manager.performance_score|floatformat:1 }}</div>
                                    <div class="text-sm text-gray-600">Performance Score</div>
                                </div>
                            </div>

                            <!-- Performance Metrics -->
                            <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-blue-600">{{ manager.total_clients }}</div>
                                    <div class="text-xs text-gray-600">Clients</div>
                                </div>
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-green-600">{{ manager.active_loans }}</div>
                                    <div class="text-xs text-gray-600">Active Loans</div>
                                </div>
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-purple-600">{{ manager.collection_rate|floatformat:1 }}%</div>
                                    <div class="text-xs text-gray-600">Collection Rate</div>
                                </div>
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-orange-600">KES {{ manager.total_disbursed|floatformat:0 }}</div>
                                    <div class="text-xs text-gray-600">Disbursed</div>
                                </div>
                            </div>
                        </div>

                        <!-- Action Button -->
                        <div class="flex-shrink-0 ml-4">
                            <a href="{% url 'users:portfolio_manager_detail' manager.manager.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>
                {% else %}
                <div class="text-center py-12">
                    <div class="w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <span>📈</span>
                    </div>
                    <h3 class="text-lg font-semibold text-gray-900 mb-2">No Analytics Data</h3>
                    <p class="text-gray-600">No portfolio manager data available for analysis.</p>
                </div>
                {% endif %}
            </div>
        </div>

        <!-- Enhanced Performance Charts Section -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            <!-- Collection Rate Trends -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200">
                <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
                    <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                        <span>📈</span>
                        Collection Rate Trends
                    </h3>
                    <div class="flex space-x-2">
                        <button onclick="toggleChartType('collection')" class="text-sm text-gray-500 hover:text-gray-700">
                            <i class="fas fa-exchange-alt"></i>
                        </button>
                    </div>
                </div>
                <div class="p-6">
                    <div class="chart-container">
                        <canvas id="collectionTrendChart"></canvas>
                    </div>
                </div>
            </div>

            <!-- Portfolio Distribution -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200">
                <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
                    <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                        <span>📊</span>
                        Portfolio Distribution
                    </h3>
                    <div class="flex space-x-2">
                        <button onclick="toggleChartType('distribution')" class="text-sm text-gray-500 hover:text-gray-700">
                            <i class="fas fa-exchange-alt"></i>
                        </button>
                    </div>
                </div>
                <div class="p-6">
                    <div class="chart-container">
                        <canvas id="distributionChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- Performance Comparison Chart -->
        <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">
                <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                    <span>📊</span>
                    Manager Performance Comparison
                </h3>
            </div>
            <div class="p-6">
                <div class="chart-container" style="height: 400px;">
                    <canvas id="performanceChart"></canvas>
                </div>
            </div>
        </div>

        <!-- Detailed Analytics Table -->
        <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">
                    <i class="fas fa-table mr-3 text-blue-500"></i>
                    Detailed Performance Metrics
                </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">Manager</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Clients</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Active Loans</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Collection Rate</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Default Rate</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Total Disbursed</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 manager in manager_rankings %}
                        <tr class="hover:bg-gray-50">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center text-white font-semibold text-sm">
                                        {{ manager.manager.first_name|first }}{{ manager.manager.last_name|first }}
                                    </div>
                                    <div class="ml-3">
                                        <div class="text-sm font-medium text-gray-900">{{ manager.manager.get_full_name }}</div>
                                        <div class="text-sm text-gray-500">{{ manager.manager.get_role_display }}</div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ manager.total_clients }}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ manager.active_loans }}</td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="text-sm font-medium text-gray-900">{{ manager.collection_rate|floatformat:1 }}%</div>
                                    <div class="ml-2 w-16 bg-gray-200 rounded-full h-2">
                                        <div class="bg-green-500 h-2 rounded-full" style="width: {{ manager.collection_rate }}%"></div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full {% if manager.default_rate < 5 %}bg-green-100 text-green-800{% elif manager.default_rate < 10 %}bg-yellow-100 text-yellow-800{% else %}bg-red-100 text-red-800{% endif %}">
                                    {{ manager.default_rate|floatformat:1 }}%
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">KES {{ manager.total_disbursed|floatformat:0 }}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <a href="{% url 'users:portfolio_manager_detail' manager.manager.id %}" 
                                   class="text-blue-600 hover:text-blue-900">View Details</a>
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="7" class="px-6 py-4 text-center text-sm text-gray-500">
                                No portfolio managers found
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
// Global chart instances
let collectionChart, distributionChart, performanceChart;

// Get real data from Django context
const chartData = {{ chart_data|safe }};

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

function initializeCharts() {
    // Collection Rate Trends Chart - Use real data
    const collectionCtx = document.getElementById('collectionTrendChart').getContext('2d');
    collectionChart = new Chart(collectionCtx, {
        type: 'line',
        data: {
            labels: chartData.manager_names,
            datasets: [{
                label: 'Collection Rate (%)',
                data: chartData.collection_rates,
                borderColor: 'rgb(34, 197, 94)',
                backgroundColor: 'rgba(34, 197, 94, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: false,
                    min: 0,
                    max: 100
                }
            }
        }
    });

    // Portfolio Distribution Chart - Use real data
    const distributionCtx = document.getElementById('distributionChart').getContext('2d');
    distributionChart = new Chart(distributionCtx, {
        type: 'doughnut',
        data: {
            labels: chartData.manager_names,
            datasets: [{
                data: chartData.client_counts,
                backgroundColor: [
                    'rgb(59, 130, 246)',
                    'rgb(34, 197, 94)',
                    'rgb(168, 85, 247)',
                    'rgb(249, 115, 22)',
                    'rgb(239, 68, 68)',
                    'rgb(156, 163, 175)'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });

    // Performance Comparison Chart - Use real data
    const performanceCtx = document.getElementById('performanceChart').getContext('2d');
    performanceChart = new Chart(performanceCtx, {
        type: 'bar',
        data: {
            labels: chartData.manager_names,
            datasets: [{
                label: 'Collection Rate (%)',
                data: chartData.collection_rates,
                backgroundColor: 'rgba(34, 197, 94, 0.8)'
            }, {
                label: 'Portfolio Size (KES)',
                data: chartData.disbursed_amounts.map(amount => amount / 1000), // Convert to thousands
                backgroundColor: 'rgba(59, 130, 246, 0.8)',
                yAxisID: 'y1'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    type: 'linear',
                    display: true,
                    position: 'left',
                    beginAtZero: true,
                    max: 100,
                    title: {
                        display: true,
                        text: 'Collection Rate (%)'
                    }
                },
                y1: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: 'Portfolio Size (K)'
                    },
                    grid: {
                        drawOnChartArea: false,
                    },
                }
            }
        }
    });
}

function loadAnalyticsData() {
    // Remove fake data generation - use real Django data
    const dateRange = document.getElementById('dateRange').value;
    
    // Show loading state
    showLoadingState();
    
    // In a real implementation, you would make an AJAX call here
    // For now, we'll just hide the loading state
    setTimeout(() => {
        hideLoadingState();
    }, 500);
}

function updateMetrics() {
    // Remove fake metric updates - metrics are now populated from Django context
    // The metrics are already displayed correctly from the server-side data
}

function updateCharts() {
    // Remove fake chart updates - charts now use real data from Django context
    // Charts are initialized with real data and don't need fake updates
}

function animateValue(elementId, start, end, duration, formatter = null) {
    const element = document.getElementById(elementId);
    const range = end - start;
    const increment = range / (duration / 16);
    let current = start;
    
    const timer = setInterval(() => {
        current += increment;
        if (current >= end) {
            current = end;
            clearInterval(timer);
        }
        element.textContent = formatter ? formatter(Math.floor(current)) : Math.floor(current);
    }, 16);
}

function toggleChartType(chartType) {
    if (chartType === 'collection') {
        collectionChart.config.type = collectionChart.config.type === 'line' ? 'bar' : 'line';
        collectionChart.update();
    } else if (chartType === 'distribution') {
        distributionChart.config.type = distributionChart.config.type === 'doughnut' ? 'pie' : 'doughnut';
        distributionChart.update();
    }
}

function refreshData() {
    const refreshIcon = document.getElementById('refreshIcon');
    refreshIcon.classList.add('fa-spin');
    
    loadAnalyticsData();
    
    setTimeout(() => {
        refreshIcon.classList.remove('fa-spin');
    }, 2000);
}

function exportAnalytics() {
    // Create export data
    const exportData = {
        timestamp: new Date().toISOString(),
        metrics: {
            portfolioValue: document.getElementById('portfolioValue').textContent,
            totalManagers: document.getElementById('totalManagers').textContent,
            collectionRate: document.getElementById('collectionRate').textContent,
            totalClients: document.getElementById('totalClients').textContent
        }
    };
    
    // 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 = `portfolio_analytics_${new Date().toISOString().split('T')[0]}.json`;
    link.click();
    URL.revokeObjectURL(url);
}

function showLoadingState() {
    // Add loading indicators to metric cards
    document.querySelectorAll('.metric-card').forEach(card => {
        card.style.opacity = '0.7';
    });
}

function hideLoadingState() {
    document.querySelectorAll('.metric-card').forEach(card => {
        card.style.opacity = '1';
    });
}
</script>
{% endblock %}