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

{% block title %}Permission Cache Performance Dashboard{% endblock %}

{% block extra_css %}
<style>
    .cache-stats-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
    }
    
    .cache-metric {
        text-align: center;
        padding: 15px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 8px;
        margin: 5px;
    }
    
    .cache-metric h4 {
        margin: 0;
        font-size: 2em;
        font-weight: bold;
    }
    
    .cache-metric p {
        margin: 5px 0 0 0;
        opacity: 0.9;
    }
    
    .recommendation-card {
        border-left: 4px solid;
        padding: 15px;
        margin-bottom: 10px;
        border-radius: 0 5px 5px 0;
    }
    
    .recommendation-success {
        border-left-color: #28a745;
        background-color: #d4edda;
    }
    
    .recommendation-warning {
        border-left-color: #ffc107;
        background-color: #fff3cd;
    }
    
    .recommendation-info {
        border-left-color: #17a2b8;
        background-color: #d1ecf1;
    }
    
    .recommendation-error {
        border-left-color: #dc3545;
        background-color: #f8d7da;
    }
    
    .cache-action-btn {
        margin: 5px;
    }
    
    .redis-stats {
        background: #f8f9fa;
        border-radius: 5px;
        padding: 15px;
        margin-top: 15px;
    }
    
    .auto-refresh {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 1000;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- Auto-refresh toggle -->
    <div class="auto-refresh">
        <div class="form-check form-switch">
            <input class="form-check-input" type="checkbox" id="autoRefresh">
            <label class="form-check-label" for="autoRefresh">Auto Refresh (30s)</label>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <h1><i class="fas fa-tachometer-alt"></i> Permission Cache Performance Dashboard</h1>
            <p class="text-muted">Monitor and manage permission caching system performance</p>
        </div>
    </div>

    <!-- Cache Statistics Overview -->
    <div class="row">
        <div class="col-12">
            <div class="cache-stats-card">
                <h3><span>📈</span> Cache Performance Overview</h3>
                <div class="row">
                    <div class="col-md-3">
                        <div class="cache-metric">
                            <h4 id="hit-rate">{{ cache_stats.hit_rate_percentage|floatformat:1 }}%</h4>
                            <p>Hit Rate</p>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="cache-metric">
                            <h4 id="total-hits">{{ cache_stats.total_hits|default:0 }}</h4>
                            <p>Total Hits</p>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="cache-metric">
                            <h4 id="total-misses">{{ cache_stats.total_misses|default:0 }}</h4>
                            <p>Total Misses</p>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="cache-metric">
                            <h4 id="backend">{{ cache_stats.cache_backend|default:"Unknown" }}</h4>
                            <p>Backend</p>
                        </div>
                    </div>
                </div>
                
                {% if cache_stats.redis_stats %}
                <div class="redis-stats">
                    <h5><i class="fab fa-redis"></i> Redis Statistics</h5>
                    <div class="row">
                        <div class="col-md-3">
                            <strong>Memory Used:</strong> {{ cache_stats.redis_stats.used_memory }}
                        </div>
                        <div class="col-md-3">
                            <strong>Connected Clients:</strong> {{ cache_stats.redis_stats.connected_clients }}
                        </div>
                        <div class="col-md-3">
                            <strong>Commands Processed:</strong> {{ cache_stats.redis_stats.total_commands_processed }}
                        </div>
                        <div class="col-md-3">
                            <strong>Keyspace Hits:</strong> {{ cache_stats.redis_stats.keyspace_hits }}
                        </div>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Cache Management Actions -->
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h4><span>🛠️</span> Cache Management Actions</h4>
                </div>
                <div class="card-body">
                    <!-- Warm Cache Actions -->
                    <h5>Warm Cache</h5>
                    <form method="post" action="{% url 'warm_cache_action' %}" class="mb-3">
                        {% csrf_token %}
                        <input type="hidden" name="action_type" value="critical_users">
                        <div class="input-group mb-2">
                            <input type="number" name="limit" class="form-control" value="50" min="1" max="200">
                            <button type="submit" class="btn btn-primary cache-action-btn">
                                <span>🔥</span> Warm Critical Users
                            </button>
                        </div>
                    </form>

                    <form method="post" action="{% url 'warm_cache_action' %}" class="mb-3">
                        {% csrf_token %}
                        <input type="hidden" name="action_type" value="role_users">
                        <div class="input-group mb-2">
                            <select name="role" class="form-control" required>
                                <option value="">Select Role</option>
                                <option value="admin">Admin</option>
                                <option value="team_leader">Team Leader</option>
                                <option value="loan_officer">Loan Officer</option>
                                <option value="secretary">Secretary</option>
                                <option value="auditor">Auditor</option>
                            </select>
                            <input type="number" name="limit" class="form-control" value="20" min="1" max="100">
                            <button type="submit" class="btn btn-info cache-action-btn">
                                <span>👥</span> Warm Role Users
                            </button>
                        </div>
                    </form>

                    <hr>

                    <!-- Invalidate Cache Actions -->
                    <h5>Invalidate Cache</h5>
                    <form method="post" action="{% url 'invalidate_cache_action' %}" class="mb-3">
                        {% csrf_token %}
                        <input type="hidden" name="action_type" value="specific_user">
                        <div class="input-group mb-2">
                            <input type="text" name="user_id" class="form-control" placeholder="User ID" required>
                            <input type="text" name="page_name" class="form-control" placeholder="Page (optional)">
                            <button type="submit" class="btn btn-warning cache-action-btn">
                                <span>🗑️</span> Invalidate User
                            </button>
                        </div>
                    </form>

                    <form method="post" action="{% url 'invalidate_cache_action' %}" class="mb-3">
                        {% csrf_token %}
                        <input type="hidden" name="action_type" value="role_cache">
                        <div class="input-group mb-2">
                            <select name="role" class="form-control" required>
                                <option value="">Select Role</option>
                                <option value="admin">Admin</option>
                                <option value="team_leader">Team Leader</option>
                                <option value="loan_officer">Loan Officer</option>
                                <option value="secretary">Secretary</option>
                                <option value="auditor">Auditor</option>
                            </select>
                            <button type="submit" class="btn btn-danger cache-action-btn">
                                <i class="fas fa-user-times"></i> Invalidate Role
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Recommendations -->
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h4><span>💡</span> Performance Recommendations</h4>
                </div>
                <div class="card-body">
                    {% if recommendations %}
                        {% for rec in recommendations %}
                        <div class="recommendation-card recommendation-{{ rec.type }}">
                            <h6><strong>{{ rec.title }}</strong></h6>
                            <p>{{ rec.message }}</p>
                            {% if rec.action %}
                            <small class="text-muted">Recommended Action: {{ rec.action }}</small>
                            {% endif %}
                        </div>
                        {% endfor %}
                    {% else %}
                        <p class="text-muted">No specific recommendations at this time.</p>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <!-- Session Statistics -->
    {% if cache_stats.session_stats %}
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4><span>⏰</span> Current Session Statistics</h4>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="text-center">
                                <h5>{{ cache_stats.session_stats.hits }}</h5>
                                <p class="text-muted">Session Hits</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h5>{{ cache_stats.session_stats.misses }}</h5>
                                <p class="text-muted">Session Misses</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h5>{{ cache_stats.session_stats.invalidations }}</h5>
                                <p class="text-muted">Session Invalidations</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h5>{{ cache_stats.session_stats.warm_operations }}</h5>
                                <p class="text-muted">Session Warm Ops</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% endif %}

    <!-- Last Updated -->
    <div class="row mt-3">
        <div class="col-12">
            <p class="text-muted text-center">
                Last updated: <span id="last-updated">{{ last_updated|date:"Y-m-d H:i:s" }}</span>
            </p>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    let autoRefreshInterval;
    const autoRefreshCheckbox = document.getElementById('autoRefresh');
    
    // Auto-refresh functionality
    autoRefreshCheckbox.addEventListener('change', function() {
        if (this.checked) {
            autoRefreshInterval = setInterval(refreshStats, 30000); // 30 seconds
        } else {
            clearInterval(autoRefreshInterval);
        }
    });
    
    function refreshStats() {
        fetch('{% url "cache_statistics_api" %}')
            .then(response => response.json())
            .then(data => {
                if (!data.error) {
                    // Update statistics
                    document.getElementById('hit-rate').textContent = 
                        parseFloat(data.hit_rate_percentage || 0).toFixed(1) + '%';
                    document.getElementById('total-hits').textContent = 
                        data.total_hits || 0;
                    document.getElementById('total-misses').textContent = 
                        data.total_misses || 0;
                    document.getElementById('backend').textContent = 
                        data.cache_backend || 'Unknown';
                    document.getElementById('last-updated').textContent = 
                        data.server_time || new Date().toLocaleString();
                }
            })
            .catch(error => {
                console.error('Error refreshing cache stats:', error);
            });
    }
    
    // Add confirmation to destructive actions
    document.querySelectorAll('form[action*="invalidate"]').forEach(form => {
        form.addEventListener('submit', function(e) {
            if (!confirm('Are you sure you want to invalidate cache? This action cannot be undone.')) {
                e.preventDefault();
            }
        });
    });
    
    // Add loading states to buttons
    document.querySelectorAll('button[type="submit"]').forEach(button => {
        button.addEventListener('click', function() {
            const originalText = this.innerHTML;
            this.innerHTML = '<span>⟳</span> Processing...';
            this.disabled = true;
            
            // Re-enable after form submission (in case of validation errors)
            setTimeout(() => {
                this.innerHTML = originalText;
                this.disabled = false;
            }, 5000);
        });
    });
});
</script>
{% endblock %}