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

{% block title %}Reports API Dashboard{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'css/reports-api.css' %}">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
{% endblock %}

{% block content %}
<div class="dashboard-container">
    <!-- Loading Indicator -->
    <div id="loading-indicator" class="loading-indicator">
        <div class="loading-spinner"></div>
        <div>Loading data...</div>
    </div>
    
    <!-- Notification Container -->
    <div id="notification-container" class="notification-container"></div>
    
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1>Reports & Analytics Dashboard</h1>
        <div class="d-flex align-items-center gap-3">
            <!-- Real-time indicator -->
            <div class="real-time-indicator">
                <div id="real-time-dot" class="real-time-dot"></div>
                <span id="real-time-status">Real-time updates active</span>
            </div>
            
            <!-- Auto-refresh toggle -->
            <div class="auto-refresh-toggle">
                <label for="auto-refresh">Auto-refresh:</label>
                <input type="checkbox" id="auto-refresh" checked>
            </div>
            
            <!-- Manual refresh button -->
            <button id="refresh-btn" class="btn btn-outline-primary btn-sm">
                <span>🔄</span> Refresh
            </button>
        </div>
    </div>
    
    <!-- Search -->
    <div class="search-container">
        <input type="text" id="global-search" class="search-input" placeholder="Search loans, customers, requests...">
        <button id="search-btn" class="search-btn">
            <span>🔍</span>
        </button>
        <div id="search-results" class="search-results"></div>
    </div>
    
    <!-- Summary Cards -->
    <div class="summary-cards">
        <div class="summary-card success">
            <div class="summary-card-title">Total Active Loans</div>
            <div id="metric-total-active-loans" class="summary-card-value">0</div>
            <div class="summary-card-change positive">
                <span>↑</span>
                <span>+5.2% from last month</span>
            </div>
        </div>
        
        <div class="summary-card info">
            <div class="summary-card-title">Portfolio Value</div>
            <div id="metric-total-portfolio-value" class="summary-card-value">KES 0</div>
            <div class="summary-card-change positive">
                <span>↑</span>
                <span>+12.8% from last month</span>
            </div>
        </div>
        
        <div class="summary-card warning">
            <div class="summary-card-title">Outstanding Balance</div>
            <div id="metric-total-outstanding" class="summary-card-value">KES 0</div>
            <div class="summary-card-change negative">
                <span>↓</span>
                <span>-3.1% from last month</span>
            </div>
        </div>
        
        <div class="summary-card success">
            <div class="summary-card-title">Collection Rate</div>
            <div id="metric-collection-rate" class="summary-card-value">0%</div>
            <div class="summary-card-change positive">
                <span>↑</span>
                <span>+2.4% from last month</span>
            </div>
        </div>
        
        <div class="summary-card danger">
            <div class="summary-card-title">Loans Due Today</div>
            <div id="metric-loans-due-today" class="summary-card-value">0</div>
            <div class="summary-card-change">
                <span>⏰</span>
                <span>Requires attention</span>
            </div>
        </div>
        
        <div class="summary-card danger">
            <div class="summary-card-title">Overdue Loans</div>
            <div id="metric-overdue-loans" class="summary-card-value">0</div>
            <div class="summary-card-change negative">
                <span>⚠️</span>
                <span>Action required</span>
            </div>
        </div>
    </div>
    
    <!-- Filter Controls -->
    <div class="filter-controls">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h5>Filters & Controls</h5>
            <div class="export-controls">
                <select id="export-format" class="export-format-select">
                    <option value="csv">CSV</option>
                    <option value="excel">Excel</option>
                    <option value="pdf">PDF</option>
                </select>
                <button id="export-btn" class="export-btn">
                    <span>⬇️</span> Export
                </button>
            </div>
        </div>
        
        <div class="filter-row">
            <div class="filter-group">
                <label for="report-type">Report Type</label>
                <select id="report-type">
                    <option value="dashboard">Dashboard Overview</option>
                    <option value="loans_due">Loans Due</option>
                    <option value="delinquent_loans">Delinquent Loans</option>
                    <option value="loans_in_arrears">Loans in Arrears</option>
                    <option value="processing_fees">Processing Fees</option>
                    <option value="interest_income">Interest Income</option>
                    <option value="registration_fees">Registration Fees</option>
                    <option value="customer_requests">Customer Requests</option>
                </select>
            </div>
            
            <div class="filter-group">
                <label for="start-date">Start Date</label>
                <input type="date" id="start-date">
            </div>
            
            <div class="filter-group">
                <label for="end-date">End Date</label>
                <input type="date" id="end-date">
            </div>
            
            <div class="filter-group">
                <label for="status-filter">Status</label>
                <select id="status-filter">
                    <option value="">All Statuses</option>
                    <option value="active">Active</option>
                    <option value="completed">Completed</option>
                    <option value="overdue">Overdue</option>
                    <option value="pending">Pending</option>
                </select>
            </div>
            
            <div class="filter-group">
                <label for="amount-min">Min Amount</label>
                <input type="number" id="amount-min" placeholder="0">
            </div>
            
            <div class="filter-group">
                <label for="amount-max">Max Amount</label>
                <input type="number" id="amount-max" placeholder="1000000">
            </div>
        </div>
        
        <div class="quick-filters">
            <span style="font-size: 12px; color: #6c757d; margin-right: 10px;">Quick Filters:</span>
            <button class="quick-filter-btn" data-period="today">Today</button>
            <button class="quick-filter-btn" data-period="week">This Week</button>
            <button class="quick-filter-btn active" data-period="month">This Month</button>
            <button class="quick-filter-btn" data-period="quarter">This Quarter</button>
        </div>
    </div>
    
    <!-- Charts -->
    <div class="charts-container">
        <div class="chart-card">
            <div class="chart-title">Loan Status Distribution</div>
            <div class="chart-container">
                <canvas id="chart-loan-status-distribution"></canvas>
            </div>
        </div>
        
        <div class="chart-card">
            <div class="chart-title">Delinquency Analysis</div>
            <div class="chart-container">
                <canvas id="chart-delinquency-analysis"></canvas>
            </div>
        </div>
        
        <div class="chart-card">
            <div class="chart-title">Revenue Trends</div>
            <div class="chart-container">
                <canvas id="chart-revenue-trends"></canvas>
            </div>
        </div>
        
        <div class="chart-card">
            <div class="chart-title">Monthly Performance</div>
            <div class="chart-container">
                <canvas id="chart-monthly-performance"></canvas>
            </div>
        </div>
    </div>
    
    <!-- Data Table -->
    <div class="data-table-container">
        <div class="d-flex justify-content-between align-items-center p-3 border-bottom">
            <h5 class="mb-0">Data Records</h5>
            <div class="page-size-selector">
                <span>Show:</span>
                <select id="page-size">
                    <option value="10">10</option>
                    <option value="25" selected>25</option>
                    <option value="50">50</option>
                    <option value="100">100</option>
                </select>
                <span>per page</span>
            </div>
        </div>
        
        <table class="data-table">
            <thead>
                <tr id="table-headers">
                    <th>ID</th>
                    <th>Name/Number</th>
                    <th>Amount</th>
                    <th>Status</th>
                    <th>Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="data-table-body">
                <!-- Dynamic content will be loaded here -->
            </tbody>
        </table>
        
        <div class="pagination-container">
            <div id="pagination-info" class="pagination-info">
                Showing 0-0 of 0 items
            </div>
            
            <div id="pagination-container" class="pagination-controls">
                <!-- Pagination buttons will be generated here -->
            </div>
        </div>
    </div>
    
    <!-- Summary Statistics -->
    <div class="row mt-4">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h6>Summary Statistics</h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-6">
                            <div class="text-muted small">Total Records</div>
                            <div id="summary-total-loans" class="h5">0</div>
                        </div>
                        <div class="col-6">
                            <div class="text-muted small">Total Amount</div>
                            <div id="summary-total-amount" class="h5">KES 0</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h6>Performance Metrics</h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-6">
                            <div class="text-muted small">Success Rate</div>
                            <div id="summary-success-rate" class="h5">0%</div>
                        </div>
                        <div class="col-6">
                            <div class="text-muted small">Average Amount</div>
                            <div id="summary-average-amount" class="h5">KES 0</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- API Testing Panel (Development Only) -->
{% if debug %}
<div class="card mt-4">
    <div class="card-header">
        <h6>API Testing Panel</h6>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-4">
                <button id="test-dashboard-api" class="btn btn-outline-primary btn-sm mb-2 w-100">
                    Test Dashboard API
                </button>
                <button id="test-filter-api" class="btn btn-outline-info btn-sm mb-2 w-100">
                    Test Filter API
                </button>
                <button id="test-pagination-api" class="btn btn-outline-success btn-sm mb-2 w-100">
                    Test Pagination API
                </button>
            </div>
            <div class="col-md-4">
                <button id="test-realtime-api" class="btn btn-outline-warning btn-sm mb-2 w-100">
                    Test Real-time API
                </button>
                <button id="test-search-api" class="btn btn-outline-secondary btn-sm mb-2 w-100">
                    Test Search API
                </button>
                <button id="clear-cache" class="btn btn-outline-danger btn-sm mb-2 w-100">
                    Clear Cache
                </button>
            </div>
            <div class="col-md-4">
                <div class="small">
                    <div>Cache Size: <span id="cache-size">0</span></div>
                    <div>Last Update: <span id="last-update">Never</span></div>
                    <div>API Status: <span id="api-status" class="text-success">Ready</span></div>
                </div>
            </div>
        </div>
        <div class="mt-3">
            <textarea id="api-response" class="form-control" rows="8" placeholder="API responses will appear here..." readonly></textarea>
        </div>
    </div>
