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

{% block title %}Batch Notification Management{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-900">Batch Notification Management</h1>
        <button id="createBatchBtn" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors">
            <span>+</span>Create Batch
        </button>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-lg shadow-md p-4 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Status</label>
                <select id="statusFilter" class="block w-full border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                    <option value="">All Statuses</option>
                    <option value="pending" {% if selected_status == 'pending' %}selected{% endif %}>Pending</option>
                    <option value="processing" {% if selected_status == 'processing' %}selected{% endif %}>Processing</option>
                    <option value="completed" {% if selected_status == 'completed' %}selected{% endif %}>Completed</option>
                    <option value="failed" {% if selected_status == 'failed' %}selected{% endif %}>Failed</option>
                    <option value="cancelled" {% if selected_status == 'cancelled' %}selected{% endif %}>Cancelled</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Date Range</label>
                <select id="dateFilter" class="block w-full border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                    <option value="">All Time</option>
                    <option value="today">Today</option>
                    <option value="week">This Week</option>
                    <option value="month">This Month</option>
                </select>
            </div>
            <div class="flex items-end">
                <button id="applyFilters" class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg transition-colors">
                    <span>🔍</span>Apply Filters
                </button>
            </div>
        </div>
    </div>

    <!-- Batch List -->
    <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200">
            <h2 class="text-lg font-semibold text-gray-900">Notification Batches</h2>
        </div>
        
        <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">Batch</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Type</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Recipients</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Progress</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Created</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {% for batch in batches %}
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div>
                                <div class="text-sm font-medium text-gray-900">{{ batch.name }}</div>
                                <div class="text-sm text-gray-500">{{ batch.template.name }}</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 bg-blue-100 text-blue-800">
                                {{ batch.notification_type|title|replace:"_":" " }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                            {{ batch.total_recipients }}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="flex-1 bg-gray-200 rounded-full h-2 mr-2">
                                    {% if batch.total_recipients > 0 %}
                                    <div class="bg-green-600 h-2 rounded-full" 
                                         style="width: {{ batch.sent_count|mul:100|div:batch.total_recipients }}%"></div>
                                    {% endif %}
                                </div>
                                <span class="text-xs text-gray-600">
                                    {{ batch.sent_count }}/{{ batch.total_recipients }}
                                </span>
                            </div>
                            {% if batch.failed_count > 0 %}
                            <div class="text-xs text-red-600 mt-1">{{ batch.failed_count }} failed</div>
                            {% endif %}
                        </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 batch.status == 'completed' %}bg-green-100 text-green-800
                                {% elif batch.status == 'processing' %}bg-yellow-100 text-yellow-800
                                {% elif batch.status == 'failed' %}bg-red-100 text-red-800
                                {% elif batch.status == 'cancelled' %}bg-gray-100 text-gray-800
                                {% else %}bg-blue-100 text-blue-800{% endif %}">
                                {{ batch.get_status_display }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ batch.created_at|date:"M d, Y H:i" }}
                            <div class="text-xs text-gray-400">by {{ batch.created_by.get_full_name }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <div class="flex space-x-2">
                                {% if batch.status == 'pending' %}
                                <button class="text-green-600 hover:text-green-900 start-batch-btn" data-batch-id="{{ batch.id }}">
                                    <span>▶</span>
                                </button>
                                <button class="text-red-600 hover:text-red-900 cancel-batch-btn" data-batch-id="{{ batch.id }}">
                                    <span>✕</span>
                                </button>
                                {% elif batch.status == 'processing' %}
                                <button class="text-red-600 hover:text-red-900 cancel-batch-btn" data-batch-id="{{ batch.id }}">
                                    <span>⏹</span>
                                </button>
                                {% endif %}
                                <button class="text-blue-600 hover:text-blue-900 view-batch-btn" data-batch-id="{{ batch.id }}">
                                    <i class="fas fa-eye"></i>
                                </button>
                                {% if batch.error_log %}
                                <button class="text-yellow-600 hover:text-yellow-900 view-errors-btn" data-batch-id="{{ batch.id }}">
                                    <span>⚠️</span>
                                </button>
                                {% endif %}
                            </div>
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="7" class="px-6 py-4 text-center text-gray-500">
                            No notification batches found.
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        {% if batches.has_other_pages %}
        <div class="px-6 py-3 border-t border-gray-200">
            <div class="flex items-center justify-between">
                <div class="text-sm text-gray-700">
                    Showing {{ batches.start_index }} to {{ batches.end_index }} of {{ batches.paginator.count }} batches
                </div>
                <div class="flex space-x-1">
                    {% if batches.has_previous %}
                    <a href="?page={{ batches.previous_page_number }}" class="px-3 py-1 border border-gray-300 rounded-md text-sm text-gray-700 hover:bg-gray-50">Previous</a>
                    {% endif %}
                    {% if batches.has_next %}
                    <a href="?page={{ batches.next_page_number }}" class="px-3 py-1 border border-gray-300 rounded-md text-sm text-gray-700 hover:bg-gray-50">Next</a>
                    {% endif %}
                </div>
            </div>
        </div>
        {% endif %}
    </div>
</div>

<!-- Create Batch Modal -->
<div id="batchModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-screen overflow-y-auto">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900">Create Notification Batch</h3>
            </div>
            
            <form id="batchForm" class="px-6 py-4 space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Batch Name</label>
                        <input type="text" id="batchName" name="name" required
                               class="block w-full border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Notification Type</label>
                        <select id="batchNotificationType" name="notification_type" required
                                class="block w-full border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                            {% for type in notification_types %}
                            <option value="{{ type }}">{{ type|title|replace:"_":" " }}</option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Template</label>
                    <select id="batchTemplate" name="template_id" required
                            class="block w-full border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                        <option value="">Select a template</option>
                        {% for template in templates %}
                        <option value="{{ template.id }}" data-type="{{ template.notification_type }}">
                            {{ template.name }} ({{ template.get_channel_display }})
                        </option>
                        {% endfor %}
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Target Recipients</label>
                    <div class="space-y-3">
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">Roles</label>
                            <div class="grid grid-cols-2 md:grid-cols-3 gap-2">
                                {% for value, label in role_choices %}
                                <label class="flex items-center">
                                    <input type="checkbox" name="target_roles" value="{{ value }}"
                                           class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                                    <span class="ml-2 text-sm text-gray-700">{{ label }}</span>
                                </label>
                                {% endfor %}
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">Additional Filters</label>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-xs text-gray-500 mb-1">Min Last Login (days ago)</label>
                                    <input type="number" name="min_last_login_days" min="0"
                                           class="block w-full text-sm border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                                </div>
                                <div>
                                    <label class="block text-xs text-gray-500 mb-1">Max Recipients</label>
                                    <input type="number" name="max_recipients" min="1"
                                           class="block w-full text-sm border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Scheduling</label>
                    <div class="flex items-center space-x-4">
                        <label class="flex items-center">
                            <input type="radio" name="schedule_type" value="immediate" checked
                                   class="text-blue-600 focus:ring-blue-500">
                            <span class="ml-2 text-sm text-gray-700">Send Immediately</span>
                        </label>
                        <label class="flex items-center">
                            <input type="radio" name="schedule_type" value="scheduled"
                                   class="text-blue-600 focus:ring-blue-500">
                            <span class="ml-2 text-sm text-gray-700">Schedule for Later</span>
                        </label>
                    </div>
                    <div id="scheduleDateTime" class="mt-2 hidden">
                        <input type="datetime-local" name="scheduled_at"
                               class="block w-full border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                    </div>
                </div>
                
                <div id="recipientPreview" class="bg-gray-50 rounded-lg p-4 hidden">
                    <h4 class="text-sm font-medium text-gray-900 mb-2">Recipient Preview</h4>
                    <div id="recipientCount" class="text-sm text-gray-600"></div>
                </div>
            </form>
            
            <div class="px-6 py-4 border-t border-gray-200 flex justify-between">
                <button id="previewRecipientsBtn" class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50">
                    Preview Recipients
                </button>
                <div class="flex space-x-3">
                    <button id="cancelBatchBtn" class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50">
                        Cancel
                    </button>
                    <button id="saveBatchBtn" class="px-4 py-2 bg-blue-600 border border-transparent rounded-md text-sm font-medium text-white hover:bg-blue-700">
                        Create Batch
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Batch Details Modal -->
<div id="batchDetailsModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-screen overflow-y-auto">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900">Batch Details</h3>
            </div>
            
            <div id="batchDetailsContent" class="px-6 py-4">
                <!-- Content will be loaded dynamically -->
            </div>
            
            <div class="px-6 py-4 border-t border-gray-200 flex justify-end">
                <button id="closeBatchDetailsBtn" class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50">
                    Close
                </button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const createBatchBtn = document.getElementById('createBatchBtn');
    const batchModal = document.getElementById('batchModal');
    const batchForm = document.getElementById('batchForm');
    const cancelBatchBtn = document.getElementById('cancelBatchBtn');
    const saveBatchBtn = document.getElementById('saveBatchBtn');
    const previewRecipientsBtn = document.getElementById('previewRecipientsBtn');
    const applyFiltersBtn = document.getElementById('applyFilters');
    
    // Create batch
    createBatchBtn.addEventListener('click', function() {
        batchForm.reset();
        batchModal.classList.remove('hidden');
    });
    
    // Cancel modal
    cancelBatchBtn.addEventListener('click', function() {
        batchModal.classList.add('hidden');
    });
    
    // Schedule type change
    document.querySelectorAll('input[name="schedule_type"]').forEach(radio => {
        radio.addEventListener('change', function() {
            const scheduleDateTime = document.getElementById('scheduleDateTime');
            if (this.value === 'scheduled') {
                scheduleDateTime.classList.remove('hidden');
            } else {
                scheduleDateTime.classList.add('hidden');
            }
        });
    });
    
    // Notification type change - filter templates
    document.getElementById('batchNotificationType').addEventListener('change', function() {
        const selectedType = this.value;
        const templateSelect = document.getElementById('batchTemplate');
        const options = templateSelect.querySelectorAll('option');
        
        options.forEach(option => {
            if (option.value === '') {
                option.style.display = 'block';
            } else {
                const templateType = option.dataset.type;
                option.style.display = templateType === selectedType ? 'block' : 'none';
            }
        });
        
        templateSelect.value = '';
    });
    
    // Preview recipients
    previewRecipientsBtn.addEventListener('click', function() {
        const formData = new FormData(batchForm);
        const criteria = {
            roles: formData.getAll('target_roles'),
            min_last_login_days: formData.get('min_last_login_days'),
            max_recipients: formData.get('max_recipients')
        };
        
        // In a real implementation, this would make an API call
        // For now, show a placeholder
        const recipientPreview = document.getElementById('recipientPreview');
        const recipientCount = document.getElementById('recipientCount');
        
        recipientCount.textContent = `Estimated recipients: ${Math.floor(Math.random() * 100) + 10}`;
        recipientPreview.classList.remove('hidden');
    });
    
    // Save batch
    saveBatchBtn.addEventListener('click', function() {
        const formData = new FormData(batchForm);
        const data = {
            action: 'create',
            name: formData.get('name'),
            notification_type: formData.get('notification_type'),
            template_id: formData.get('template_id'),
            target_criteria: {
                roles: formData.getAll('target_roles'),
                min_last_login_days: formData.get('min_last_login_days'),
                max_recipients: formData.get('max_recipients')
            },
            scheduled_at: formData.get('schedule_type') === 'scheduled' ? formData.get('scheduled_at') : null
        };
        
        fetch('{% url "utils:notification_batch_management" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                location.reload();
            } else {
                alert('Error creating batch: ' + data.message);
            }
        });
    });
    
    // Batch actions
    document.querySelectorAll('.start-batch-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const batchId = this.dataset.batchId;
            if (confirm('Are you sure you want to start this batch?')) {
                fetch('{% url "utils:notification_batch_management" %}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                    },
                    body: JSON.stringify({
                        action: 'start',
                        batch_id: batchId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        location.reload();
                    } else {
                        alert('Error starting batch: ' + data.message);
                    }
                });
            }
        });
    });
    
    document.querySelectorAll('.cancel-batch-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const batchId = this.dataset.batchId;
            if (confirm('Are you sure you want to cancel this batch?')) {
                fetch('{% url "utils:notification_batch_management" %}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                    },
                    body: JSON.stringify({
                        action: 'cancel',
                        batch_id: batchId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        location.reload();
                    } else {
                        alert('Error cancelling batch: ' + data.message);
                    }
                });
            }
        });
    });
    
    // Apply filters
    applyFiltersBtn.addEventListener('click', function() {
        const status = document.getElementById('statusFilter').value;
        const date = document.getElementById('dateFilter').value;
        
        const params = new URLSearchParams();
        if (status) params.append('status', status);
        if (date) params.append('date', date);
        
        window.location.href = '{% url "utils:notification_batch_management" %}?' + params.toString();
    });
    
    // Close modal on outside click
    batchModal.addEventListener('click', function(e) {
        if (e.target === batchModal) {
            batchModal.classList.add('hidden');
        }
    });
});
</script>
{% endblock %}