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

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

{% block extra_css %}
<link href="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.css" rel="stylesheet">
<style>
    .health-score-badge {
        font-size: 1.2em;
        font-weight: bold;
        padding: 0.5rem 1rem;
        border-radius: 0.5rem;
    }
    .health-critical { background-color: #dc3545; color: white; }
    .health-warning { background-color: #ffc107; color: black; }
    .health-good { background-color: #28a745; color: white; }
    .health-excellent { background-color: #007bff; color: white; }
    
    .metric-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 1rem;
        padding: 1.5rem;
        margin-bottom: 1rem;
    }
    
    .metric-value {
        font-size: 2.5rem;
        font-weight: bold;
        margin-bottom: 0.5rem;
    }
    
    .metric-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }
    
    .portfolio-card {
        border: 1px solid #e0e0e0;
        border-radius: 0.5rem;
        padding: 1rem;
        margin-bottom: 1rem;
        transition: box-shadow 0.3s ease;
    }
    
    .portfolio-card:hover {
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    
    .alert-item {
        border-left: 4px solid;
        padding: 0.75rem;
        margin-bottom: 0.5rem;
        border-radius: 0.25rem;
    }
    
    .alert-critical { border-left-color: #dc3545; background-color: #f8d7da; }
    .alert-warning { border-left-color: #ffc107; background-color: #fff3cd; }
    .alert-info { border-left-color: #17a2b8; background-color: #d1ecf1; }
</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">Portfolio Snapshot Dashboard</h1>
                <div>
                    <span class="text-muted">Last Updated: {{ today|date:"M d, Y" }}</span>
                    {% if user.role == 'admin' %}
                    <a href="{% url 'generate_snapshot_manual' %}" class="btn btn-primary ms-3">
                        <span>🔄</span> Generate Snapshots
                    </a>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <!-- Summary Statistics -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="metric-card">
                <div class="metric-value">{{ summary_stats.total_clients|floatformat:0 }}</div>
                <div class="metric-label">Total Clients</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="metric-card">
                <div class="metric-value">{{ summary_stats.total_active_loans|floatformat:0 }}</div>
                <div class="metric-label">Active Loans</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="metric-card">
                <div class="metric-value">KES {{ summary_stats.total_outstanding|floatformat:0 }}</div>
                <div class="metric-label">Total Outstanding</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="metric-card">
                <div class="metric-value">{{ summary_stats.avg_health_score }}%</div>
                <div class="metric-label">Avg Health Score</div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Portfolio Managers Overview -->
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">Portfolio Managers Overview</h5>
                </div>
                <div class="card-body">
                    {% if latest_snapshots %}
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Manager</th>
                                        <th>Branch</th>
                                        <th>Clients</th>
                                        <th>Active Loans</th>
                                        <th>Health Score</th>
                                        <th>Growth Rate</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for item in latest_snapshots %}
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="avatar-sm me-2">
                                                    <div class="avatar-title bg-primary rounded-circle">
                                                        {{ item.manager.first_name|first }}{{ item.manager.last_name|first }}
                                                    </div>
                                                </div>
                                                <div>
                                                    <h6 class="mb-0">{{ item.manager.get_full_name }}</h6>
                                                    <small class="text-muted">{{ item.manager.get_role_display }}</small>
                                                </div>
                                            </div>
                                        </td>
                                        <td>{{ item.manager.branch.name|default:"No Branch" }}</td>
                                        <td>{{ item.snapshot.total_clients }}</td>
                                        <td>{{ item.snapshot.active_loans }}</td>
                                        <td>
                                            {% if item.health_score >= 80 %}
                                                <span class="health-score-badge health-excellent">{{ item.health_score|floatformat:1 }}%</span>
                                            {% elif item.health_score >= 70 %}
                                                <span class="health-score-badge health-good">{{ item.health_score|floatformat:1 }}%</span>
                                            {% elif item.health_score >= 50 %}
                                                <span class="health-score-badge health-warning">{{ item.health_score|floatformat:1 }}%</span>
                                            {% else %}
                                                <span class="health-score-badge health-critical">{{ item.health_score|floatformat:1 }}%</span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            {% if item.growth_rate > 0 %}
                                                <span class="text-success">+{{ item.growth_rate|floatformat:1 }}%</span>
                                            {% elif item.growth_rate < 0 %}
                                                <span class="text-danger">{{ item.growth_rate|floatformat:1 }}%</span>
                                            {% else %}
                                                <span class="text-muted">0.0%</span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            <a href="{% url 'manager_portfolio_detail' item.manager.id %}" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-eye"></i> View Details
                                            </a>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <div class="text-center py-4">
                            <span>📈</span>
                            <h5>No Portfolio Data Available</h5>
                            <p class="text-muted">Portfolio snapshots will appear here once generated.</p>
                            {% if user.role == 'admin' %}
                            <a href="{% url 'generate_snapshot_manual' %}" class="btn btn-primary">
                                Generate First Snapshot
                            </a>
                            {% endif %}
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>

        <!-- Recent Alerts -->
        <div class="col-lg-4">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">Recent Alerts</h5>
                    <a href="{% url 'portfolio_health_alerts' %}" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body">
                    {% if recent_alerts %}
                        <div class="alert-list">
                            {% for alert in recent_alerts %}
                            <div class="alert-item {% if alert.priority == 'high' %}alert-critical{% elif alert.priority == 'medium' %}alert-warning{% else %}alert-info{% endif %}">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <h6 class="mb-1">{{ alert.title }}</h6>
                                        <p class="mb-1 small">{{ alert.message|truncatechars:80 }}</p>
                                        <small class="text-muted">{{ alert.created_at|timesince }} ago</small>
                                    </div>
                                    {% if not alert.read_at %}
                                    <span class="badge bg-danger">New</span>
                                    {% endif %}
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                    {% else %}
                        <div class="text-center py-3">
                            <i class="fas fa-bell-slash fa-2x text-muted mb-2"></i>
                            <p class="text-muted mb-0">No recent alerts</p>
                        </div>
                    {% endif %}
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="card mt-3">
                <div class="card-header">
                    <h5 class="card-title mb-0">Quick Actions</h5>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <a href="{% url 'portfolio_comparison' %}" class="btn btn-outline-primary">
                            <span>📊</span> Compare Portfolios
                        </a>
                        <a href="{% url 'portfolio_health_alerts' %}" class="btn btn-outline-warning">
                            <span>⚠️</span> View Alerts
                        </a>
                        {% if user.role == 'admin' %}
                        <a href="{% url 'generate_snapshot_manual' %}" class="btn btn-outline-success">
                            <span>🔄</span> Generate Snapshots
                        </a>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
    // Auto-refresh every 5 minutes
    setTimeout(function() {
        location.reload();
    }, 300000);
    
    // Initialize tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
</script>
{% endblock %}