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

{% block title %}Admin Activities{% endblock %}
{% block page_title %}Admin Activities{% endblock %}

{% block content %}
<!-- Header -->
<div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 space-y-4 sm:space-y-0">
    <div>
        <h1 class="text-2xl font-bold text-gray-900">Admin Activities</h1>
        <p class="text-gray-600">Track all administrative actions and changes</p>
    </div>
    <div class="flex space-x-3">
        <button onclick="refreshActivities()" class="bg-matrichaya-green hover:bg-matrichaya-dark-green text-white px-4 py-2 rounded-lg font-semibold transition duration-200">
            <i class="fas fa-sync-alt mr-2"></i>Refresh
        </button>
        <button onclick="exportActivities()" class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg font-semibold transition duration-200">
            <i class="fas fa-download mr-2"></i>Export
        </button>
        <a href="{% url 'custom_admin:delete_all_activities' %}" 
           class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg font-semibold transition duration-200"
           onclick="return confirm('Are you sure you want to delete ALL activities? This action cannot be undone!')">
            <i class="fas fa-trash mr-2"></i>Delete All
        </a>
    </div>
</div>

<!-- Statistics Cards -->
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 lg:gap-6 mb-6">
    <div class="bg-white rounded-lg shadow-md p-6">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-sm font-medium text-gray-600">Total Activities</p>
                <p class="text-3xl font-bold text-gray-900">{{ total_activities }}</p>
                <p class="text-xs text-gray-500 mt-1">All time</p>
            </div>
            <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                <i class="fas fa-history text-blue-600 text-xl"></i>
            </div>
        </div>
    </div>
    
    <div class="bg-white rounded-lg shadow-md p-6">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-sm font-medium text-gray-600">Today's Activities</p>
                <p class="text-3xl font-bold text-gray-900">{{ today_activities }}</p>
                <p class="text-xs text-gray-500 mt-1">Last 24 hours</p>
            </div>
            <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                <i class="fas fa-calendar-day text-green-600 text-xl"></i>
            </div>
        </div>
    </div>
    
    <div class="bg-white rounded-lg shadow-md p-6">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-sm font-medium text-gray-600">This Week</p>
                <p class="text-3xl font-bold text-gray-900">{{ week_activities }}</p>
                <p class="text-xs text-gray-500 mt-1">Last 7 days</p>
            </div>
            <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                <i class="fas fa-calendar-week text-purple-600 text-xl"></i>
            </div>
        </div>
    </div>
    
    <div class="bg-white rounded-lg shadow-md p-6">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-sm font-medium text-gray-600">This Month</p>
                <p class="text-3xl font-bold text-gray-900">{{ month_activities }}</p>
                <p class="text-xs text-gray-500 mt-1">Last 30 days</p>
            </div>
            <div class="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                <i class="fas fa-calendar-alt text-orange-600 text-xl"></i>
            </div>
        </div>
    </div>
</div>


<!-- Filters -->
<div class="bg-white rounded-lg shadow-md p-4 lg:p-6 mb-6">
    <form method="get" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Filter by Admin</label>
            <input type="text" 
                   name="admin" 
                   value="{{ admin_filter }}"
                   placeholder="Search by admin username..."
                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-matrichaya-green focus:border-transparent">
        </div>
        
        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Filter by Action</label>
            <select name="action" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-matrichaya-green focus:border-transparent">
                <option value="">All Actions</option>
                {% for action_code, action_name in action_types %}
                    <option value="{{ action_code }}" {% if action_filter == action_code %}selected{% endif %}>{{ action_name }}</option>
                {% endfor %}
            </select>
        </div>
        
        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Filter by Model</label>
            <select name="model" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-matrichaya-green focus:border-transparent">
                <option value="">All Models</option>
                {% for model in model_types %}
                    <option value="{{ model }}" {% if model_filter == model %}selected{% endif %}>{{ model }}</option>
                {% endfor %}
            </select>
        </div>
        
        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Date Range</label>
            <select name="date_range" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-matrichaya-green focus:border-transparent">
                <option value="">All Time</option>
                <option value="today" {% if date_filter == 'today' %}selected{% endif %}>Today</option>
                <option value="week" {% if date_filter == 'week' %}selected{% endif %}>This Week</option>
                <option value="month" {% if date_filter == 'month' %}selected{% endif %}>This Month</option>
                <option value="year" {% if date_filter == 'year' %}selected{% endif %}>This Year</option>
            </select>
        </div>
        
        <div class="flex items-end space-x-2">
            <button type="submit" 
                    class="flex-1 bg-matrichaya-green hover:bg-matrichaya-dark-green text-white px-4 py-2 rounded-lg transition duration-200">
                <i class="fas fa-search mr-2"></i>
                Filter
            </button>
            <a href="{% url 'custom_admin:activities' %}" 
               class="flex-1 bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg transition duration-200 text-center">
                <i class="fas fa-times mr-2"></i>
                Clear
            </a>
        </div>
    </form>
