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

{% block title %}Portfolio Benchmarking Dashboard{% endblock %}

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

{% block content %}
<div class="min-h-screen bg-gray-50">
    <!-- Header -->
    <div class="bg-gradient-to-r from-teal-600 to-cyan-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">
                        <i class="fas fa-bullseye text-2xl"></i>
                    </div>
                    <div>
                        <h1 class="text-3xl font-bold">Portfolio Benchmarking Dashboard</h1>
                        <p class="text-teal-100 mt-1">Compare performance across managers, branches, and time periods</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <!-- Comparison Type Filter -->
                    <div class="bg-cyan-100 bg-opacity-20 rounded-lg p-3">
                        <select id="comparisonType" class="bg-transparent text-white border-none focus:outline-none" onchange="updateComparison()">
                            <option value="branch" {% if comparison_type == 'branch' %}selected{% endif %}>By Branch</option>
                            <option value="role" {% if comparison_type == 'role' %}selected{% endif %}>By Role</option>
                            <option value="period" {% if comparison_type == 'period' %}selected{% endif %}>By Period</option>
                        </select>
                    </div>
                    <!-- Period Filter -->
                    <div class="bg-cyan-100 bg-opacity-20 rounded-lg p-3">
                        <select id="period" class="bg-transparent text-white border-none focus:outline-none" onchange="updateComparison()">
                            <option value="monthly" {% if period == 'monthly' %}selected{% endif %}>Monthly</option>
                            <option value="quarterly" {% if period == 'quarterly' %}selected{% endif %}>Quarterly</option>
                            <option value="yearly" {% if period == 'yearly' %}selected{% endif %}>Yearly</option>
                        </select>
                    </div>
                    <!-- Export Button -->
                    <button onclick="exportBenchmarkData()" class="bg-cyan-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">
        <!-- Industry Benchmarks Overview -->
        {% if industry_benchmarks %}
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="benchmark-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">Avg Performance Score</div>
                        <div class="text-2xl font-bold">{{ industry_benchmarks.avg_performance_score|floatformat:1 }}</div>
                        <div class="text-xs text-blue-200 mt-1">
                            <span class="inline-flex items-center">
                                <span>📈</span>Industry average
                            </span>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <span>⭐</span>
                    </div>
                </div>
            </div>

            <div class="benchmark-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 Efficiency Ratio</div>
                        <div class="text-2xl font-bold">{{ industry_benchmarks.avg_efficiency_ratio|floatformat:2 }}</div>
                        <div class="text-xs text-green-200 mt-1">
                            <span class="inline-flex items-center">
                                <span>⚙️</span>Operational efficiency
                            </span>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <span>⚙️</span>
                    </div>
                </div>
            </div>

            <div class="benchmark-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 Growth Rate</div>
                        <div class="text-2xl font-bold">{{ industry_benchmarks.avg_growth_rate|floatformat:1 }}%</div>
                        <div class="text-xs text-purple-200 mt-1">
                            <span class="inline-flex items-center">
                                <span>↑</span>Portfolio growth
                            </span>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <span>↑</span>
                    </div>
                </div>
            </div>

            <div class="benchmark-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">Avg Risk Score</div>
                        <div class="text-2xl font-bold">{{ industry_benchmarks.avg_risk_score|floatformat:1 }}</div>
                        <div class="text-xs text-orange-200 mt-1">
                            <span class="inline-flex items-center">
                                <i class="fas fa-shield-alt mr-1"></i>Risk assessment
                            </span>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <i class="fas fa-shield-alt text-xl"></i>
                    </div>
                </div>
            </div>
        </div>
        {% endif %}

        <!-- Benchmarking Insights -->
        {% if comparison_insights %}
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            <!-- Top Performers -->
            <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 Leaders
                    </h3>
                </div>
                <div class="p-6">
                    {% if comparison_insights.performance_leaders %}
                    <div class="space-y-4">
                        {% for leader in comparison_insights.performance_leaders|slice:":5" %}
                        <div class="flex items-center justify-between p-3 bg-green-50 rounded-lg">
                            <div class="flex items-center space-x-3">
                                <div class="w-8 h-8 bg-green-600 rounded-full flex items-center justify-center text-white font-semibold text-sm">
                                    {{ forloop.counter }}
                                </div>
                                <div>
                                    <div class="font-semibold text-gray-900">{{ leader.manager.get_full_name }}</div>
                                    <div class="text-sm text-gray-600">{{ leader.manager.get_role_display }}</div>
                                </div>
                            </div>
                            <div class="text-right">
                                <div class="font-bold text-green-600">{{ leader.performance_score|floatformat:1 }}</div>
                                <div class="text-xs text-gray-600">Score</div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    {% else %}
                    <div class="text-center py-8">
                        <span>🏆</span>
                        <p class="text-gray-500">No performance leaders data available</p>
                    </div>
                    {% endif %}
                </div>
            </div>

            <!-- Improvement Opportunities -->
            <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>
                        Improvement Opportunities
                    </h3>
                </div>
                <div class="p-6">
                    {% if comparison_insights.needs_attention %}
                    <div class="space-y-4">
                        {% for opportunity in comparison_insights.needs_attention|slice:":5" %}
                        <div class="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
                            <div class="flex items-center space-x-3">
                                <div class="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center text-white">
                                    <span>↑</span>
                                </div>
                                <div>
                                    <div class="font-semibold text-gray-900">{{ opportunity.manager.get_full_name }}</div>
                                    <div class="text-sm text-gray-600">{{ opportunity.manager.get_role_display }}</div>
                                </div>
                            </div>
                            <div class="text-right">
                                <div class="font-bold text-blue-600">{{ opportunity.performance_score|floatformat:1 }}</div>
                                <div class="text-xs text-gray-600">Score</div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    {% else %}
                    <div class="text-center py-8">
                        <span>✓</span>
                        <p class="text-gray-500">All managers performing well!</p>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
        {% endif %}

        <!-- Benchmarking Charts -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            <!-- Performance Comparison 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 Comparison
                    </h3>
                </div>
                <div class="p-6">
                    <div class="chart-container">
                        <canvas id="performanceComparisonChart"></canvas>
                    </div>
                </div>
            </div>

            <!-- Efficiency vs Risk 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">
                        <i class="fas fa-chart-scatter mr-3 text-purple-500"></i>
                        Efficiency vs Risk Analysis
                    </h3>
                </div>
                <div class="p-6">
                    <div class="chart-container">
                        <canvas id="efficiencyRiskChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- Detailed Benchmarking Results -->
        <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-gray-600"></i>
                    Detailed Benchmarking Results
                </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">Performance Score</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Efficiency Ratio</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Growth Rate</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Risk Score</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Benchmark Status</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 result in benchmarking_results %}
                        <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">
                                        {{ result.manager.first_name|first }}{{ result.manager.last_name|first }}
                                    </div>
                                    <div class="ml-3">
                                        <div class="text-sm font-medium text-gray-900">{{ result.manager.get_full_name }}</div>
                                        <div class="text-sm text-gray-500">{{ result.manager.get_role_display }}</div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="text-sm font-medium text-gray-900">{{ result.performance_score|floatformat:1 }}</div>
                                    <div class="ml-2 w-16 bg-gray-200 rounded-full h-2">
                                        <div class="bg-blue-500 h-2 rounded-full" style="width: {{ result.performance_score }}%"></div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ result.efficiency_ratio|floatformat:2 }}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ result.growth_rate|floatformat:1 }}%</td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full {% if result.risk_score < 5 %}bg-green-100 text-green-800{% elif result.risk_score < 10 %}bg-yellow-100 text-yellow-800{% else %}bg-red-100 text-red-800{% endif %}">
                                    {{ result.risk_score|floatformat:1 }}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                {% if result.performance_score >= industry_benchmarks.top_quartile_performance %}
                                <span class="metric-badge metric-excellent">Top Quartile</span>
                                {% elif result.performance_score >= industry_benchmarks.avg_performance_score %}
                                <span class="metric-badge metric-good">Above Average</span>
                                {% elif result.performance_score >= industry_benchmarks.bottom_quartile_performance %}
                                <span class="metric-badge metric-average">Below Average</span>
                                {% else %}
                                <span class="metric-badge metric-poor">Bottom Quartile</span>
                                {% endif %}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <a href="{% url 'users:portfolio_manager_detail' result.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 benchmarking data available
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
// Global chart instances
let performanceComparisonChart, efficiencyRiskChart;

