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

{% block title %}Client Analytics Dashboard{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.css">
<style>
    .analytics-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;
    }

    .analytics-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    }

    .metric-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 10px;
        padding: 20px;
        text-align: center;
        margin-bottom: 20px;
    }

    .metric-value {
        font-size: 2.5rem;
        font-weight: bold;
        margin-bottom: 5px;
    }

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

    .chart-container {
        position: relative;
        height: 400px;
        margin: 20px 0;
    }

    .filter-section {
        background: #f8f9fa;
        padding: 20px;
        border-radius: 10px;
        margin-bottom: 20px;
    }

    .demographic-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
        margin-top: 20px;
    }

    .demographic-chart {
        height: 300px;
    }

    .lifecycle-stage {
        display: flex;
        align-items: center;
        padding: 15px;
        margin: 10px 0;
        background: #f8f9fa;
        border-radius: 8px;
        border-left: 4px solid #007bff;
    }

    .lifecycle-stage .icon {
        font-size: 2rem;
        margin-right: 15px;
        color: #007bff;
    }

    .lifecycle-stage .content {
        flex: 1;
    }

    .lifecycle-stage .count {
        font-size: 1.5rem;
        font-weight: bold;
        color: #007bff;
    }

    .conversion-rate {
        font-size: 0.9rem;
        color: #6c757d;
        margin-top: 5px;
    }

    .export-buttons {
        margin: 20px 0;
    }

    .export-buttons .btn {
        margin-right: 10px;
        margin-bottom: 10px;
    }

    .trend-indicator {
        display: inline-flex;
        align-items: center;
        margin-left: 10px;
        font-size: 0.9rem;
    }

    .trend-up {
        color: #28a745;
    }

    .trend-down {
        color: #dc3545;
    }

    .trend-neutral {
        color: #6c757d;
    }
