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

{% block title %}Growth Forecasting Dashboard{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.css">
<style>
    .forecast-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;
    }
    
    .forecast-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    }
    
    .executive-summary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 10px;
        padding: 30px;
        margin-bottom: 30px;
    }
    
    .summary-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        margin-top: 20px;
    }
    
    .summary-item {
        text-align: center;
        padding: 15px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 8px;
    }
    
    .summary-value {
        font-size: 2rem;
        font-weight: bold;
        margin-bottom: 5px;
    }
    
    .summary-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }
    
    .trend-indicator {
        display: inline-flex;
        align-items: center;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 0.8rem;
        font-weight: 500;
        margin-left: 10px;
    }
    
    .trend-increasing {
        background: #d4edda;
        color: #155724;
    }
    
    .trend-decreasing {
        background: #f8d7da;
        color: #721c24;
    }
    
    .trend-stable {
        background: #d1ecf1;
        color: #0c5460;
    }
    
    .chart-container {
        position: relative;
        height: 400px;
        margin: 20px 0;
    }
    
    .alert-item {
        padding: 15px;
        margin: 10px 0;
        border-radius: 8px;
        border-left: 4px solid;
    }
    
    .alert-critical {
        background: #f8d7da;
        border-left-color: #dc3545;
        color: #721c24;
    }
    
    .alert-warning {
        background: #fff3cd;
        border-left-color: #ffc107;
        color: #856404;
    }
    
    .alert-info {
        background: #d1ecf1;
        border-left-color: #17a2b8;
        color: #0c5460;
    }
    
    .recommendation-card {
        border: 1px solid #e9ecef;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 15px;
        background: white;
    }
    
    .priority-critical {
        border-left: 4px solid #dc3545;
    }
    
    .priority-high {
        border-left: 4px solid #fd7e14;
    }
    
    .priority-medium {
        border-left: 4px solid #ffc107;
    }
    
    .priority-low {
        border-left: 4px solid #28a745;
    }
    
    .seasonal-chart {
        height: 300px;
    }
    
    .capacity-timeline {
        max-height: 400px;
        overflow-y: auto;
    }
    
    .timeline-item {
        display: flex;
        align-items: center;
        padding: 10px;
        margin: 5px 0;
        background: #f8f9fa;
        border-radius: 5px;
    }
    
    .timeline-month {
        font-weight: bold;
        min-width: 80px;
    }
    
    .timeline-content {
        flex: 1;
        margin-left: 15px;
    }
    
    .filter-section {
        background: #f8f9fa;
        padding: 20px;
        border-radius: 10px;
        margin-bottom: 20px;
    }
    
    .export-buttons {
        margin: 20px 0;
    }
    
    .export-buttons .btn {
        margin-right: 10px;
        margin-bottom: 10px;
    }
