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

{% block title %}Loan Officer Performance Dashboard{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.css">
<style>
    .performance-card {
        background: white;
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        padding: 20px;
        margin-bottom: 20px;
        transition: transform 0.2s;
    }
    
    .performance-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    }
    
    .officer-card {
        border: 1px solid #e9ecef;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
        background: white;
    }
    
    .officer-header {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #e9ecef;
    }
    
    .officer-avatar {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 1.5rem;
        font-weight: bold;
        margin-right: 15px;
    }
    
    .officer-info h5 {
        margin: 0;
        color: #333;
    }
    
    .officer-info .text-muted {
        font-size: 0.9rem;
    }
    
    .performance-metrics {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 15px;
        margin: 20px 0;
    }
    
    .metric-item {
        text-align: center;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 8px;
    }
    
    .metric-value {
        font-size: 1.8rem;
        font-weight: bold;
        color: #007bff;
        margin-bottom: 5px;
    }
    
    .metric-label {
        font-size: 0.9rem;
        color: #6c757d;
    }
    
    .performance-indicator {
        display: inline-flex;
        align-items: center;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 0.8rem;
        font-weight: 500;
        margin-left: 10px;
    }
    
    .indicator-excellent {
        background: #d4edda;
        color: #155724;
    }
    
    .indicator-good {
        background: #d1ecf1;
        color: #0c5460;
    }
    
    .indicator-average {
        background: #fff3cd;
        color: #856404;
    }
    
    .indicator-poor {
        background: #f8d7da;
        color: #721c24;
    }
    
    .ranking-badge {
        background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
        color: #333;
        padding: 5px 10px;
        border-radius: 15px;
        font-size: 0.8rem;
        font-weight: bold;
        margin-left: 10px;
    }
    
    .trend-chart {
        height: 300px;
        margin: 20px 0;
    }
    
    .comparison-table {
        margin-top: 20px;
    }
    
    .comparison-table th {
        background: #f8f9fa;
        border-top: none;
        font-weight: 600;
        color: #495057;
    }
    
    .filter-section {
        background: #f8f9fa;
        padding: 20px;
        border-radius: 10px;
        margin-bottom: 20px;
    }
    
    .summary-stats {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
    }
    
    .summary-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: 20px;
    }
    
    .summary-item {
        text-align: center;
    }
    
    .summary-value {
        font-size: 2rem;
        font-weight: bold;
        margin-bottom: 5px;
    }
    
    .summary-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="h3 mb-0">Loan Officer Performance Dashboard</h1>
                <div>
                    <button class="btn btn-outline-primary" onclick="exportData('officer', 'excel')">
                        <span>📊</span> Export Performance Data
                    </button>
                    <button class="btn btn-outline-success" onclick="refreshData()">
                        <span>🔄</span> Refresh Data
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters Section -->
    <div class="row">
        <div class="col-12">
            <div class="filter-section">
                <h5><span>🔍</span> Filters</h5>
                <form method="GET" id="filterForm">
                    <div class="row">
                        <div class="col-md-4">
                            <label for="officer_id" class="form-label">Loan Officer</label>
                            <select name="officer_id" id="officer_id" class="form-select">
                                <option value="">All Officers</option>
                                {% for officer in officers %}
                                <option value="{{ officer.id }}" {% if officer.id|stringformat:"s" == selected_officer %}selected{% endif %}>
                                    {{ officer.get_full_name }} ({{ officer.get_role_display }})
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="period" class="form-label">Period</label>
                            <select name="period" id="period" class="form-select">
                                <option value="monthly" {% if selected_period == 'monthly' %}selected{% endif %}>Monthly</option>
                                <option value="quarterly" {% if selected_period == 'quarterly' %}selected{% endif %}>Quarterly</option>
                                <option value="yearly" {% if selected_period == 'yearly' %}selected{% endif %}>Yearly</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="months" class="form-label">Months to Analyze</label>
                            <select name="months" id="months" class="form-select">
                                <option value="3" {% if selected_months == 3 %}selected{% endif %}>3 Months</option>
                                <option value="6" {% if selected_months == 6 %}selected{% endif %}>6 Months</option>
                                <option value="12" {% if selected_months == 12 %}selected{% endif %}>12 Months</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">&nbsp;</label>
                            <div>
                                <button type="submit" class="btn btn-primary">
                                    <span>🔍</span> Apply
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Summary Statistics -->
    <div class="row">
        <div class="col-12">
            <div class="summary-stats">
                <h5><span>📊</span> Overall Performance Summary</h5>
                <div class="summary-grid">
                    <div class="summary-item">
                        <div class="summary-value">{{ performance_data.officers_analyzed }}</div>
                        <div class="summary-label">Officers Analyzed</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-value">{{ performance_data.summary.total_clients|floatformat:0 }}</div>
                        <div class="summary-label">Total Clients</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-value">{{ performance_data.summary.total_loans|floatformat:0 }}</div>
                        <div class="summary-label">Total Loans</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-value">KES {{ performance_data.summary.total_disbursed|floatformat:0 }}</div>
                        <div class="summary-label">Total Disbursed</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-value">{{ performance_data.summary.avg_collection_rate|floatformat:1 }}%</div>
                        <div class="summary-label">Avg Collection Rate</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-value">{{ performance_data.summary.avg_default_rate|floatformat:1 }}%</div>
                        <div class="summary-label">Avg Default Rate</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Individual Officer Performance -->
    <div class="row">
        <div class="col-12">
            {% for officer in performance_data.performance_data %}
            <div class="officer-card">
                <div class="officer-header">
                    <div class="officer-avatar">
                        {{ officer.officer_name|slice:":2"|upper }}
                    </div>
                    <div class="officer-info">
                        <h5>{{ officer.officer_name }}
                            {% if officer.rankings %}
                            <span class="ranking-badge">
                                Rank #{{ officer.rankings.collection_rate_rank }} of {{ officer.rankings.total_officers }}
                            </span>
                            {% endif %}
                        </h5>
                        <div class="text-muted">{{ officer.officer_role|title }} - {{ officer.branch }}</div>
                    </div>
                </div>

                <!-- Performance Metrics -->
                <div class="performance-metrics">
                    <div class="metric-item">
                        <div class="metric-value">{{ officer.portfolio_metrics.total_clients }}</div>
                        <div class="metric-label">Total Clients</div>
                    </div>
                    <div class="metric-item">
                        <div class="metric-value">{{ officer.portfolio_metrics.active_loans }}</div>
                        <div class="metric-label">Active Loans</div>
                    </div>
                    <div class="metric-item">
                        <div class="metric-value">KES {{ officer.financial_metrics.total_disbursed|floatformat:0 }}</div>
                        <div class="metric-label">Total Disbursed</div>
                    </div>
                    <div class="metric-item">
                        <div class="metric-value">{{ officer.performance_ratios.collection_rate|floatformat:1 }}%
                            {% if officer.performance_ratios.collection_rate >= 90 %}
                            <span class="performance-indicator indicator-excellent">Excellent</span>
                            {% elif officer.performance_ratios.collection_rate >= 80 %}
                            <span class="performance-indicator indicator-good">Good</span>
                            {% elif officer.performance_ratios.collection_rate >= 70 %}
                            <span class="performance-indicator indicator-average">Average</span>
                            {% else %}
                            <span class="performance-indicator indicator-poor">Needs Improvement</span>
                            {% endif %}
                        </div>
                        <div class="metric-label">Collection Rate</div>
                    </div>
                    <div class="metric-item">
                        <div class="metric-value">{{ officer.performance_ratios.default_rate|floatformat:1 }}%
                            {% if officer.performance_ratios.default_rate <= 5 %}
                            <span class="performance-indicator indicator-excellent">Excellent</span>
                            {% elif officer.performance_ratios.default_rate <= 10 %}
                            <span class="performance-indicator indicator-good">Good</span>
                            {% elif officer.performance_ratios.default_rate <= 15 %}
                            <span class="performance-indicator indicator-average">Average</span>
                            {% else %}
                            <span class="performance-indicator indicator-poor">High Risk</span>
                            {% endif %}
                        </div>
                        <div class="metric-label">Default Rate</div>
                    </div>
                    <div class="metric-item">
                        <div class="metric-value">{{ officer.performance_ratios.approval_rate|floatformat:1 }}%</div>
                        <div class="metric-label">Approval Rate</div>
                    </div>
                </div>

                <!-- Monthly Trend Chart -->
                <div class="trend-chart">
                    <canvas id="trendChart{{ forloop.counter }}"></canvas>
                </div>

                <!-- Additional Metrics -->
                <div class="row mt-3">
                    <div class="col-md-6">
                        <h6>Portfolio Quality</h6>
                        <div class="progress mb-2">
                            <div class="progress-bar bg-success" role="progressbar" 
                                 style="width: {{ officer.performance_ratios.collection_rate }}%">
                                Collection Rate: {{ officer.performance_ratios.collection_rate|floatformat:1 }}%
                            </div>
                        </div>
                        <div class="progress mb-2">
                            <div class="progress-bar bg-warning" role="progressbar" 
                                 style="width: {{ officer.performance_ratios.par_ratio }}%">
                                PAR Ratio: {{ officer.performance_ratios.par_ratio|floatformat:1 }}%
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <h6>Client Growth</h6>
                        <p><strong>New Clients (Period):</strong> {{ officer.portfolio_metrics.new_clients_period }}</p>
                        <p><strong>Average Loan Size:</strong> KES {{ officer.financial_metrics.avg_loan_size|floatformat:2 }}</p>
                        <p><strong>Outstanding Amount:</strong> KES {{ officer.financial_metrics.total_outstanding|floatformat:2 }}</p>
                    </div>
                </div>
            </div>
            {% empty %}
            <div class="performance-card text-center">
                <span>👥</span>
                <h5>No Performance Data Available</h5>
                <p class="text-muted">No loan officers found matching the selected criteria.</p>
            </div>
            {% endfor %}
        </div>
    </div>

    <!-- Comparison Table -->
    {% if performance_data.performance_data|length > 1 %}
    <div class="row">
        <div class="col-12">
            <div class="performance-card">
                <h5><i class="fas fa-table"></i> Officer Performance Comparison</h5>
                <div class="table-responsive">
                    <table class="table table-hover comparison-table">
                        <thead>
                            <tr>
                                <th>Officer</th>
                                <th>Branch</th>
                                <th>Clients</th>
                                <th>Active Loans</th>
                                <th>Total Disbursed</th>
                                <th>Collection Rate</th>
                                <th>Default Rate</th>
                                <th>PAR Ratio</th>
                                <th>Approval Rate</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for officer in performance_data.performance_data %}
                            <tr>
                                <td>
                                    <strong>{{ officer.officer_name }}</strong>
                                    <br><small class="text-muted">{{ officer.officer_role|title }}</small>
                                </td>
                                <td>{{ officer.branch }}</td>
                                <td>{{ officer.portfolio_metrics.total_clients }}</td>
                                <td>{{ officer.portfolio_metrics.active_loans }}</td>
                                <td>KES {{ officer.financial_metrics.total_disbursed|floatformat:0 }}</td>
                                <td>
                                    <span class="{% if officer.performance_ratios.collection_rate >= 90 %}text-success{% elif officer.performance_ratios.collection_rate >= 80 %}text-info{% elif officer.performance_ratios.collection_rate >= 70 %}text-warning{% else %}text-danger{% endif %}">
                                        {{ officer.performance_ratios.collection_rate|floatformat:1 }}%
                                    </span>
                                </td>
                                <td>
                                    <span class="{% if officer.performance_ratios.default_rate <= 5 %}text-success{% elif officer.performance_ratios.default_rate <= 10 %}text-info{% elif officer.performance_ratios.default_rate <= 15 %}text-warning{% else %}text-danger{% endif %}">
                                        {{ officer.performance_ratios.default_rate|floatformat:1 }}%
                                    </span>
                                </td>
                                <td>{{ officer.performance_ratios.par_ratio|floatformat:1 }}%</td>
                                <td>{{ officer.performance_ratios.approval_rate|floatformat:1 }}%</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
