{% extends 'base.html' %}
{% load static %}
{% load humanize %}
{% load json_tags %}
{% block title %}Dashboard - HAVEN GRAZURI INVESTMENT LIMITED{% endblock %}
{% block content %}
<!-- Page header -->
<div class="mb-6">
    <div class="flex justify-between items-center">
        <h2 class="text-xl font-semibold leading-6 text-gray-900 sm:truncate">
            Dashboard
        </h2>
        <div class="flex space-x-2">
            <a href="{% url 'loans:analytics_dashboard' %}" class="inline-flex items-center px-3 py-1.5 border border-gray-300 rounded-md shadow-sm text-xs font-medium text-gray-700 bg-white hover:bg-gray-50">
                <span>📊</span>
                Analytics
            </a>
            <button onclick="generateDashboardPDF('loans')" class="inline-flex items-center px-3 py-1.5 border border-transparent rounded-md shadow-sm text-xs font-medium text-white bg-primary hover:bg-primary-dark">
                <span>📄</span>
                PDF
            </button>
        </div>
    </div>
</div>

<!-- Stats -->
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
    <a href="{% url 'loans:filtered_loans' %}?status=active"
        class="stats-card relative overflow-hidden rounded-lg bg-white px-3 pb-8 pt-4 shadow hover:shadow-lg transition-shadow cursor-pointer block">
        <dt>
            <div class="absolute rounded-md bg-primary p-2">
                <span>💵</span>
            </div>
            <p class="ml-12 truncate text-xs font-medium text-gray-500">Active Loans</p>
        </dt>
        <dd class="ml-12 flex items-baseline pb-4">
            <p class="text-lg font-semibold text-gray-900">{{ active_loans }}</p>
            <p
                class="ml-2 flex items-baseline text-xs font-semibold {% if active_loans_change >= 0 %}text-green-600{% else %}text-red-600{% endif %}">
                <span class="sr-only">{% if active_loans_change >= 0 %}Increased{% else %}Decreased{% endif %} by</span>
                {% if active_loans_change >= 0 %}
                <span>↑</span>
                {% else %}
                <span>↓</span>
                {% endif %}
                {{ active_loans_change|floatformat:1 }}%
            </p>
        </dd>
    </a>

    <a href="{% url 'users:filtered_clients' %}?status=active"
        class="stats-card relative overflow-hidden rounded-lg bg-white px-3 pb-8 pt-4 shadow hover:shadow-lg transition-shadow cursor-pointer block">
        <dt>
            <div class="absolute rounded-md bg-primary p-2">
                <span>👥</span>
            </div>
            <p class="ml-12 truncate text-xs font-medium text-gray-500">Active Clients</p>
        </dt>
        <dd class="ml-12 flex items-baseline pb-4">
            <p class="text-lg font-semibold text-gray-900">{{ active_users }}</p>
            <p
                class="ml-2 flex items-baseline text-xs font-semibold {% if active_users_change >= 0 %}text-green-600{% else %}text-red-600{% endif %}">
                <span class="sr-only">{% if active_users_change >= 0 %}Increased{% else %}Decreased{% endif %} by</span>
                {% if active_users_change >= 0 %}
                <span>↑</span>
                {% else %}
                <span>↓</span>
                {% endif %}
                {{ active_users_change|floatformat:1 }}%
            </p>
        </dd>
    </a>

    <a href="{% url 'loans:filtered_applications' %}?status=pending"
        class="stats-card relative overflow-hidden rounded-lg bg-white px-3 pb-8 pt-4 shadow hover:shadow-lg transition-shadow cursor-pointer block">
        <dt>
            <div class="absolute rounded-md bg-primary p-2">
                <span>⏰</span>
            </div>
            <p class="ml-12 truncate text-xs font-medium text-gray-500">Pending Applications</p>
        </dt>
        <dd class="ml-12 flex items-baseline pb-4">
            <p class="text-lg font-semibold text-gray-900">{{ pending_applications }}</p>
            <p
                class="ml-2 flex items-baseline text-xs font-semibold {% if pending_applications_change >= 0 %}text-yellow-600{% else %}text-green-600{% endif %}">
                <span class="sr-only">{% if pending_applications_change >= 0 %}Increased{% else %}Decreased{% endif %} by</span>
                {% if pending_applications_change >= 0 %}
                <span>↑</span>
                {% else %}
                <span>↓</span>
                {% endif %}
                {{ pending_applications_change|floatformat:1 }}%
            </p>
        </dd>
    </a>

    <a href="{% url 'loans:filtered_loans' %}?status=defaulted"
        class="stats-card relative overflow-hidden rounded-lg bg-white px-3 pb-8 pt-4 shadow hover:shadow-lg transition-shadow cursor-pointer block">
        <dt>
            <div class="absolute rounded-md bg-primary p-2">
                <span>⚠️</span>
            </div>
            <p class="ml-12 truncate text-xs font-medium text-gray-500">Default Rate</p>
        </dt>
        <dd class="ml-12 flex items-baseline pb-4">
            <p class="text-lg font-semibold text-gray-900">{{ default_rate|floatformat:1 }}%</p>
            <p
                class="ml-2 flex items-baseline text-xs font-semibold {% if default_rate_change <= 0 %}text-green-600{% else %}text-red-600{% endif %}">
                <span class="sr-only">{% if default_rate_change <= 0 %}Decreased{% else %}Increased{% endif %} by</span>
                        {% if default_rate_change <= 0 %} <span>↓</span>
                            {% else %}
                            <span>↑</span>
                            {% endif %}
                            {{ default_rate_change|floatformat:1 }}%
            </p>
        </dd>
    </a>
