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

{% block title %}Customer Requests Management{% endblock %}

{% block extra_css %}
<style>
    .request-card {
        border-left: 4px solid #dee2e6;
        transition: all 0.3s;
    }
    
    .request-card:hover {
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        transform: translateY(-2px);
    }
    
    .request-card.priority-urgent { border-left-color: #dc3545; }
    .request-card.priority-high { border-left-color: #fd7e14; }
    .request-card.priority-medium { border-left-color: #ffc107; }
    .request-card.priority-low { border-left-color: #28a745; }
    
    .status-badge {
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 0.8rem;
        font-weight: 500;
    }
    
    .status-pending { background-color: #fff3cd; color: #856404; }
    .status-in_progress { background-color: #d1ecf1; color: #0c5460; }
    .status-resolved { background-color: #d4edda; color: #155724; }
    .status-closed { background-color: #e2e3e5; color: #383d41; }
    .status-escalated { background-color: #f8d7da; color: #721c24; }
    .status-cancelled { background-color: #f5f5f5; color: #6c757d; }
    
    .priority-badge {
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 500;
    }
    
    .priority-urgent { background-color: #dc3545; color: white; }
    .priority-high { background-color: #fd7e14; color: white; }
    .priority-medium { background-color: #ffc107; color: #212529; }
    .priority-low { background-color: #28a745; color: white; }
    
    .filters-card {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
    }
    
    .request-meta {
        font-size: 0.85rem;
        color: #6c757d;
    }
    
    .request-actions {
        display: flex;
        gap: 5px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- Page Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="h3 mb-0">Customer Requests Management</h1>
                    <p class="text-muted">Track and manage customer service requests</p>
                </div>
                <div>
                    <a href="{% url 'reports:create_customer_request' %}" class="btn btn-primary">
                        <span>+</span> Create Request
                    </a>
                    <a href="{% url 'reports:customer_requests_analytics' %}" class="btn btn-outline-info ml-2">
                        <span>📈</span> Analytics
                    </a>
                    <a href="{% url 'reports:customer_requests_report' %}" class="btn btn-outline-secondary ml-2">
                        <span>📊</span> View Report
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Search and Filters -->
    <div class="filters-card">
        <!-- Search Bar -->
        <div class="row mb-3">
            <div class="col-md-8">
                <div class="input-group">
                    <input type="text" class="form-control" id="searchInput" 
                           placeholder="Search by request number, subject, customer name, email, or phone...">
                    <div class="input-group-append">
                        <button class="btn btn-outline-secondary" type="button" onclick="performSearch()">
                            <span>🔍</span>
                        </button>
                    </div>
                </div>
                <div id="searchResults" class="mt-2" style="display: none;"></div>
            </div>
            <div class="col-md-4 text-right">
                <button class="btn btn-outline-primary" onclick="toggleBulkMode()">
                    <i class="fas fa-check-square"></i> Bulk Actions
                </button>
            </div>
        </div>
        
        <!-- Bulk Actions Bar (hidden by default) -->
        <div id="bulkActionsBar" class="row mb-3" style="display: none;">
            <div class="col-12">
                <div class="alert alert-info">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <span id="selectedCount">0</span> requests selected
                        </div>
                        <div>
                            <select id="bulkAction" class="form-control d-inline-block mr-2" style="width: auto;">
                                <option value="">Select Action</option>
                                <option value="update_status">Update Status</option>
                                <option value="assign">Assign to Staff</option>
                                <option value="update_priority">Update Priority</option>
                            </select>
                            <select id="bulkValue" class="form-control d-inline-block mr-2" style="width: auto; display: none;">
                            </select>
                            <button class="btn btn-primary btn-sm" onclick="executeBulkAction()">
                                <span>▶</span> Execute
                            </button>
                            <button class="btn btn-secondary btn-sm ml-1" onclick="cancelBulkMode()">
                                <span>✕</span> Cancel
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Filters -->
        <form method="get" class="row align-items-end">
            <div class="col-md-2">
                <label for="status" class="form-label">Status</label>
                <select class="form-control" id="status" name="status">
                    <option value="">All Statuses</option>
                    {% for value, label in status_choices %}
                    <option value="{{ value }}" {% if filters.status == value %}selected{% endif %}>
                        {{ label }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-2">
                <label for="request_type" class="form-label">Type</label>
                <select class="form-control" id="request_type" name="request_type">
                    <option value="">All Types</option>
                    {% for value, label in type_choices %}
                    <option value="{{ value }}" {% if filters.request_type == value %}selected{% endif %}>
                        {{ label }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-2">
                <label for="priority" class="form-label">Priority</label>
                <select class="form-control" id="priority" name="priority">
                    <option value="">All Priorities</option>
                    {% for value, label in priority_choices %}
                    <option value="{{ value }}" {% if filters.priority == value %}selected{% endif %}>
                        {{ label }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-2">
                <label for="assigned_to" class="form-label">Assigned To</label>
                <select class="form-control" id="assigned_to" name="assigned_to">
                    <option value="">All Staff</option>
                    {% for staff in staff_members %}
                    <option value="{{ staff.id }}" {% if filters.assigned_to == staff.id|stringformat:"s" %}selected{% endif %}>
                        {{ staff.get_full_name }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-4">
                <button type="submit" class="btn btn-primary">
                    <span>🔍</span> Apply Filters
                </button>
                <a href="{% url 'reports:customer_requests_list' %}" class="btn btn-outline-secondary ml-2">
                    <span>✕</span> Clear
                </a>
            </div>
        </form>
    </div>

    <!-- Requests List -->
    <div class="row">
        {% for request in page_obj %}
        <div class="col-12 mb-3">
            <div class="card request-card priority-{{ request.priority }}">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <div class="d-flex align-items-start">
                                <div class="mr-3" id="bulkCheckboxContainer" style="display: none;">
                                    <input type="checkbox" class="bulk-checkbox" value="{{ request.pk }}" 
                                           onchange="updateBulkSelection()">
                                </div>
                                <div class="flex-grow-1">
                                    <h6 class="mb-1">
                                        <a href="{% url 'reports:customer_request_detail' request.pk %}" class="text-decoration-none">
                                            {{ request.subject }}
                                        </a>
                                        <span class="priority-badge priority-{{ request.priority }} ml-2">
                                            {{ request.get_priority_display }}
                                        </span>
                                    </h6>
                                    <div class="request-meta mb-2">
                                        <span class="mr-3">
                                            <i class="fas fa-ticket-alt"></i> {{ request.request_number }}
                                        </span>
                                        <span class="mr-3">
                                            <span>👤</span> {{ request.customer.get_full_name }}
                                        </span>
                                        <span class="mr-3">
                                            <span>🏷️</span> {{ request.get_request_type_display }}
                                        </span>
                                        <span class="mr-3">
                                            <span>⏰</span> {{ request.created_at|timesince }} ago
                                        </span>
                                        {% if request.assigned_to %}
                                        <span class="mr-3">
                                            <span>👔</span> {{ request.assigned_to.get_full_name }}
                                        </span>
                                        {% endif %}
                                    </div>
                                    <p class="mb-0 text-muted">
                                        {{ request.description|truncatewords:20 }}
                                    </p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2 text-center">
                            <span class="status-badge status-{{ request.status }}">
                                {{ request.get_status_display }}
                            </span>
                            {% if request.status == 'resolved' and request.resolved_at %}
                            <div class="mt-1">
                                <small class="text-success">
                                    <span>✓</span> {{ request.resolved_at|timesince }} ago
                                </small>
                            </div>
                            {% endif %}
                        </div>
                        <div class="col-md-2 text-right">
                            <div class="request-actions">
                                <a href="{% url 'reports:customer_request_detail' request.pk %}" 
                                   class="btn btn-sm btn-outline-primary" title="View Details">
                                    <i class="fas fa-eye"></i>
                                </a>
                                {% if request.status != 'resolved' and request.status != 'closed' %}
                                <button class="btn btn-sm btn-outline-success" 
                                        onclick="quickResolve('{{ request.pk }}')" title="Quick Resolve">
                                    <span>✓</span>
                                </button>
                                {% endif %}
                                {% if not request.assigned_to %}
                                <button class="btn btn-sm btn-outline-info" 
                                        onclick="assignToMe('{{ request.pk }}')" title="Assign to Me">
                                    <i class="fas fa-hand-paper"></i>
                                </button>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        {% empty %}
        <div class="col-12">
            <div class="card">
                <div class="card-body text-center py-5">
                    <span>📥</span>
                    <h5 class="mt-3">No requests found</h5>
                    <p class="text-muted">No customer requests match your current filters.</p>
                    <a href="{% url 'reports:create_customer_request' %}" class="btn btn-primary">
                        <span>+</span> Create First Request
                    </a>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>

    <!-- Pagination -->
    {% if page_obj.has_other_pages %}
    <div class="row mt-4">
        <div class="col-12">
            <nav aria-label="Requests pagination">
                <ul class="pagination justify-content-center">
                    {% if page_obj.has_previous %}
                    <li class="page-item">
                        <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ page_obj.previous_page_number }}">
                            <span>‹</span> Previous
                        </a>
                    </li>
                    {% endif %}
                    
                    {% for num in page_obj.paginator.page_range %}
                    {% if page_obj.number == num %}
                    <li class="page-item active">
                        <span class="page-link">{{ num }}</span>
                    </li>
                    {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                    <li class="page-item">
                        <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ num }}">{{ num }}</a>
                    </li>
                    {% endif %}
                    {% endfor %}
                    
                    {% if page_obj.has_next %}
                    <li class="page-item">
                        <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ page_obj.next_page_number }}">
                            Next <span>›</span>
                        </a>
                    </li>
                    {% endif %}
                </ul>
            </nav>
        </div>
    </div>
    {% endif %}

    <!-- Summary Stats -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <div class="row text-center">
                        <div class="col-md-3">
                            <h5 class="text-warning">{{ page_obj.paginator.count }}</h5>
                            <small class="text-muted">Total Requests</small>
                        </div>
                        <div class="col-md-3">
                            <h5 class="text-info">
                                {% with pending_count=page_obj.object_list|length %}
                                {{ pending_count }}
                                {% endwith %}
                            </h5>
                            <small class="text-muted">In Current View</small>
                        </div>
                        <div class="col-md-3">
                            <h5 class="text-success">-</h5>
                            <small class="text-muted">Avg Resolution Time</small>
                        </div>
                        <div class="col-md-3">
                            <h5 class="text-primary">-</h5>
                            <small class="text-muted">Resolution Rate</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Quick Action Modals -->
<div class="modal fade" id="quickResolveModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Quick Resolve Request</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form id="quickResolveForm" method="post">
                {% csrf_token %}
                <div class="modal-body">
                    <input type="hidden" name="action" value="update_status">
                    <input type="hidden" name="status" value="resolved">
                    <div class="form-group">
                        <label for="resolution_notes">Resolution Notes</label>
                        <textarea class="form-control" id="resolution_notes" name="notes" rows="3" 
                                  placeholder="Briefly describe how this request was resolved..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success">
                        <span>✓</span> Mark as Resolved
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let bulkModeActive = false;
let selectedRequests = new Set();

function quickResolve(requestId) {
    $('#quickResolveForm').attr('action', '/reports/customer-requests/' + requestId + '/');
    $('#quickResolveModal').modal('show');
}

function assignToMe(requestId) {
    if (confirm('Assign this request to yourself?')) {
        $.post('/reports/customer-requests/' + requestId + '/', {
            'action': 'assign',
            'assigned_to': '{{ request.user.id }}',
            'csrfmiddlewaretoken': $('[name=csrfmiddlewaretoken]').val()
        }, function(data) {
            location.reload();
        }).fail(function() {
            alert('Failed to assign request. Please try again.');
        });
    }
}

function performSearch() {
    const query = document.getElementById('searchInput').value.trim();
    const resultsDiv = document.getElementById('searchResults');
    
    if (query.length < 2) {
        resultsDiv.style.display = 'none';
        return;
    }
    
    fetch(`{% url 'reports:customer_requests_search' %}?q=${encodeURIComponent(query)}`)
        .then(response => response.json())
        .then(data => {
            if (data.results.length > 0) {
                let html = '<div class="list-group">';
                data.results.forEach(result => {
                    html += `
                        <a href="${result.url}" class="list-group-item list-group-item-action">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1">${result.subject}</h6>
                                    <p class="mb-1 text-muted">${result.request_number} - ${result.customer_name}</p>
                                    <small class="text-muted">${result.request_type_display} | ${result.status_display}</small>
                                </div>
                                <span class="badge badge-${result.priority === 'urgent' ? 'danger' : result.priority === 'high' ? 'warning' : 'secondary'}">
                                    ${result.priority_display}
                                </span>
                            </div>
                        </a>
                    `;
                });
                html += '</div>';
                resultsDiv.innerHTML = html;
                resultsDiv.style.display = 'block';
            } else {
                resultsDiv.innerHTML = '<div class="alert alert-info">No requests found matching your search.</div>';
                resultsDiv.style.display = 'block';
            }
        })
        .catch(error => {
            console.error('Search failed:', error);
            resultsDiv.innerHTML = '<div class="alert alert-danger">Search failed. Please try again.</div>';
            resultsDiv.style.display = 'block';
        });
}

function toggleBulkMode() {
    bulkModeActive = !bulkModeActive;
    const checkboxContainers = document.querySelectorAll('#bulkCheckboxContainer');
    const bulkActionsBar = document.getElementById('bulkActionsBar');
    
    if (bulkModeActive) {
        checkboxContainers.forEach(container => container.style.display = 'block');
        bulkActionsBar.style.display = 'block';
    } else {
        checkboxContainers.forEach(container => container.style.display = 'none');
        bulkActionsBar.style.display = 'none';
        selectedRequests.clear();
        updateBulkSelection();
    }
}

function cancelBulkMode() {
    bulkModeActive = false;
    const checkboxContainers = document.querySelectorAll('#bulkCheckboxContainer');
    const bulkActionsBar = document.getElementById('bulkActionsBar');
    const checkboxes = document.querySelectorAll('.bulk-checkbox');
    
    checkboxContainers.forEach(container => container.style.display = 'none');
    bulkActionsBar.style.display = 'none';
    checkboxes.forEach(checkbox => checkbox.checked = false);
    selectedRequests.clear();
    updateBulkSelection();
}

function updateBulkSelection() {
    const checkboxes = document.querySelectorAll('.bulk-checkbox:checked');
    selectedRequests.clear();
    
    checkboxes.forEach(checkbox => {
        selectedRequests.add(checkbox.value);
    });
    
    document.getElementById('selectedCount').textContent = selectedRequests.size;
    
    // Update bulk value options based on selected action
    const actionSelect = document.getElementById('bulkAction');
    const valueSelect = document.getElementById('bulkValue');
    
    if (actionSelect.value) {
        updateBulkValueOptions(actionSelect.value);
    }
}

function updateBulkValueOptions(action) {
    const valueSelect = document.getElementById('bulkValue');
    valueSelect.innerHTML = '';
    valueSelect.style.display = 'none';
    
    if (action === 'update_status') {
        valueSelect.style.display = 'inline-block';
        {% for value, label in status_choices %}
        valueSelect.innerHTML += '<option value="{{ value }}">{{ label }}</option>';
        {% endfor %}
    } else if (action === 'assign') {
        valueSelect.style.display = 'inline-block';
        valueSelect.innerHTML += '<option value="">Select Staff Member</option>';
        {% for staff in staff_members %}
        valueSelect.innerHTML += '<option value="{{ staff.id }}">{{ staff.get_full_name }}</option>';
        {% endfor %}
    } else if (action === 'update_priority') {
        valueSelect.style.display = 'inline-block';
        {% for value, label in priority_choices %}
        valueSelect.innerHTML += '<option value="{{ value }}">{{ label }}</option>';
        {% endfor %}
    }
}

function executeBulkAction() {
    const action = document.getElementById('bulkAction').value;
    const value = document.getElementById('bulkValue').value;
    
    if (!action || selectedRequests.size === 0) {
        alert('Please select an action and at least one request.');
        return;
    }
    
    if ((action === 'assign' || action === 'update_status' || action === 'update_priority') && !value) {
        alert('Please select a value for the chosen action.');
        return;
    }
    
    const formData = new FormData();
    formData.append('action', action);
    formData.append('csrfmiddlewaretoken', $('[name=csrfmiddlewaretoken]').val());
    
    if (action === 'assign') {
        formData.append('assigned_to', value);
    } else if (action === 'update_status') {
        formData.append('status', value);
    } else if (action === 'update_priority') {
        formData.append('priority', value);
    }
    
    selectedRequests.forEach(requestId => {
        formData.append('request_ids', requestId);
    });
    
    fetch('{% url "reports:bulk_update_requests" %}', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            location.reload();
        } else {
            alert('Error: ' + (data.error || 'Unknown error occurred'));
        }
    })
    .catch(error => {
        console.error('Bulk action failed:', error);
        alert('Bulk action failed. Please try again.');
    });
}

// Event listeners
document.getElementById('searchInput').addEventListener('keyup', function(e) {
    if (e.key === 'Enter') {
        performSearch();
    } else if (this.value.length >= 2) {
        // Debounced search
        clearTimeout(this.searchTimeout);
        this.searchTimeout = setTimeout(performSearch, 500);
    } else if (this.value.length === 0) {
        document.getElementById('searchResults').style.display = 'none';
    }
});

document.getElementById('bulkAction').addEventListener('change', function() {
    updateBulkValueOptions(this.value);
});

// Hide search results when clicking outside
document.addEventListener('click', function(e) {
    const searchInput = document.getElementById('searchInput');
    const searchResults = document.getElementById('searchResults');
    
    if (!searchInput.contains(e.target) && !searchResults.contains(e.target)) {
        searchResults.style.display = 'none';
    }
});

$(document).ready(function() {
    // Auto-refresh every 2 minutes
    setInterval(function() {
        if (!bulkModeActive) {
            location.reload();
        }
    }, 120000);
    
    // Initialize tooltips
    $('[title]').tooltip();
});
</script>
{% endblock %}