// Chart.js configuration
Chart.defaults.font.family = "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif";
Chart.defaults.color = '#6c757d';

// Create trend charts for each officer
{% for officer in performance_data.performance_data %}
const trendCtx{{ forloop.counter }} = document.getElementById('trendChart{{ forloop.counter }}').getContext('2d');
const trendChart{{ forloop.counter }} = new Chart(trendCtx{{ forloop.counter }}, {
    type: 'line',
    data: {
        labels: {{ officer.monthly_trends|safe }}.map(item => item.month),
        datasets: [{
            label: 'Loans Disbursed',
            data: {{ officer.monthly_trends|safe }}.map(item => item.loans_disbursed),
            borderColor: '#007bff',
            backgroundColor: 'rgba(0, 123, 255, 0.1)',
            tension: 0.4,
            yAxisID: 'y'
        }, {
            label: 'Amount Disbursed (KES)',
            data: {{ officer.monthly_trends|safe }}.map(item => item.amount_disbursed),
            borderColor: '#28a745',
            backgroundColor: 'rgba(40, 167, 69, 0.1)',
            tension: 0.4,
            yAxisID: 'y1'
        }, {
            label: 'New Clients',
            data: {{ officer.monthly_trends|safe }}.map(item => item.new_clients),
            borderColor: '#ffc107',
            backgroundColor: 'rgba(255, 193, 7, 0.1)',
            tension: 0.4,
            yAxisID: 'y'
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            title: {
                display: true,
                text: '{{ officer.officer_name }} - Monthly Performance Trends'
            },
            legend: {
                position: 'top'
            }
        },
        scales: {
            y: {
                type: 'linear',
                display: true,
                position: 'left',
                beginAtZero: true,
                ticks: {
                    precision: 0
                }
            },
            y1: {
                type: 'linear',
                display: true,
                position: 'right',
                beginAtZero: true,
                grid: {
                    drawOnChartArea: false,
                },
                ticks: {
                    callback: function(value) {
                        return 'KES ' + value.toLocaleString();
                    }
                }
            }
        }
    }
});
{% endfor %}

// Export functionality
function exportData(type, format) {
    const params = new URLSearchParams(window.location.search);
    params.set('type', type);
    params.set('format', format);
    
    window.open(`{% url 'users:export_analytics_data' %}?${params.toString()}`, '_blank');
}

// Refresh data
function refreshData() {
    location.reload();
}

// Auto-refresh every 10 minutes
setInterval(function() {
    location.reload();
}, 600000);
</script>
{% endblock %}