</div>

<!-- Enhanced Charts -->
<div class="mt-6 grid grid-cols-1 gap-4 lg:grid-cols-2">
    <div class="rounded-lg bg-white p-4 shadow border border-gray-100 hover:shadow-md transition-shadow duration-300">
        <div class="flex items-center justify-between mb-4">
            <div>
                <h3 class="text-lg font-semibold text-gray-900">Loan Performance</h3>
                <p class="text-xs text-gray-600 mt-1">Monthly disbursements vs collections</p>
            </div>
            <div class="flex items-center space-x-1 flex-wrap">
                <button onclick="updateChart('1w')" class="px-2 py-1 text-xs font-medium rounded transition-all duration-200 bg-gray-200 text-gray-700 hover:bg-gray-300"
                    id="btn1w">1W</button>
                <button onclick="updateChart('1m')" class="px-2 py-1 text-xs font-medium rounded transition-all duration-200 bg-gray-200 text-gray-700 hover:bg-gray-300"
                    id="btn1m">1M</button>
                <button onclick="updateChart('3m')" class="px-2 py-1 text-xs font-medium rounded transition-all duration-200 bg-gray-200 text-gray-700 hover:bg-gray-300"
                    id="btn3m">3M</button>
                <button onclick="updateChart('6m')" class="px-2 py-1 text-xs font-medium rounded transition-all duration-200 bg-primary text-white"
                    id="btn6m">6M</button>
                <button onclick="updateChart('1y')" class="px-2 py-1 text-xs font-medium rounded transition-all duration-200 bg-gray-200 text-gray-700 hover:bg-gray-300"
                    id="btn1y">1Y</button>
                <button onclick="updateChart('2y')" class="px-2 py-1 text-xs font-medium rounded transition-all duration-200 bg-gray-200 text-gray-700 hover:bg-gray-300"
                    id="btn2y">2Y</button>
                <button onclick="updateChart('5y')" class="px-2 py-1 text-xs font-medium rounded transition-all duration-200 bg-gray-200 text-gray-700 hover:bg-gray-300"
                    id="btn5y">5Y</button>
                <button onclick="updateChart('all')" class="px-2 py-1 text-xs font-medium rounded transition-all duration-200 bg-gray-200 text-gray-700 hover:bg-gray-300"
                    id="btnAll">All</button>
            </div>
        </div>
        <div class="relative" style="height: 250px;">
            <canvas id="loanChart"></canvas>
        </div>
    </div>

    <!-- Enhanced Recent Activity -->
    <div class="rounded-lg bg-white p-4 shadow border border-gray-100 hover:shadow-md transition-shadow duration-300">
        <div class="flex items-center justify-between mb-4">
            <div>
                <h3 class="text-lg font-semibold text-gray-900">Recent Activity</h3>
                <p class="text-xs text-gray-600 mt-1">Latest system activities</p>
            </div>
            <button onclick="refreshActivity()" class="p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-all duration-200">
                <span>🔄</span>
            </button>
        </div>
        <div class="mt-5">
            <div class="flow-root">
                <ul role="list" class="-mb-8" id="activityList">
                    {% for activity in recent_activity %}
                    <li>
                        <div class="relative pb-8">
                            {% if not forloop.last %}
                            <span class="absolute left-4 top-4 -ml-px h-full w-0.5 bg-gray-200"
                                aria-hidden="true"></span>
                            {% endif %}
                            <div class="relative flex space-x-3">
                                <div>
                                    <span class="h-8 w-8 rounded-full flex items-center justify-center ring-8 ring-white
                                        {% if activity.type == 'delete' %}bg-red-500
                                        {% elif activity.type == 'create' %}bg-green-500
                                        {% elif activity.type == 'update' %}bg-blue-500
                                        {% elif activity.type == 'payment' %}bg-purple-500
                                        {% else %}bg-gray-500{% endif %}">
                                        <i class="fas fa-{{ activity.icon }} h-5 w-5 text-white"></i>
                                    </span>
                                </div>
                                <div class="flex min-w-0 flex-1 justify-between space-x-4 pt-1.5">
                                    <div>
                                        <p class="text-sm text-gray-500">
                                            <span class="font-medium text-gray-900">{{ activity.user }}</span>
                                            {{ activity.action }}
                                        </p>
                                    </div>
                                    <div class="whitespace-nowrap text-right text-sm text-gray-500">
                                        <time datetime="{{ activity.timestamp|date:'c' }}" class="timeago">{{
                                            activity.timestamp|timesince }} ago</time>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </li>
                    {% empty %}
                    <li>
                        <p class="text-sm text-gray-500 text-center">No recent activity</p>
                    </li>
                    {% endfor %}
                </ul>
            </div>
        </div>
    </div>
