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

{% block title %}Enhanced Dashboard - HAVEN GRAZURI INVESTMENT LIMITED{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'css/reports-enhanced.css' %}">
<style>
.dashboard-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 1.5rem;
    margin: 2rem 0;
}

.metric-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 1.5rem;
    border-radius: 15px;
    box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
    transition: all 0.3s ease;
}

.metric-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 35px rgba(102, 126, 234, 0.4);
}

.metric-value {
    font-size: 2.5rem;
    font-weight: 700;
    margin-bottom: 0.5rem;
}

.metric-label {
    font-size: 1rem;
    opacity: 0.9;
}

.chart-grid {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 2rem;
    margin: 2rem 0;
}

@media (max-width: 1024px) {
    .chart-grid {
        grid-template-columns: 1fr;
    }
}
</style>
{% endblock %}

{% block content %}
<div class="report-container">
    <div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 fade-in">
        
        <!-- Enhanced Header -->
        <div class="report-card slide-up">
            <div class="report-header">
                <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                    <div>
                        <h1 class="report-title">Enhanced Analytics Dashboard</h1>
                        <p class="report-subtitle">Comprehensive business intelligence and performance metrics</p>
                    </div>
                    <div class="export-buttons">
                        <button onclick="refreshDashboard()" class="action-button secondary">
                            <span>🔄</span> Refresh
                        </button>
                        <a href="{% url 'loans:analytics_dashboard' %}" class="action-button primary">
                            <span>📈</span> Advanced Analytics
                        </a>
                    </div>
                </div>
            </div>
            
            <!-- Real-time Metrics -->
            <div class="dashboard-grid">
                <div class="metric-card">
                    <div class="metric-value">{{ real_time_metrics.todays_loan_count }}</div>
                    <div class="metric-label">Today's Loans</div>
                </div>
                <div class="metric-card">
                    <div class="metric-value">KES {{ real_time_metrics.todays_disbursements|floatformat:0|intcomma }}</div>
                    <div class="metric-label">Today's Disbursements</div>
                </div>
                <div class="metric-card">
                    <div class="metric-value">KES {{ real_time_metrics.todays_collections|floatformat:0|intcomma }}</div>
                    <div class="metric-label">Today's Collections</div>
                </div>
                <div class="metric-card">
                    <div class="metric-value">{{ dashboard_data.loan_performance.collection_rate|floatformat:1 }}%</div>
                    <div class="metric-label">Collection Rate</div>
                </div>
            </div>
        </div>
        
        <!-- Performance Summary -->
        <div class="summary-grid slide-up">
            <div class="summary-card">
                <div class="summary-card-content">
                    <div class="summary-icon blue">
                        <span>📈</span>
                    </div>
                    <div class="summary-details">
                        <h3>Total Portfolio</h3>
                        <p>KES {{ dashboard_data.loan_performance.total_disbursed|floatformat:0|intcomma }}</p>
                    </div>
                </div>
            </div>
            
            <div class="summary-card">
                <div class="summary-card-content">
                    <div class="summary-icon green">
                        <span>💵</span>
                    </div>
                    <div class="summary-details">
                        <h3>Active Loans</h3>
                        <p>{{ dashboard_data.loan_performance.active_loans }}</p>
                    </div>
                </div>
            </div>
            
            <div class="summary-card">
                <div class="summary-card-content">
                    <div class="summary-icon purple">
                        <i class="fas fa-percentage"></i>
                    </div>
                    <div class="summary-details">
                        <h3>Default Rate</h3>
                        <p>{{ dashboard_data.loan_performance.default_rate|floatformat:1 }}%</p>
                    </div>
                </div>
            </div>
            
            <div class="summary-card">
                <div class="summary-card-content">
                    <div class="summary-icon yellow">
                        <span>⚠️</span>
                    </div>
                    <div class="summary-details">
                        <h3>Overdue Rate</h3>
                        <p>{{ dashboard_data.portfolio_quality.overdue_rate|floatformat:1 }}%</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Enhanced Charts -->
        <div class="chart-grid slide-up">
            <!-- Performance Trend Chart -->
            <div class="chart-container">
                <div class="chart-header">
                    <h3 class="chart-title">Monthly Performance Trend</h3>
                    <div class="flex gap-2">
                        <button onclick="updatePerformanceChart('6m')" class="action-button secondary" id="perf6m">6M</button>
                        <button onclick="updatePerformanceChart('12m')" class="action-button primary" id="perf12m">12M</button>
                    </div>
                </div>
                <div class="chart-wrapper">
                    <canvas id="performanceChart"></canvas>
                </div>
            </div>
            
            <!-- Loan Distribution Chart -->
            <div class="chart-container">
                <div class="chart-header">
                    <h3 class="chart-title">Loan Status Distribution</h3>
                </div>
                <div class="chart-wrapper">
                    <canvas id="distributionChart"></canvas>
                </div>
            </div>
        </div>
        
        <!-- Client Growth Chart -->
        <div class="chart-container slide-up">
            <div class="chart-header">
                <h3 class="chart-title">Client Growth Trend</h3>
            </div>
            <div class="chart-wrapper">
                <canvas id="clientGrowthChart"></canvas>
            </div>
        </div>
        
        <!-- Risk Analysis -->
        <div class="summary-grid slide-up">
            <div class="summary-card">
                <div class="summary-card-content">
                    <div class="summary-icon green">
                        <i class="fas fa-shield-alt"></i>
                    </div>
                    <div class="summary-details">
                        <h3>Low Risk Loans</h3>
                        <p>{{ dashboard_data.risk_categories.low_risk }}</p>
                    </div>
                </div>
            </div>
            
            <div class="summary-card">
                <div class="summary-card-content">
                    <div class="summary-icon yellow">
                        <span>⚠️</span>
                    </div>
                    <div class="summary-details">
                        <h3>Medium Risk Loans</h3>
                        <p>{{ dashboard_data.risk_categories.medium_risk }}</p>
                    </div>
                </div>
            </div>
            
            <div class="summary-card">
                <div class="summary-card-content">
                    <div class="summary-icon red">
                        <span>⚠️</span>
                    </div>
                    <div class="summary-details">
                        <h3>High Risk Loans</h3>
                        <p>{{ dashboard_data.risk_categories.high_risk }}</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Dashboard data from Django