// Get real data from Django context
const benchmarkChartData = {{ benchmark_chart_data|safe }};
const industryBenchmarks = {{ industry_benchmarks|safe }};

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

function initializeCharts() {
    // Performance Comparison Chart
    const perfCompCtx = document.getElementById('performanceComparisonChart').getContext('2d');
    performanceComparisonChart = new Chart(perfCompCtx, {
        type: 'bar',
        data: {
            labels: benchmarkChartData.manager_names,
            datasets: [{
                label: 'Performance Score',
                data: benchmarkChartData.performance_scores,
                backgroundColor: 'rgba(59, 130, 246, 0.8)',
                borderColor: 'rgb(59, 130, 246)',
                borderWidth: 1
            }, {
                label: 'Industry Average',
                data: Array(benchmarkChartData.manager_names.length).fill(industryBenchmarks.avg_performance_score),
                type: 'line',
                borderColor: 'rgb(239, 68, 68)',
                backgroundColor: 'rgba(239, 68, 68, 0.1)',
                borderWidth: 2,
                pointRadius: 0,
                fill: false
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top'
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100
                }
            }
        }
    });

    // Efficiency vs Risk Scatter Chart
    const effRiskCtx = document.getElementById('efficiencyRiskChart').getContext('2d');
    efficiencyRiskChart = new Chart(effRiskCtx, {
        type: 'scatter',
        data: {
            datasets: [{
                label: 'Managers',
                data: benchmarkChartData.manager_names.map((name, index) => ({
                    x: benchmarkChartData.efficiency_ratios[index],
                    y: benchmarkChartData.risk_scores[index],
                    label: name
                })),
                backgroundColor: 'rgba(168, 85, 247, 0.6)',
                borderColor: 'rgb(168, 85, 247)',
                borderWidth: 2,
                pointRadius: 8,
                pointHoverRadius: 10
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return `${context.raw.label}: Efficiency ${context.parsed.x.toFixed(2)}, Risk ${context.parsed.y.toFixed(1)}`;
                        }
                    }
                }
            },
            scales: {
                x: {
                    title: {
                        display: true,
                        text: 'Efficiency Ratio'
                    }
                },
                y: {
                    title: {
                        display: true,
                        text: 'Risk Score'
                    },
                    beginAtZero: true
                }
            }
        }
    });
}

function updateComparison() {
    const comparisonType = document.getElementById('comparisonType').value;
    const period = document.getElementById('period').value;
    
    // Reload page with new parameters
    const url = new URL(window.location);
    url.searchParams.set('type', comparisonType);
    url.searchParams.set('period', period);
    window.location.href = url.toString();
}

function exportBenchmarkData() {
    // Create comprehensive export data
    const exportData = {
        timestamp: new Date().toISOString(),
        industry_benchmarks: industryBenchmarks,
        chart_data: benchmarkChartData,
        comparison_type: '{{ comparison_type }}',
        period: '{{ period }}'
    };
    
    // 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_benchmarking_${new Date().toISOString().split('T')[0]}.json`;
    link.click();
    URL.revokeObjectURL(url);
}
</script>
{% endblock %}