</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">Growth Forecasting Dashboard</h1>
                <div class="export-buttons">
                    <button class="btn btn-outline-primary" onclick="exportReport('excel')">
                        <span>📊</span> Export Excel Report
                    </button>
                    <button class="btn btn-outline-danger" onclick="exportReport('pdf')">
                        <span>📄</span> Export PDF Report
                    </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="branch_id" class="form-label">Branch</label>
                            <select name="branch_id" id="branch_id" class="form-select">
                                <option value="">All Branches</option>
                                {% for branch in branches %}
                                <option value="{{ branch.id }}" {% if branch.id|stringformat:"s" == selected_branch %}selected{% endif %}>
                                    {{ branch.name }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="forecast_months" class="form-label">Forecast Period</label>
                            <select name="forecast_months" id="forecast_months" class="form-select">
                                <option value="6" {% if forecast_months == 6 %}selected{% endif %}>6 Months</option>
                                <option value="12" {% if forecast_months == 12 %}selected{% endif %}>12 Months</option>
                                <option value="18" {% if forecast_months == 18 %}selected{% endif %}>18 Months</option>
                                <option value="24" {% if forecast_months == 24 %}selected{% endif %}>24 Months</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">&nbsp;</label>
                            <div>
                                <button type="submit" class="btn btn-primary">
                                    <span>🔍</span> Apply Filters
                                </button>
                                <button type="button" class="btn btn-outline-secondary" onclick="resetFilters()">
                                    <span>↶</span> Reset
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Executive Summary -->
    <div class="row">
        <div class="col-12">
            <div class="executive-summary">
                <h4><span>📈</span> Executive Summary</h4>
                <div class="summary-grid">
                    <div class="summary-item">
                        <div class="summary-value">{{ forecast_report.executive_summary.projected_growth.new_clients|floatformat:0 }}</div>
                        <div class="summary-label">Projected New Clients</div>
                        <span class="trend-indicator trend-{{ forecast_report.executive_summary.projected_growth.growth_trend }}">
                            {% if forecast_report.executive_summary.projected_growth.growth_trend == 'increasing' %}
                                <span>↑</span> Growing
                            {% elif forecast_report.executive_summary.projected_growth.growth_trend == 'decreasing' %}
                                <span>↓</span> Declining
                            {% else %}
                                <span>−</span> Stable
                            {% endif %}
                        </span>
                    </div>
                    <div class="summary-item">
                        <div class="summary-value">{{ forecast_report.executive_summary.projected_growth.confidence|floatformat:1 }}%</div>
                        <div class="summary-label">Model Confidence</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-value">{{ forecast_report.executive_summary.seasonal_insights.peak_month }}</div>
                        <div class="summary-label">Peak Season</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-value">{{ forecast_report.executive_summary.capacity_requirements.additional_staff_needed }}</div>
                        <div class="summary-label">Additional Staff Needed</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-value">KES {{ forecast_report.executive_summary.capacity_requirements.budget_impact|floatformat:0 }}</div>
                        <div class="summary-label">Annual Budget Impact</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-value">{{ forecast_report.executive_summary.risk_alerts }}</div>
                        <div class="summary-label">Critical Alerts</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Growth Forecasts -->
    <div class="row">
        <div class="col-12">
            <div class="forecast-card">
                <h5><i class="fas fa-crystal-ball"></i> Growth Forecasts</h5>
                <div class="chart-container">
                    <canvas id="forecastChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Seasonal Analysis and Early Warnings -->
    <div class="row">
        <div class="col-md-8">
            <div class="forecast-card">
                <h5><span>📅</span> Seasonal Trends</h5>
                <div class="seasonal-chart">
                    <canvas id="seasonalChart"></canvas>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="forecast-card">
                <h5><span>⚠️</span> Early Warning Alerts</h5>
                <div class="alerts-container">
                    {% for alert in forecast_report.detailed_analysis.early_warnings.alerts %}
                    <div class="alert-item alert-{{ alert.type }}">
                        <h6>{{ alert.title }}</h6>
                        <p>{{ alert.message }}</p>
                        <small><strong>Recommendation:</strong> {{ alert.recommendation }}</small>
                        {% if alert.action_required %}
                        <div class="mt-2">
                            <span class="badge bg-danger">Action Required</span>
                        </div>
                        {% endif %}
                    </div>
                    {% empty %}
                    <div class="text-center text-muted">
                        <span>✓</span>
                        <p>No alerts detected</p>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>

    <!-- Capacity Planning -->
    <div class="row">
        <div class="col-md-8">
            <div class="forecast-card">
                <h5><span>👥</span> Capacity Planning Timeline</h5>
                <div class="capacity-timeline">
                    {% for item in forecast_report.detailed_analysis.capacity_planning.hiring_timeline %}
                    <div class="timeline-item">
                        <div class="timeline-month">{{ item.month }}</div>
                        <div class="timeline-content">
                            <div><strong>{{ item.projected_clients }}</strong> projected clients</div>
                            <div>Staff needed: <strong>{{ item.staff_needed }}</strong></div>
                            {% if item.additional_staff_needed > 0 %}
                            <div class="text-warning">Additional staff needed: <strong>{{ item.additional_staff_needed }}</strong></div>
                            {% endif %}
                            <small class="text-muted">Ratio: {{ item.clients_per_officer|floatformat:1 }} clients/officer</small>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="forecast-card">
                <h5><span>📊</span> Capacity Metrics</h5>
                <div class="capacity-metrics">
                    <div class="metric-item mb-3">
                        <div class="d-flex justify-content-between">
                            <span>Current Staff</span>
                            <strong>{{ forecast_report.detailed_analysis.capacity_planning.current_metrics.total_staff }}</strong>
                        </div>
                    </div>
                    <div class="metric-item mb-3">
                        <div class="d-flex justify-content-between">
                            <span>Current Clients</span>
                            <strong>{{ forecast_report.detailed_analysis.capacity_planning.current_metrics.total_clients }}</strong>
                        </div>
                    </div>
                    <div class="metric-item mb-3">
                        <div class="d-flex justify-content-between">
                            <span>Clients per Officer</span>
                            <strong>{{ forecast_report.detailed_analysis.capacity_planning.current_metrics.clients_per_officer|floatformat:1 }}</strong>
                        </div>
                    </div>
                    <div class="metric-item mb-3">
                        <div class="d-flex justify-content-between">
                            <span>Projected Growth</span>
                            <strong>{{ forecast_report.detailed_analysis.capacity_planning.projections.growth_rate|floatformat:1 }}%</strong>
                        </div>
                    </div>
                    <div class="metric-item mb-3">
                        <div class="d-flex justify-content-between">
                            <span>Optimal Staff Needed</span>
                            <strong>{{ forecast_report.detailed_analysis.capacity_planning.resource_requirements.staff_expansion.optimal_staff_needed }}</strong>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Recommendations -->
    <div class="row">
        <div class="col-12">
            <div class="forecast-card">
                <h5><span>💡</span> Strategic Recommendations</h5>
                <div class="recommendations-container">
                    {% for recommendation in forecast_report.recommendations %}
                    <div class="recommendation-card priority-{{ recommendation.priority }}">
                        <div class="d-flex justify-content-between align-items-start">
                            <h6>{{ recommendation.title }}</h6>
                            <span class="badge bg-{{ recommendation.priority|yesno:'danger,warning,info' }}">
                                {{ recommendation.priority|title }} Priority
                            </span>
                        </div>
                        <p class="text-muted">{{ recommendation.description }}</p>
                        <div class="actions-list">
                            <strong>Recommended Actions:</strong>
                            <ul class="mt-2">
                                {% for action in recommendation.actions %}
                                <li>{{ action }}</li>
                                {% endfor %}
                            </ul>
                        </div>
                    </div>
                    {% empty %}
                    <div class="text-center text-muted">
                        <span>👍</span>
                        <p>No specific recommendations at this time</p>
                    </div>
                    {% endfor %}
                </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>
// Chart.js configuration
Chart.defaults.font.family = "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif";
Chart.defaults.color = '#6c757d';

// Growth Forecast Chart
const forecastCtx = document.getElementById('forecastChart').getContext('2d');
const forecastData = {{ forecast_report.detailed_analysis.predictive_models.forecasts|safe }};
const historicalData = {{ forecast_report.detailed_analysis.predictive_models.historical_data|safe }};

const forecastChart = new Chart(forecastCtx, {
    type: 'line',
    data: {
        labels: [...historicalData.map(item => item.month), ...forecastData.map(item => item.month)],
        datasets: [{
            label: 'Historical New Clients',
            data: [...historicalData.map(item => item.new_clients), ...Array(forecastData.length).fill(null)],
            borderColor: '#007bff',
            backgroundColor: 'rgba(0, 123, 255, 0.1)',
            tension: 0.4,
            fill: false
        }, {
            label: 'Predicted New Clients',
            data: [...Array(historicalData.length).fill(null), ...forecastData.map(item => item.predicted_new_clients)],
            borderColor: '#28a745',
            backgroundColor: 'rgba(40, 167, 69, 0.1)',
            borderDash: [5, 5],
            tension: 0.4,
            fill: false
        }, {
            label: 'Historical Approved',
            data: [...historicalData.map(item => item.approved_clients), ...Array(forecastData.length).fill(null)],
            borderColor: '#ffc107',
            backgroundColor: 'rgba(255, 193, 7, 0.1)',
            tension: 0.4,
            fill: false
        }, {
            label: 'Predicted Approved',
            data: [...Array(historicalData.length).fill(null), ...forecastData.map(item => item.predicted_approved_clients)],
            borderColor: '#dc3545',
            backgroundColor: 'rgba(220, 53, 69, 0.1)',
            borderDash: [5, 5],
            tension: 0.4,
            fill: false
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            title: {
                display: true,
                text: 'Client Growth Forecast'
            },
            legend: {
                position: 'top'
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    precision: 0
                }
            }
        }
    }
});

// Seasonal Trends Chart
const seasonalCtx = document.getElementById('seasonalChart').getContext('2d');
const seasonalData = {{ forecast_report.detailed_analysis.seasonal_analysis.monthly_patterns|safe }};

const seasonalChart = new Chart(seasonalCtx, {
    type: 'bar',
    data: {
        labels: Object.keys(seasonalData),
        datasets: [{
            label: 'Average Clients per Month',
            data: Object.values(seasonalData).map(item => item.avg_per_year),
            backgroundColor: 'rgba(0, 123, 255, 0.8)',
            borderColor: '#007bff',
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            title: {
                display: true,
                text: 'Seasonal Client Acquisition Patterns'
            },
            legend: {
                display: false
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    precision: 0
                }
            }
        }
    }
});

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

// Reset filters
function resetFilters() {
    window.location.href = '{% url "users:growth_forecasting_dashboard" %}';
}

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

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