</div>
{% endif %}
{% endblock %}

{% block extra_js %}
<script src="{% static 'js/reports-api.js' %}"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Set default date range to current month
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    
    document.getElementById('start-date').value = firstDay.toISOString().split('T')[0];
    document.getElementById('end-date').value = today.toISOString().split('T')[0];
    
    // Development API testing (only if debug mode)
    {% if debug %}
    setupAPITesting();
    {% endif %}
});

{% if debug %}
function setupAPITesting() {
    const apiResponseTextarea = document.getElementById('api-response');
    
    document.getElementById('test-dashboard-api').addEventListener('click', async () => {
        try {
            const data = await window.reportsAPI.getDashboardData({ refresh: true });
            apiResponseTextarea.value = JSON.stringify(data, null, 2);
            document.getElementById('api-status').textContent = 'Success';
            document.getElementById('api-status').className = 'text-success';
        } catch (error) {
            apiResponseTextarea.value = `Error: ${error.message}`;
            document.getElementById('api-status').textContent = 'Error';
            document.getElementById('api-status').className = 'text-danger';
        }
    });
    
    document.getElementById('test-filter-api').addEventListener('click', async () => {
        try {
            const data = await window.reportsAPI.getFilteredReportData({
                reportType: 'loans_due',
                startDate: '2024-01-01',
                endDate: '2024-12-31'
            });
            apiResponseTextarea.value = JSON.stringify(data, null, 2);
        } catch (error) {
            apiResponseTextarea.value = `Error: ${error.message}`;
        }
    });
    
    document.getElementById('test-pagination-api').addEventListener('click', async () => {
        try {
            const data = await window.reportsAPI.getPaginatedData({
                dataType: 'loans',
                page: 1,
                pageSize: 10
            });
            apiResponseTextarea.value = JSON.stringify(data, null, 2);
        } catch (error) {
            apiResponseTextarea.value = `Error: ${error.message}`;
        }
    });
    
    document.getElementById('test-realtime-api').addEventListener('click', async () => {
        try {
            const data = await window.reportsAPI.getRealTimeUpdates(['summary_metrics', 'loans_due_today']);
            apiResponseTextarea.value = JSON.stringify(data, null, 2);
        } catch (error) {
            apiResponseTextarea.value = `Error: ${error.message}`;
        }
    });
    
    document.getElementById('test-search-api').addEventListener('click', async () => {
        try {
            const data = await window.reportsAPI.search('test', { type: 'all', limit: 5 });
            apiResponseTextarea.value = JSON.stringify(data, null, 2);
        } catch (error) {
            apiResponseTextarea.value = `Error: ${error.message}`;
        }
    });
    
    document.getElementById('clear-cache').addEventListener('click', () => {
        window.reportsAPI.clearCache();
        updateCacheStats();
        apiResponseTextarea.value = 'Cache cleared successfully';
    });
    
    function updateCacheStats() {
        const stats = window.reportsAPI.getCacheStats();
        document.getElementById('cache-size').textContent = stats.size;
        document.getElementById('last-update').textContent = window.reportsAPI.lastUpdate || 'Never';
    }
    
    // Update cache stats every 5 seconds
    setInterval(updateCacheStats, 5000);
    updateCacheStats();
}
{% endif %}
</script>
{% endblock %}