</div>

<!-- Enhanced Additional Charts -->
<div class="mt-6 grid grid-cols-1 gap-4 lg:grid-cols-2">
    <div class="rounded-lg bg-white p-4 shadow border border-gray-100 hover:shadow-md transition-shadow duration-300">
        <div class="mb-4">
            <h3 class="text-lg font-semibold text-gray-900">Loan Distribution</h3>
            <p class="text-xs text-gray-600 mt-1">Breakdown by loan status</p>
        </div>
        <div class="relative" style="height: 250px;">
            <canvas id="loanDistributionChart"></canvas>
        </div>
    </div>

    <div class="rounded-lg bg-white p-4 shadow border border-gray-100 hover:shadow-md transition-shadow duration-300">
        <div class="mb-4">
            <h3 class="text-lg font-semibold text-gray-900">Client Growth</h3>
            <p class="text-xs text-gray-600 mt-1">New client registrations over time</p>
        </div>
        <div class="relative" style="height: 250px;">
            <canvas id="clientGrowthChart"></canvas>
        </div>
    </div>
</div>

<!-- Enhanced Performance Metrics -->
{% if dashboard_data.enhanced %}
<div class="mt-6 grid grid-cols-1 gap-4 lg:grid-cols-3">
    <div class="rounded-lg bg-gradient-to-br from-blue-500 to-blue-600 p-4 text-white shadow">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-blue-100 text-xs font-medium">Collection Rate</p>
                <p class="text-xl font-bold">{{ dashboard_data.enhanced.loan_performance.collection_rate|floatformat:1 }}%</p>
            </div>
            <div class="p-2 bg-blue-400 bg-opacity-30 rounded">
                <i class="fas fa-percentage text-lg"></i>
            </div>
        </div>
    </div>
    
    <div class="rounded-lg bg-gradient-to-br from-green-500 to-green-600 p-4 text-white shadow">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-green-100 text-xs font-medium">Portfolio Value</p>
                <p class="text-xl font-bold">KES {{ dashboard_data.enhanced.loan_performance.total_disbursed|floatformat:0|intcomma }}</p>
            </div>
            <div class="p-2 bg-green-400 bg-opacity-30 rounded">
                <span>📈</span>
            </div>
        </div>
    </div>
    
    <div class="rounded-lg bg-gradient-to-br from-purple-500 to-purple-600 p-4 text-white shadow">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-purple-100 text-xs font-medium">Overdue Rate</p>
                <p class="text-xl font-bold">{{ dashboard_data.enhanced.portfolio_quality.overdue_rate|floatformat:1 }}%</p>
            </div>
            <div class="p-2 bg-purple-400 bg-opacity-30 rounded">
                <span>⚠️</span>
            </div>
        </div>
    </div>
</div>
{% endif %}
{% endblock %}

