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

{% block title %}Notification Rules{% 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">Notification Rules</h1>
        <button id="createRuleBtn" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors">
            <span>+</span>Create Rule
        </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">Notification Type</label>
                <select id="typeFilter" class="block w-full border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                    <option value="">All Types</option>
                    {% for type in notification_types %}
                    <option value="{{ type }}" {% if type == selected_type %}selected{% endif %}>
                        {{ type|title|replace:"_":" " }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Status</label>
                <select id="activeFilter" class="block w-full border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                    <option value="">All Rules</option>
                    <option value="true" {% if selected_active == 'true' %}selected{% endif %}>Active</option>
                    <option value="false" {% if selected_active == 'false' %}selected{% endif %}>Inactive</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>

    <!-- Rules 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 Rules</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">Rule</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">Condition</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Target Roles</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">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {% for rule in rules %}
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div>
                                <div class="text-sm font-medium text-gray-900">{{ rule.name }}</div>
                                <div class="text-sm text-gray-500">Priority: {{ rule.priority }}</div>
                                {% if rule.description %}
                                <div class="text-xs text-gray-400 mt-1">{{ rule.description|truncatechars:50 }}</div>
                                {% endif %}
                            </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">
                                {{ rule.notification_type|title|replace:"_":" " }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">
                                {{ rule.condition_field }} {{ rule.get_operator_display|lower }} {{ rule.condition_value|truncatechars:20 }}
                            </div>
                            <div class="text-xs text-gray-500">{{ rule.get_condition_type_display }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex flex-wrap gap-1">
                                {% for role in rule.target_roles %}
                                <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                    {{ role|title|replace:"_":" " }}
                                </span>
                                {% endfor %}
                            </div>
                            {% if rule.escalation_roles %}
                            <div class="text-xs text-gray-500 mt-1">
                                Escalates to: {{ rule.escalation_roles|join:", " }}
                            </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 rule.is_active %}bg-green-100 text-green-800{% else %}bg-red-100 text-red-800{% endif %}">
                                {% if rule.is_active %}Active{% else %}Inactive{% endif %}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <div class="flex space-x-2">
                                <button class="text-blue-600 hover:text-blue-900 edit-rule-btn" data-rule-id="{{ rule.id }}">
                                    <span>✏️</span>
                                </button>
                                <button class="text-{% if rule.is_active %}red{% else %}green{% endif %}-600 hover:text-{% if rule.is_active %}red{% else %}green{% endif %}-900 toggle-rule-btn" 
                                        data-rule-id="{{ rule.id }}" data-active="{{ rule.is_active }}">
                                    <i class="fas fa-{% if rule.is_active %}pause{% else %}play{% endif %}"></i>
                                </button>
                                <button class="text-red-600 hover:text-red-900 delete-rule-btn" data-rule-id="{{ rule.id }}">
                                    <span>🗑️</span>
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="6" class="px-6 py-4 text-center text-gray-500">
                            No notification rules found.
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        {% if rules.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 {{ rules.start_index }} to {{ rules.end_index }} of {{ rules.paginator.count }} rules
                </div>
                <div class="flex space-x-1">
                    {% if rules.has_previous %}
                    <a href="?page={{ rules.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 rules.has_next %}
                    <a href="?page={{ rules.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/Edit Rule Modal -->
<div id="ruleModal" 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" id="modalTitle">Create Notification Rule</h3>
            </div>
            
            <form id="ruleForm" class="px-6 py-4 space-y-4">
                <input type="hidden" id="ruleId" name="rule_id">
                
                <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">Rule Name</label>
                        <input type="text" id="ruleName" 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">Priority</label>
                        <input type="number" id="rulePriority" name="priority" min="1" value="1"
                               class="block w-full border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Description</label>
                    <textarea id="ruleDescription" name="description" rows="2"
                              class="block w-full border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"></textarea>
                </div>
                
                <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">Notification Type</label>
                        <select id="ruleNotificationType" 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>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Condition Type</label>
                        <select id="ruleConditionType" name="condition_type" required
                                class="block w-full border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                            {% for value, label in condition_types %}
                            <option value="{{ value }}">{{ label }}</option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
                
                <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">Condition Field</label>
                        <input type="text" id="ruleConditionField" name="condition_field" required
                               placeholder="e.g., user.role, loan.amount"
                               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">Operator</label>
                        <select id="ruleOperator" name="operator" required
                                class="block w-full border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                            {% for value, label in operators %}
                            <option value="{{ value }}">{{ label }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Condition Value</label>
                        <input type="text" id="ruleConditionValue" name="condition_value" required
                               placeholder="Value to compare against"
                               class="block w-full border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Target 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 class="border-t pt-4">
                    <h4 class="text-md font-medium text-gray-900 mb-3">Escalation Settings</h4>
                    <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">Escalation Delay (minutes)</label>
                            <input type="number" id="ruleEscalationDelay" name="escalation_delay" min="0" value="0"
                                   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">Escalation Roles</label>
                            <div class="space-y-1">
                                {% for value, label in role_choices %}
                                <label class="flex items-center">
                                    <input type="checkbox" name="escalation_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>
                </div>
            </form>
            
            <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
                <button id="cancelRuleBtn" 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="saveRuleBtn" class="px-4 py-2 bg-blue-600 border border-transparent rounded-md text-sm font-medium text-white hover:bg-blue-700">
                    Save Rule
                </button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const createRuleBtn = document.getElementById('createRuleBtn');
    const ruleModal = document.getElementById('ruleModal');
    const ruleForm = document.getElementById('ruleForm');
    const cancelRuleBtn = document.getElementById('cancelRuleBtn');
    const saveRuleBtn = document.getElementById('saveRuleBtn');
    const applyFiltersBtn = document.getElementById('applyFilters');
    
    let currentRuleId = null;
    
    // Create rule
    createRuleBtn.addEventListener('click', function() {
        currentRuleId = null;
        document.getElementById('modalTitle').textContent = 'Create Notification Rule';
        ruleForm.reset();
        ruleModal.classList.remove('hidden');
    });
    
    // Edit rule
    document.querySelectorAll('.edit-rule-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            currentRuleId = this.dataset.ruleId;
            document.getElementById('modalTitle').textContent = 'Edit Notification Rule';
            // Load rule data (would need to fetch from server)
            ruleModal.classList.remove('hidden');
        });
    });
    
    // Toggle rule
    document.querySelectorAll('.toggle-rule-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const ruleId = this.dataset.ruleId;
            const isActive = this.dataset.active === 'True';
            
            fetch('{% url "utils:notification_rules" %}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                },
                body: JSON.stringify({
                    action: 'toggle',
                    rule_id: ruleId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    location.reload();
                } else {
                    alert('Error toggling rule: ' + data.message);
                }
            });
        });
    });
    
    // Delete rule
    document.querySelectorAll('.delete-rule-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            if (confirm('Are you sure you want to delete this rule?')) {
                const ruleId = this.dataset.ruleId;
                
                fetch('{% url "utils:notification_rules" %}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                    },
                    body: JSON.stringify({
                        action: 'delete',
                        rule_id: ruleId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        location.reload();
                    } else {
                        alert('Error deleting rule: ' + data.message);
                    }
                });
            }
        });
    });
    
    // Cancel modal
    cancelRuleBtn.addEventListener('click', function() {
        ruleModal.classList.add('hidden');
    });
    
    // Save rule
    saveRuleBtn.addEventListener('click', function() {
        const formData = new FormData(ruleForm);
        const data = {
            action: currentRuleId ? 'update' : 'create',
            name: formData.get('name'),
            description: formData.get('description'),
            notification_type: formData.get('notification_type'),
            condition_type: formData.get('condition_type'),
            condition_field: formData.get('condition_field'),
            operator: formData.get('operator'),
            condition_value: formData.get('condition_value'),
            target_roles: formData.getAll('target_roles'),
            escalation_delay: parseInt(formData.get('escalation_delay')) || 0,
            escalation_roles: formData.getAll('escalation_roles'),
            priority: parseInt(formData.get('priority')) || 1
        };
        
        if (currentRuleId) {
            data.rule_id = currentRuleId;
        }
        
        fetch('{% url "utils:notification_rules" %}', {
            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 saving rule: ' + data.message);
            }
        });
    });
    
    // Apply filters
    applyFiltersBtn.addEventListener('click', function() {
        const type = document.getElementById('typeFilter').value;
        const active = document.getElementById('activeFilter').value;
        
        const params = new URLSearchParams();
        if (type) params.append('type', type);
        if (active) params.append('active', active);
        
        window.location.href = '{% url "utils:notification_rules" %}?' + params.toString();
    });
    
    // Close modal on outside click
    ruleModal.addEventListener('click', function(e) {
        if (e.target === ruleModal) {
            ruleModal.classList.add('hidden');
        }
    });
});
</script>
{% endblock %}