</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">Client Analytics Dashboard</h1>
                <div class="export-buttons">
                    <button class="btn btn-outline-primary" onclick="exportData('acquisition', 'excel')">
                        <span>📊</span> Export Trends
                    </button>
                    <button class="btn btn-outline-success" onclick="exportData('demographic', 'excel')">
                        <span>📊</span> Export Demographics
                    </button>
                    <button class="btn btn-outline-info" onclick="exportData('lifecycle', 'excel')">
                        <i class="fas fa-route"></i> Export Lifecycle
                    </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-3">
                            <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-3">
                            <label for="period" class="form-label">Period</label>
                            <select name="period" id="period" class="form-select">
                                <option value="daily" {% if selected_period=='daily' %}selected{% endif %}>Daily
                                </option>
                                <option value="weekly" {% if selected_period=='weekly' %}selected{% endif %}>Weekly
                                </option>
                                <option value="monthly" {% if selected_period=='monthly' %}selected{% endif %}>Monthly
                                </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>
                                <option value="24" {% if selected_months==24 %}selected{% endif %}>24 Months</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <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>

    <!-- Summary Metrics -->
    <div class="row">
        <div class="col-md-3">
            <div class="metric-card">
                <div class="metric-value">{{ acquisition_data.summary.total_clients|floatformat:0 }}</div>
                <div class="metric-label">Total Clients</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="metric-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                <div class="metric-value">{{ acquisition_data.summary.avg_monthly_acquisition|floatformat:0 }}</div>
                <div class="metric-label">Avg Monthly Acquisition</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="metric-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                <div class="metric-value">{{ acquisition_data.summary.overall_conversion_rate|floatformat:1 }}%</div>
                <div class="metric-label">Conversion Rate</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="metric-card" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
                <div class="metric-value">{{ demographic_data.total_clients|floatformat:0 }}</div>
                <div class="metric-label">Active Clients</div>
            </div>
        </div>
    </div>

    <!-- Client Acquisition Trends -->
    <div class="row">
        <div class="col-12">
            <div class="analytics-card">
                <h5><span>📈</span> Client Acquisition Trends</h5>
                <div class="chart-container">
                    <canvas id="acquisitionChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Demographics Analysis -->
    <div class="row">
        <div class="col-12">
            <div class="analytics-card">
                <h5><span>👥</span> Client Demographics</h5>
                <div class="demographic-grid">
                    <div>
                        <h6>Gender Distribution</h6>
                        <div class="demographic-chart">
                            <canvas id="genderChart"></canvas>
                        </div>
                    </div>
                    <div>
                        <h6>Age Distribution</h6>
                        <div class="demographic-chart">
                            <canvas id="ageChart"></canvas>
                        </div>
                    </div>
                    <div>
                        <h6>Geographic Distribution</h6>
                        <div class="demographic-chart">
                            <canvas id="geographicChart"></canvas>
                        </div>
                    </div>
                    <div>
                        <h6>Income Distribution</h6>
                        <div class="demographic-chart">
                            <canvas id="incomeChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Client Lifecycle Analysis -->
    <div class="row">
        <div class="col-md-8">
            <div class="analytics-card">
                <h5><i class="fas fa-route"></i> Client Lifecycle Journey</h5>
                <div class="lifecycle-stages">
                    <div class="lifecycle-stage">
                        <div class="icon"><span>👤+</span></div>
                        <div class="content">
                            <div class="count">{{ lifecycle_data.lifecycle_stages.registration }}</div>
                            <div>Client Registration</div>
                        </div>
                    </div>

                    <div class="lifecycle-stage">
                        <div class="icon"><span>✓</span></div>
                        <div class="content">
                            <div class="count">{{ lifecycle_data.lifecycle_stages.kyc_completed }}</div>
                            <div>KYC Completed</div>
                            <div class="conversion-rate">
                                Conversion: {{
                                lifecycle_data.conversion_rates.registration_to_kyc_completed|floatformat:1 }}%
                            </div>
                        </div>
                    </div>

                    <div class="lifecycle-stage">
                        <div class="icon"><span>📄</span></div>
                        <div class="content">
                            <div class="count">{{ lifecycle_data.lifecycle_stages.first_application }}</div>
                            <div>First Application</div>
                            <div class="conversion-rate">
                                Conversion: {{
                                lifecycle_data.conversion_rates.kyc_completed_to_first_application|floatformat:1 }}%
                            </div>
                        </div>
                    </div>

                    <div class="lifecycle-stage">
                        <div class="icon"><span>💵</span></div>
                        <div class="content">
                            <div class="count">{{ lifecycle_data.lifecycle_stages.first_approval }}</div>
                            <div>First Loan Approval</div>
                            <div class="conversion-rate">
                                Conversion: {{
                                lifecycle_data.conversion_rates.first_application_to_first_approval|floatformat:1 }}%
                            </div>
                        </div>
                    </div>

                    <div class="lifecycle-stage">
                        <div class="icon"><span>🔄</span></div>
                        <div class="content">
                            <div class="count">{{ lifecycle_data.lifecycle_stages.repeat_borrower }}</div>
                            <div>Repeat Borrower</div>
                            <div class="conversion-rate">
                                Conversion: {{
                                lifecycle_data.conversion_rates.first_approval_to_repeat_borrower|floatformat:1 }}%
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="analytics-card">
                <h5><span>⏰</span> Client Retention</h5>
                <div class="retention-metrics">
                    {% for period, data in lifecycle_data.retention_analysis.items %}
                    <div class="retention-item mb-3">
                        <div class="d-flex justify-content-between">
                            <span>{{ period|title }} Retention</span>
                            <strong>{{ data.retention_rate|floatformat:1 }}%</strong>
                        </div>
                        <div class="progress" style="height: 8px;">
                            <div class="progress-bar" role="progressbar" style="width: {{ data.retention_rate }}%"
                                aria-valuenow="{{ data.retention_rate }}" aria-valuemin="0" aria-valuemax="100">
                            </div>
                        </div>
                        <small class="text-muted">{{ data.retained_clients }} of {{ data.eligible_clients }}
                            clients</small>
                    </div>
                    {% endfor %}
                </div>
            </div>

            <div class="analytics-card">
                <h5><span>$</span> Client Value Metrics</h5>
                <div class="value-metrics">
                    <div class="metric-item mb-3">
                        <div class="metric-label">Avg Total Borrowed</div>
                        <div class="metric-value">KES {{ lifecycle_data.client_value.avg_total_borrowed|floatformat:2 }}
                        </div>
                    </div>
                    <div class="metric-item mb-3">
                        <div class="metric-label">Avg Loan Count</div>
                        <div class="metric-value">{{ lifecycle_data.client_value.avg_loan_count|floatformat:1 }}</div>
                    </div>
                    <div class="metric-item mb-3">
                        <div class="metric-label">Avg Loan Size</div>
                        <div class="metric-value">KES {{ lifecycle_data.client_value.avg_loan_size|floatformat:2 }}
                        </div>
                    </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>
    // Chart.js configuration
    Chart.defaults.font.family = "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif";
    Chart.defaults.color = '#6c757d';

    // Acquisition Trends Chart
    const acquisitionCtx = document.getElementById('acquisitionChart').getContext('2d');
    const acquisitionChart = new Chart(acquisitionCtx, {
        type: 'line',
        data: {
            labels: {{ acquisition_data.trend_data | safe |default: "[]" }}.map(item => item.period),
                datasets: [{
                    label: 'New Clients',
                    data: {{ acquisition_data.trend_data | safe |default: "[]" }}.map(item => item.new_clients),
                    borderColor: '#007bff',
                    backgroundColor: 'rgba(0, 123, 255, 0.1)',
                    tension: 0.4,
                    fill: true
        }, {
                    label: 'Approved Clients',
                    data: {{ acquisition_data.trend_data | safe |default: "[]" }}.map(item => item.approved_clients),
                    borderColor: '#28a745',
                    backgroundColor: 'rgba(40, 167, 69, 0.1)',
                    tension: 0.4,
                    fill: true
        }]
    },
    options: {
        responsive: true,
            maintainAspectRatio: false,
                plugins: {
            legend: {
                position: 'top',
            },
            title: {
                display: true,
                    text: 'Client Acquisition Over Time'
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                    ticks: {
                    precision: 0
                }
            }
        }
    }
});

    // Gender Distribution Chart
    const genderCtx = document.getElementById('genderChart').getContext('2d');
    const genderData = {{ demographic_data.gender_distribution| safe |default: "{}" }};
    const genderChart = new Chart(genderCtx, {
        type: 'doughnut',
        data: {
            labels: Object.keys(genderData),
            datasets: [{
                data: Object.values(genderData).map(item => item.count),
                backgroundColor: ['#007bff', '#28a745', '#ffc107', '#dc3545', '#6c757d']
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });

    // Age Distribution Chart
    const ageCtx = document.getElementById('ageChart').getContext('2d');
    const ageData = {{ demographic_data.age_distribution| safe |default: "{}" }};
    const ageChart = new Chart(ageCtx, {
        type: 'bar',
        data: {
            labels: Object.keys(ageData),
            datasets: [{
                label: 'Clients',
                data: Object.values(ageData).map(item => item.count),
                backgroundColor: 'rgba(0, 123, 255, 0.8)'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        precision: 0
                    }
                }
            }
        }
    });

    // Geographic Distribution Chart
    const geographicCtx = document.getElementById('geographicChart').getContext('2d');
    const geographicData = {{ demographic_data.geographic_distribution| safe |default: "{}" }};
    const geographicChart = new Chart(geographicCtx, {
        type: 'horizontalBar',
        data: {
            labels: Object.keys(geographicData),
            datasets: [{
                label: 'Clients',
                data: Object.values(geographicData).map(item => item.count),
                backgroundColor: 'rgba(40, 167, 69, 0.8)'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                x: {
                    beginAtZero: true,
                    ticks: {
                        precision: 0
                    }
                }
            }
        }
    });

    // Income Distribution Chart
    const incomeCtx = document.getElementById('incomeChart').getContext('2d');
    const incomeData = {{ demographic_data.income_distribution| safe |default: "{}" }};
    const incomeChart = new Chart(incomeCtx, {
        type: 'pie',
        data: {
            labels: Object.keys(incomeData),
            datasets: [{
                data: Object.values(incomeData).map(item => item.count),
                backgroundColor: [
                    '#007bff', '#28a745', '#ffc107', '#dc3545', '#6f42c1', '#20c997'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });

    // 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');
    }

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

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