</div>

<!-- Activities Table -->
<div class="bg-white rounded-lg shadow-md overflow-hidden">
    {% if page_obj %}
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Admin</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Action</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Model</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Description</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">IP Address</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Timestamp</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {% for activity in page_obj %}
                        <tr class="hover:bg-gray-50">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="w-8 h-8 bg-gray-300 rounded-full flex items-center justify-center mr-3">
                                        <i class="fas fa-user text-gray-600 text-sm"></i>
                                    </div>
                                    <div class="text-sm font-medium text-gray-900">{{ activity.admin.username }}</div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                                    {% if activity.action == 'create' %}bg-green-100 text-green-800
                                    {% elif activity.action == 'update' %}bg-blue-100 text-blue-800
                                    {% elif activity.action == 'delete' %}bg-red-100 text-red-800
                                    {% elif activity.action == 'login' %}bg-purple-100 text-purple-800
                                    {% elif activity.action == 'logout' %}bg-gray-100 text-gray-800
                                    {% else %}bg-yellow-100 text-yellow-800{% endif %}">
                                    {% if activity.action == 'create' %}
                                        <i class="fas fa-plus mr-1"></i>
                                    {% elif activity.action == 'update' %}
                                        <i class="fas fa-edit mr-1"></i>
                                    {% elif activity.action == 'delete' %}
                                        <i class="fas fa-trash mr-1"></i>
                                    {% elif activity.action == 'login' %}
                                        <i class="fas fa-sign-in-alt mr-1"></i>
                                    {% elif activity.action == 'logout' %}
                                        <i class="fas fa-sign-out-alt mr-1"></i>
                                    {% else %}
                                        <i class="fas fa-eye mr-1"></i>
                                    {% endif %}
                                    {{ activity.get_action_display }}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ activity.model_name }}</td>
                            <td class="px-6 py-4 text-sm text-gray-900 max-w-xs truncate">{{ activity.description }}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ activity.ip_address }}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <div class="timestamp" data-timestamp="{{ activity.timestamp|date:'c' }}">
                                    {{ activity.timestamp|date:"M d, Y" }}
                                </div>
                                <div class="text-xs text-gray-400">{{ activity.timestamp|time:"H:i:s" }}</div>
                            </td>
                        </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        {% if page_obj.has_other_pages %}
            <div class="bg-white px-4 py-3 border-t border-gray-200 sm:px-6">
                <div class="flex items-center justify-between">
                    <div class="flex-1 flex justify-between sm:hidden">
                        {% if page_obj.has_previous %}
                            <a href="?page={{ page_obj.previous_page_number }}{% if admin_filter %}&admin={{ admin_filter }}{% endif %}{% if action_filter %}&action={{ action_filter }}{% endif %}{% if model_filter %}&model={{ model_filter }}{% endif %}{% if date_filter %}&date_range={{ date_filter }}{% endif %}" 
                               class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                                Previous
                            </a>
                        {% endif %}
                        {% if page_obj.has_next %}
                            <a href="?page={{ page_obj.next_page_number }}{% if admin_filter %}&admin={{ admin_filter }}{% endif %}{% if action_filter %}&action={{ action_filter }}{% endif %}{% if model_filter %}&model={{ model_filter }}{% endif %}{% if date_filter %}&date_range={{ date_filter }}{% endif %}" 
                               class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                                Next
                            </a>
                        {% endif %}
                    </div>
                    <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                        <div>
                            <p class="text-sm text-gray-700">
                                Showing {{ page_obj.start_index }} to {{ page_obj.end_index }} of {{ page_obj.paginator.count }} results
                            </p>
                        </div>
                        <div>
                            <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                                {% if page_obj.has_previous %}
                                    <a href="?page={{ page_obj.previous_page_number }}{% if admin_filter %}&admin={{ admin_filter }}{% endif %}{% if action_filter %}&action={{ action_filter }}{% endif %}{% if model_filter %}&model={{ model_filter }}{% endif %}{% if date_filter %}&date_range={{ date_filter }}{% endif %}" 
                                       class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                                        <i class="fas fa-chevron-left"></i>
                                    </a>
                                {% endif %}
                                
                                {% for num in page_obj.paginator.page_range %}
                                    {% if page_obj.number == num %}
                                        <span class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-matrichaya-green text-sm font-medium text-white">
                                            {{ num }}
                                        </span>
                                    {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                                        <a href="?page={{ num }}{% if admin_filter %}&admin={{ admin_filter }}{% endif %}{% if action_filter %}&action={{ action_filter }}{% endif %}{% if model_filter %}&model={{ model_filter }}{% endif %}{% if date_filter %}&date_range={{ date_filter }}{% endif %}" 
                                           class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">
                                            {{ num }}
                                        </a>
                                    {% endif %}
                                {% endfor %}
                                
                                {% if page_obj.has_next %}
                                    <a href="?page={{ page_obj.next_page_number }}{% if admin_filter %}&admin={{ admin_filter }}{% endif %}{% if action_filter %}&action={{ action_filter }}{% endif %}{% if model_filter %}&model={{ model_filter }}{% endif %}{% if date_filter %}&date_range={{ date_filter }}{% endif %}" 
                                       class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                                        <i class="fas fa-chevron-right"></i>
                                    </a>
                                {% endif %}
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        {% endif %}
    {% else %}
        <div class="text-center py-12">
            <i class="fas fa-history text-gray-400 text-6xl mb-4"></i>
            <h3 class="text-lg font-medium text-gray-900 mb-2">No activities found</h3>
            <p class="text-gray-600">No admin activities match your current filters.</p>
        </div>
    {% endif %}
</div>



<script>
// Auto-refresh functionality
let autoRefreshInterval;

function refreshActivities() {
    const refreshBtn = document.querySelector('button[onclick="refreshActivities()"]');
    const icon = refreshBtn.querySelector('i');
    
    // Show loading state
    icon.classList.add('fa-spin');
    refreshBtn.disabled = true;
    
    // Reload the page
    setTimeout(() => {
        window.location.reload();
    }, 500);
}

function exportActivities() {
    // Get current filter parameters
    const urlParams = new URLSearchParams(window.location.search);
    const exportUrl = '{% url "custom_admin:activities" %}?' + urlParams.toString() + '&export=1';
    
    // Create download link
    const link = document.createElement('a');
    link.href = exportUrl;
    link.download = 'admin_activities_' + new Date().toISOString().split('T')[0] + '.csv';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

function startAutoRefresh() {
    // Auto-refresh every 30 seconds
    autoRefreshInterval = setInterval(() => {
        const refreshBtn = document.querySelector('button[onclick="refreshActivities()"]');
        if (refreshBtn && !refreshBtn.disabled) {
            refreshActivities();
        }
    }, 30000);
}

function stopAutoRefresh() {
    if (autoRefreshInterval) {
        clearInterval(autoRefreshInterval);
    }
}

// Start auto-refresh when page loads
document.addEventListener('DOMContentLoaded', function() {
    startAutoRefresh();
    
    // Stop auto-refresh when user is interacting
    document.addEventListener('click', stopAutoRefresh);
    document.addEventListener('keydown', stopAutoRefresh);
    
    // Add real-time timestamp updates
    updateTimestamps();
    setInterval(updateTimestamps, 60000); // Update every minute
});

function updateTimestamps() {
    const timestampElements = document.querySelectorAll('.timestamp');
    timestampElements.forEach(element => {
        const timestamp = element.dataset.timestamp;
        if (timestamp) {
            const date = new Date(timestamp);
            const now = new Date();
            const diff = now - date;
            
            let timeAgo;
            if (diff < 60000) { // Less than 1 minute
                timeAgo = 'Just now';
            } else if (diff < 3600000) { // Less than 1 hour
                timeAgo = Math.floor(diff / 60000) + ' minutes ago';
            } else if (diff < 86400000) { // Less than 1 day
                timeAgo = Math.floor(diff / 3600000) + ' hours ago';
            } else {
                timeAgo = Math.floor(diff / 86400000) + ' days ago';
            }
            
            element.textContent = timeAgo;
        }
    });
}

// Add keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Ctrl+R to refresh
    if (e.ctrlKey && e.key === 'r') {
        e.preventDefault();
        refreshActivities();
    }
    
    // Ctrl+E to export
    if (e.ctrlKey && e.key === 'e') {
        e.preventDefault();
        exportActivities();
    }
});
</script>
{% endblock %}