{% block scripts %}
<script id="dashboard-data" type="application/json">{{ dashboard_data|json }}</script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/timeago.js/4.0.2/timeago.min.js"></script>
<script>
    // Session management
    let sessionRefreshInterval;
    let lastActivityTime = Date.now();

    function setupSessionManagement() {
        // Refresh session every 10 minutes
        sessionRefreshInterval = setInterval(refreshSession, 600000); // 10 minutes

        // Track user activity
        document.addEventListener('mousemove', updateLastActivity);
        document.addEventListener('keypress', updateLastActivity);
        document.addEventListener('click', updateLastActivity);
        document.addEventListener('scroll', updateLastActivity);
    }

    function updateLastActivity() {
        lastActivityTime = Date.now();
    }

    function refreshSession() {
        // Only refresh if there was activity in the last hour
        if (Date.now() - lastActivityTime < 3600000) { // 1 hour
            fetch('/api/session-ping/', {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCsrfToken(),
                    'Content-Type': 'application/json'
                }
            })
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 403) {
                            handleSessionTimeout();
                        }
                    }
                })
                .catch(error => {
                    console.warn('Session refresh failed:', error);
                });
        }
    }

    function getCsrfToken() {
        const name = 'csrftoken';
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    function handleSessionTimeout() {
        // Clear intervals
        if (sessionRefreshInterval) clearInterval(sessionRefreshInterval);
        if (refreshInterval) clearInterval(refreshInterval);

        // Show session timeout message
        const mainContent = document.querySelector('main') || document.body;
        mainContent.innerHTML = `
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"></div>
        <div class="fixed inset-0 z-10 overflow-y-auto">
            <div class="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
                <div class="relative transform overflow-hidden rounded-lg bg-white px-4 pb-4 pt-5 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-sm sm:p-6">
                    <div>
                        <div class="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-red-100">
                            <svg class="h-6 w-6 text-red-600" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
                            </svg>
                        </div>
                        <div class="mt-3 text-center sm:mt-5">
                            <h3 class="text-base font-semibold leading-6 text-gray-900">Session Expired</h3>
                            <div class="mt-2">
                                <p class="text-sm text-gray-500">Your session has expired. Please refresh the page to continue.</p>
                            </div>
                        </div>
                    </div>
                    <div class="mt-5 sm:mt-6">
                        <button type="button"
                                onclick="window.location.reload()"
                                class="inline-flex w-full justify-center rounded-md bg-primary px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-opacity-90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                            Refresh Page
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    }

    // Initialize dashboard data safely with better error handling
    var DASHBOARD_DATA = (function () {
        try {
            var dataElement = document.getElementById('dashboard-data');
            if (!dataElement) {
                console.warn('Dashboard data element not found, using defaults');
                return getDefaultData();
            }
            var data = JSON.parse(dataElement.textContent);
            return {
                monthlyData: Array.isArray(data.monthlyData) ? data.monthlyData : [],
                distributionData: {
                    labels: Array.isArray(data.distributionData && data.distributionData.labels) ? data.distributionData.labels : [],
                    data: Array.isArray(data.distributionData && data.distributionData.data) ? data.distributionData.data : [],
                    colors: Array.isArray(data.distributionData && data.distributionData.colors) ? data.distributionData.colors : []
                },
                clientGrowth: Array.isArray(data.clientGrowth) ? data.clientGrowth : []
            };
        } catch (e) {
            console.error('Error parsing dashboard data:', e);
            return getDefaultData();
        }
    })();

    function getDefaultData() {
        return {
            monthlyData: [],
            distributionData: { labels: [], data: [], colors: [] },
            clientGrowth: []
        };
    }

    // Wait for DOM and Chart.js to be ready
    document.addEventListener('DOMContentLoaded', function () {
        if (!window.Chart) {
            console.warn('Chart.js not loaded, dashboard functionality will be limited');
            return;
        }

        try {
            // Initialize timeago with error handling
            initializeTimeago();

            // Initialize charts with error handling
            initializeCharts();

            // Set up activity refresh with error handling
            setupActivityRefresh();

            // Initialize session management
            setupSessionManagement();

        } catch (e) {
            console.error('Error initializing dashboard:', e);
            // Don't let the error propagate and crash the page
        }
    });

    function initializeTimeago() {
        try {
            var timeagoElements = document.querySelectorAll('.timeago');
            timeagoElements.forEach(function (node) {
                try {
                    var datetime = node.getAttribute('datetime');
                    if (datetime) {
                        node.textContent = timeago.format(datetime);
                    }
                } catch (e) {
                    console.warn('Error formatting timeago for element:', e);
                    // Keep the original text if formatting fails
                }
            });
        } catch (e) {
            console.error('Error initializing timeago:', e);
        }
    }

    function initializeCharts() {
        try {
            console.log('Initializing charts');
            
            // Set initial active period
            var initialPeriodBtn = document.getElementById('btn6m');
            if (initialPeriodBtn) {
                initialPeriodBtn.classList.add('bg-primary', 'text-white');
            }
            window.currentPeriod = '6m';
            
            // Load initial data for all charts
            loadChartData('6m');
        } catch (e) {
            console.error('Error initializing charts:', e);
            // Show error message to user
            showGlobalError('Charts failed to load. Please refresh the page.');
        }
    }

    function initializeEnhancedCharts() {
        var enhancedData = DASHBOARD_DATA.enhanced;
        
        // Update loan performance chart with enhanced data
        updateLoanChart({
            labels: enhancedData.monthly_labels,
            disbursements: enhancedData.monthly_performance.map(d => d.disbursed),
            repayments: enhancedData.monthly_performance.map(d => d.collected),
            success: true
        });
        
        // Update distribution chart with enhanced data
        updateDistributionChart(enhancedData.loan_distribution);
        
        // Update growth chart with enhanced data
        updateGrowthChart({
            labels: enhancedData.client_growth.map(d => d.month),
            data: enhancedData.client_growth.map(d => d.new_clients)
        });
    }

    function updatePeriodButtons(period) {
        var periodButtons = document.querySelectorAll('#btn1w, #btn1m, #btn3m, #btn6m, #btn1y, #btn2y, #btn5y, #btnAll');
        periodButtons.forEach(function(btn) {
            btn.classList.remove('bg-primary', 'text-white');
            btn.classList.add('bg-gray-200', 'text-gray-700', 'hover:bg-gray-300');
        });
        
        var activeBtn = document.getElementById('btn' + period);
        if (activeBtn) {
            activeBtn.classList.remove('bg-gray-200', 'text-gray-700', 'hover:bg-gray-300');
            activeBtn.classList.add('bg-primary', 'text-white');
        }
    }

    function initializeLoanChart() {
        // This function is no longer needed as loadChartData handles everything
        console.log('Loan chart will be initialized by loadChartData');
    }

    function loadChartData(period) {
        console.log('Loading chart data for period:', period);
        
        // Show loading state with timeout
        var loanChartEl = document.getElementById('loanChart');
        if (loanChartEl && loanChartEl.parentElement) {
            loanChartEl.parentElement.innerHTML = `
                <div class="flex items-center justify-center h-64">
                    <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                    <span class="ml-3 text-gray-600">Loading chart data...</span>
                </div>
            `;
        }

        // Set a timeout to prevent infinite loading
        var loadingTimeout = setTimeout(function() {
            console.warn('Chart loading timeout, showing error');
            showChartError(document.getElementById('loanChart'));
        }, 10000); // 10 second timeout

        fetch('/api/loan-data/?period=' + period)
            .then(response => {
                clearTimeout(loadingTimeout);
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('Received chart data:', data);
                
                if (data.success) {
                    // Restore chart canvas
                    if (loanChartEl && loanChartEl.parentElement) {
                        loanChartEl.parentElement.innerHTML = '<canvas id="loanChart"></canvas>';
                    }
                    
                    // Update performance chart with new data
                    updateLoanChart({
                        labels: data.labels || [],
                        disbursements: data.disbursements || [],
                        repayments: data.repayments || [],
                        success: true
                    });
                    
                    // Update distribution chart only on first load (not on period changes)
                    if (data.distribution && !window.distributionChartInitialized) {
                        updateDistributionChart(data.distribution);
                        window.distributionChartInitialized = true;
                    }
                    
                    // Update growth chart with new data
                    if (data.client_growth) {
                        updateGrowthChart(data.client_growth);
                    }
                } else {
                    console.error('API returned error:', data);
                    showChartError(document.getElementById('loanChart'));
                }
            })
            .catch(error => {
                clearTimeout(loadingTimeout);
                console.error('Error loading chart data:', error);
                showChartError(document.getElementById('loanChart'));
                showGlobalError('Failed to load chart data: ' + error.message);
            });
    }

    function updateLoanChart(data) {
        var loanChartEl = document.getElementById('loanChart');
        if (!loanChartEl) return;

        var ctx = loanChartEl.getContext('2d');
        
        // Destroy existing chart if it exists
        if (window.loanChart) {
            window.loanChart.destroy();
        }

        var chartData = {
            labels: data.labels || [],
            datasets: [
                {
                    label: 'Loan Disbursements',
                    data: data.disbursements || [],
                    borderColor: '#3C9EBD',
                    backgroundColor: 'rgba(60, 158, 189, 0.1)',
                    tension: 0.4,
                    fill: true,
                    pointBackgroundColor: '#3C9EBD',
                    pointBorderColor: '#ffffff',
                    pointBorderWidth: 2,
                    pointRadius: 4
                },
                {
                    label: 'Repayments',
                    data: data.repayments || [],
                    borderColor: '#0A3D62',
                    backgroundColor: 'rgba(10, 61, 98, 0.1)',
                    tension: 0.4,
                    fill: true,
                    pointBackgroundColor: '#0A3D62',
                    pointBorderColor: '#ffffff',
                    pointBorderWidth: 2,
                    pointRadius: 4
                }
            ]
        };

        window.loanChart = new Chart(ctx, {
            type: 'line',
            data: chartData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    intersect: false,
                    mode: 'index'
                },
                plugins: {
                    legend: { 
                        position: 'top',
                        labels: {
                            usePointStyle: true,
                            padding: 20
                        }
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        titleColor: '#ffffff',
                        bodyColor: '#ffffff',
                        borderColor: '#3C9EBD',
                        borderWidth: 1,
                        callbacks: {
                            label: function(context) {
                                return context.dataset.label + ': KES ' + context.parsed.y.toLocaleString();
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: {
                            display: false
                        }
                    },
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.1)'
                        },
                        ticks: {
                            callback: function (value) {
                                return 'KES ' + value.toLocaleString();
                            }
                        }
                    }
                }
            }
        });
    }

    function updateDistributionChart(distributionData) {
        var distributionChartEl = document.getElementById('loanDistributionChart');
        if (!distributionChartEl) {
            console.warn('Distribution chart element not found');
            return;
        }
        
        if (!distributionData) {
            console.warn('No distribution data provided');
            showChartError(distributionChartEl);
            return;
        }

        try {
            var distributionCtx = distributionChartEl.getContext('2d');
            
            // Destroy existing chart if it exists
            if (window.distributionChart) {
                window.distributionChart.destroy();
            }

            window.distributionChart = new Chart(distributionCtx, {
                type: 'doughnut',
                data: {
                    labels: distributionData.labels || [],
                    datasets: [{
                        data: distributionData.data || [],
                        backgroundColor: distributionData.colors || [],
                        borderWidth: 2,
                        borderColor: '#ffffff',
                        hoverBorderWidth: 3,
                        hoverBorderColor: '#ffffff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '60%',
                    plugins: {
                        legend: { 
                            position: 'right',
                            labels: {
                                usePointStyle: true,
                                padding: 20,
                                generateLabels: function(chart) {
                                    const data = chart.data;
                                    if (data.labels.length && data.datasets.length) {
                                        return data.labels.map((label, i) => {
                                            const dataset = data.datasets[0];
                                            const value = dataset.data[i];
                                            const total = dataset.data.reduce((a, b) => a + b, 0);
                                            const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
                                            
                                            return {
                                                text: `${label} (${percentage}%)`,
                                                fillStyle: dataset.backgroundColor[i],
                                                strokeStyle: dataset.backgroundColor[i],
                                                pointStyle: 'circle',
                                                hidden: false,
                                                index: i
                                            };
                                        });
                                    }
                                    return [];
                                }
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            titleColor: '#ffffff',
                            bodyColor: '#ffffff',
                            borderColor: '#3C9EBD',
                            borderWidth: 1,
                            callbacks: {
                                label: function(context) {
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = total > 0 ? ((context.parsed / total) * 100).toFixed(1) : 0;
                                    return `${context.label}: ${context.parsed} loans (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });
        } catch (e) {
            console.error('Error updating distribution chart:', e);
            showChartError(distributionChartEl);
        }
    }

    function updateGrowthChart(clientGrowthData) {
        var growthChartEl = document.getElementById('clientGrowthChart');
        if (!growthChartEl) {
            console.warn('Client growth chart element not found');
            return;
        }

        try {
            var growthCtx = growthChartEl.getContext('2d');
            
            // Destroy existing chart if it exists
            if (window.growthChart) {
                window.growthChart.destroy();
            }

            var labels = clientGrowthData.labels || [];
            var data = clientGrowthData.data || [];

            window.growthChart = new Chart(growthCtx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'New Clients',
                        data: data,
                        backgroundColor: 'rgba(46, 204, 113, 0.8)',
                        borderColor: '#2ECC71',
                        borderWidth: 2,
                        borderRadius: 4,
                        borderSkipped: false,
                        hoverBackgroundColor: 'rgba(46, 204, 113, 0.9)',
                        hoverBorderColor: '#27AE60'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { 
                            position: 'top',
                            labels: {
                                usePointStyle: true,
                                padding: 20
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            titleColor: '#ffffff',
                            bodyColor: '#ffffff',
                            borderColor: '#2ECC71',
                            borderWidth: 1,
                            callbacks: {
                                label: function(context) {
                                    const value = context.parsed.y;
                                    return `New Clients: ${value}`;
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: false
                            }
                        },
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.1)'
                            },
                            ticks: { 
                                stepSize: 1,
                                callback: function(value) {
                                    return Math.floor(value) === value ? value : '';
                                }
                            }
                        }
                    }
                }
            });
        } catch (e) {
            console.error('Error updating growth chart:', e);
            showChartError(growthChartEl);
        }
    }

    function initializeDistributionChart() {
        // This function is no longer needed as loadChartData handles everything
        console.log('Distribution chart will be initialized by loadChartData');
    }

    function initializeGrowthChart() {
        var growthChartEl = document.getElementById('clientGrowthChart');
        if (!growthChartEl) {
            console.warn('Growth chart element not found');
            return;
        }

        try {
            // Use existing dashboard data if available
            if (DASHBOARD_DATA && DASHBOARD_DATA.clientGrowth) {
                var clientGrowthData = DASHBOARD_DATA.clientGrowth;
                updateGrowthChart({
                    labels: clientGrowthData.map(function (data) { return data.month; }),
                    data: clientGrowthData.map(function (data) { return parseInt(data.new_clients) || 0; })
                });
            } else if (DASHBOARD_DATA && DASHBOARD_DATA.enhanced && DASHBOARD_DATA.enhanced.client_growth) {
                var enhancedGrowth = DASHBOARD_DATA.enhanced.client_growth;
                updateGrowthChart({
                    labels: enhancedGrowth.map(function (data) { return data.month; }),
                    data: enhancedGrowth.map(function (data) { return data.new_clients; })
                });
            } else {
                // Create default empty chart
                updateGrowthChart({
                    labels: ['No Data'],
                    data: [0]
                });
            }
        } catch (e) {
            console.error('Error initializing growth chart:', e);
            showChartError(growthChartEl);
        }
    }

    function showChartError(element) {
        if (element && element.parentElement) {
            element.parentElement.innerHTML = `
                <div class="flex flex-col items-center justify-center h-64 text-gray-500">
                    <span>📊</span>
                    <p class="text-sm font-medium mb-1">Chart Unavailable</p>
                    <p class="text-xs">Unable to load chart data</p>
                    <button onclick="location.reload()" class="mt-3 px-3 py-1.5 bg-blue-500 text-white rounded text-xs hover:bg-blue-600 transition-colors">
                        <span>🔄</span>Retry
                    </button>
                </div>
            `;
        }
    }

    function showGlobalError(message) {
        var errorDiv = document.createElement('div');
        errorDiv.className = 'fixed top-4 right-4 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
        errorDiv.innerHTML = `
            <div class="flex items-center">
                <span>⚠️</span>
                <span>${message}</span>
                <button onclick="this.parentElement.parentElement.remove()" class="ml-4 text-white hover:text-gray-200">
                    <span>✕</span>
                </button>
            </div>
        `;
        document.body.appendChild(errorDiv);
        
        // Auto-remove after 5 seconds
        setTimeout(() => {
            if (errorDiv.parentElement) {
                errorDiv.remove();
            }
        }, 5000);
    }

    function setupActivityRefresh() {
        // Initial refresh
        refreshActivity();

        // Set up periodic refresh every 60 seconds instead of 30
        var refreshInterval = setInterval(refreshActivity, 60000);

        // Clean up interval when leaving the page
        window.addEventListener('beforeunload', function () {
            if (refreshInterval) {
                clearInterval(refreshInterval);
            }
        });
    }

    function refreshActivity() {
        var button = document.querySelector('button i.fa-sync-alt');
        if (button) button.classList.add('fa-spin');

        fetch('/api/recent-activity/', {
            headers: {
                'X-CSRFToken': getCsrfToken()
            }
        })
            .then(response => {
                if (!response.ok) {
                    if (response.status === 403) {
                        throw new Error('session_timeout');
                    }
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(updateActivityList)
            .catch(error => {
                if (error.message === 'session_timeout') {
                    handleSessionTimeout();
                } else {
                    handleActivityError(error);
                }
            })
            .finally(function () {
                if (button) button.classList.remove('fa-spin');
            });
    }

    function handleResponse(response) {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    }

    function updateActivityList(data) {
        var activityList = document.getElementById('activityList');
        if (!activityList) return;

        try {
            if (!data.activities || !data.activities.length) {
                activityList.innerHTML = '<li><p class="text-sm text-gray-500 text-center">No recent activity</p></li>';
                return;
            }

            activityList.innerHTML = data.activities.map(createActivityHTML).join('');
            updateTimeagoElements(activityList);
        } catch (e) {
            console.error('Error updating activity list:', e);
            throw e;
        }
    }

    function createActivityHTML(activity) {
        if (!activity) return '';

        var color = getActivityColor(activity.type);
        var icon = activity.icon || 'info';
        var user = activity.user || 'Unknown';
        var action = activity.action || '';
        var timestamp = activity.timestamp;

        return `
        <li>
            <div class="relative pb-8">
                <span class="absolute left-4 top-4 -ml-px h-full w-0.5 bg-gray-200"></span>
                <div class="relative flex space-x-3">
                    <div>
                        <span class="h-8 w-8 rounded-full flex items-center justify-center ring-8 ring-white ${color}">
                            <i class="fas fa-${icon} h-5 w-5 text-white"></i>
                        </span>
                    </div>
                    <div class="flex min-w-0 flex-1 justify-between space-x-4 pt-1.5">
                        <div>
                            <p class="text-sm text-gray-500">
                                <span class="font-medium text-gray-900">${user}</span> ${action}
                            </p>
                        </div>
                        <div class="whitespace-nowrap text-right text-sm text-gray-500">
                            <time datetime="${timestamp}" class="timeago">${timeago.format(timestamp)}</time>
                        </div>
                    </div>
                </div>
            </div>
        </li>
    `;
    }

    function updateTimeagoElements(container) {
        container.querySelectorAll('.timeago').forEach(function (node) {
            try {
                var datetime = node.getAttribute('datetime');
                if (datetime) {
                    node.textContent = timeago.format(datetime);
                }
            } catch (e) {
                console.warn('Error updating timeago element:', e);
            }
        });
    }

    function handleActivityError(error) {
        console.error('Error refreshing activity:', error);
        var activityList = document.getElementById('activityList');
        if (activityList) {
            activityList.innerHTML = '<li><p class="text-sm text-gray-500 text-center">Error loading activities</p></li>';
        }
    }

    function getActivityColor(type) {
        var colors = {
            delete: 'bg-red-500',
            create: 'bg-green-500',
            update: 'bg-blue-500',
            payment: 'bg-purple-500'
        };
        return colors[type] || 'bg-gray-500';
    }

    // Make updateChart available globally with error handling
    window.updateChart = function (period) {
        if (period === window.currentPeriod) return;

        try {
            console.log('Updating chart for period:', period);
            updatePeriodButtons(period);
            window.currentPeriod = period;
            
            // Load new data for all charts
            loadChartData(period);
        } catch (e) {
            console.error('Error in updateChart:', e);
            showGlobalError('Failed to update chart period');
        }
    };



    function fetchChartData(period) {
        fetch('/api/loan-data/?period=' + period, {
            headers: {
                'X-CSRFToken': getCsrfToken()
            }
        })
            .then(response => {
                if (!response.ok) {
                    if (response.status === 403) {
                        throw new Error('session_timeout');
                    }
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(function (data) {
                if (!window.loanChart) return;

                window.loanChart.data.labels = data.labels || [];
                window.loanChart.data.datasets[0].data = (data.disbursements || []).map(function (val) { return parseFloat(val) || 0; });
                window.loanChart.data.datasets[1].data = (data.repayments || []).map(function (val) { return parseFloat(val) || 0; });
                window.loanChart.update();
            })
            .catch(function (error) {
                if (error.message === 'session_timeout') {
                    handleSessionTimeout();
                } else {
                    console.error('Error updating chart:', error);
                }
            });
    }

// PDF Generation Functions
function generateDashboardPDF(dashboardType) {
    const button = event.target.closest('button');
    const originalText = button.innerHTML;
    
    // Show loading state
    button.innerHTML = '<span>⟳</span>Generating PDF...';
    button.disabled = true;
    
    // Determine the correct URL based on dashboard type
    let pdfUrl;
    switch(dashboardType) {
        case 'loans':
            pdfUrl = '{% url "loans:generate_loans_dashboard_pdf" %}';
            break;
        case 'clients':
            pdfUrl = '{% url "loans:generate_clients_dashboard_pdf" %}';
            break;
        case 'payments':
            pdfUrl = '{% url "loans:generate_payments_dashboard_pdf" %}';
            break;
        case 'reports':
            pdfUrl = '{% url "loans:generate_reports_dashboard_pdf" %}';
            break;
        case 'portfolio':
            pdfUrl = '{% url "loans:generate_portfolio_dashboard_pdf" %}';
            break;
        default:
            pdfUrl = '{% url "loans:generate_loans_dashboard_pdf" %}';
    }
    
    // Create a temporary link to download the PDF
    const link = document.createElement('a');
    link.href = pdfUrl;
    link.download = `${dashboardType}_dashboard_report_${new Date().toISOString().slice(0,10)}.pdf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    // Reset button after a delay
    setTimeout(() => {
        button.innerHTML = originalText;
        button.disabled = false;
    }, 3000);
}

// Make analytics boxes more interactive
document.addEventListener('DOMContentLoaded', function() {
    // Add click animations to analytics boxes
    const analyticsBoxes = document.querySelectorAll('.stats-card');
    analyticsBoxes.forEach(box => {
        box.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-2px)';
            this.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
        });
        
        box.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = '';
        });
    });
});
</script>
{% endblock %}