const dashboardData = {{ dashboard_data|safe }};

// Initialize charts when page loads
document.addEventListener('DOMContentLoaded', function() {
    initializePerformanceChart();
    initializeDistributionChart();
    initializeClientGrowthChart();
});

function initializePerformanceChart() {
    const ctx = document.getElementById('performanceChart').getContext('2d');
    
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: dashboardData.monthly_labels,
            datasets: [
                {
                    label: 'Disbursements',
                    data: dashboardData.monthly_performance.map(d => d.disbursed),
                    borderColor: '#667eea',
                    backgroundColor: 'rgba(102, 126, 234, 0.1)',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: 'Collections',
                    data: dashboardData.monthly_performance.map(d => d.collected),
                    borderColor: '#10b981',
                    backgroundColor: 'rgba(16, 185, 129, 0.1)',
                    tension: 0.4,
                    fill: true
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { position: 'top' }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return 'KES ' + value.toLocaleString();
                        }
                    }
                }
            }
        }
    });
}

function initializeDistributionChart() {
    const ctx = document.getElementById('distributionChart').getContext('2d');
    
    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: dashboardData.loan_distribution.labels,
            datasets: [{
                data: dashboardData.loan_distribution.counts,
                backgroundColor: dashboardData.loan_distribution.colors,
                borderWidth: 2,
                borderColor: '#ffffff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { position: 'bottom' }
            }
        }
    });
}

function initializeClientGrowthChart() {
    const ctx = document.getElementById('clientGrowthChart').getContext('2d');
    
    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: dashboardData.client_growth.map(d => d.month),
            datasets: [{
                label: 'New Clients',
                data: dashboardData.client_growth.map(d => d.new_clients),
                backgroundColor: 'rgba(46, 204, 113, 0.8)',
                borderColor: '#2ecc71',
                borderWidth: 2
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { position: 'top' }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: { stepSize: 1 }
                }
            }
        }
    });
}

function refreshDashboard() {
    location.reload();
}

function updatePerformanceChart(period) {
    // Update chart based on period
    document.querySelectorAll('#perf6m, #perf12m').forEach(btn => {
        btn.classList.remove('primary');
        btn.classList.add('secondary');
    });
    
    document.getElementById('perf' + period).classList.remove('secondary');
    document.getElementById('perf' + period).classList.add('primary');
    
    // Here you would fetch new data and update the chart
    // For now, we'll just show the current data
}
</script>
{% endblock %}