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

{% block content %}
<div class="container mt-5">
    <h1>Customers</h1>

    <!-- Search and Filter Form -->
    <form method="get" class="mb-4">
        <div class="row">
            <div class="col-md-4">
                <input type="text" name="q" class="form-control" placeholder="Search by name, email, or ID..." value="{{ query }}" aria-label="Search Customers">
            </div>
            <div class="col-md-2">
                <select name="status" class="form-control" aria-label="Filter by Status">
                    <option value="">All Statuses</option>
                    {% for value, display in statuses %}
                        <option value="{{ value }}" {% if value == selected_status %}selected{% endif %}>{{ display }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-2">
                <select name="owner" class="form-control" aria-label="Filter by Owner">
                    <option value="">All Owners</option>
                    {% for owner in owners %}
                        <option value="{{ owner.id }}" {% if owner.id|stringformat:"s" == selected_owner %}selected{% endif %}>{{ owner.email }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-2">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="show_deleted" id="show_deleted" {% if show_deleted %}checked{% endif %} aria-label="Show Deleted Customers">
                    <label class="form-check-label" for="show_deleted">
                        Show Deleted
                    </label>
                </div>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary" aria-label="Apply Filters">Filter</button>
            </div>
        </div>
    </form>

    <div class="row mb-4">
        <div class="col-md-12">
            <form method="get" class="mb-2">
                <div class="row">
                    <div class="col-md-3">
                        <select name="activity_user" class="form-control" aria-label="Filter by User">
                            <option value="">All Users</option>
                            {% for user in activity_users %}
                                <option value="{{ user.id }}" {% if user.id|stringformat:"s" == selected_activity_user %}selected{% endif %}>{{ user.email }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="col-md-3">
                        <select name="activity_action" class="form-control" aria-label="Filter by Action">
                            <option value="">All Actions</option>
                            {% for action in activity_actions %}
                                <option value="{{ action }}" {% if action == selected_activity_action %}selected{% endif %}>{{ action }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="col-md-4">
                        <input type="text" name="activity_date_range" class="form-control" placeholder="Select date range..." value="{{ selected_activity_date_range }}" aria-label="Filter by Date Range">
                    </div>
                    <div class="col-md-auto">
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setDateRange('today')" aria-label="Set Date Range to Today">Today</button>
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setDateRange('7days')" aria-label="Set Date Range to Last 7 Days">Last 7 Days</button>
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setDateRange('30days')" aria-label="Set Date Range to Last 30 Days">Last 30 Days</button>
                    </div>
                    <div class="col-md-2">
                        <select name="activity_sort" class="form-control" aria-label="Sort Activity Feed">
                            <option value="-timestamp" {% if selected_activity_sort == "-timestamp" %}selected{% endif %}>Newest First</option>
                            <option value="timestamp" {% if selected_activity_sort == "timestamp" %}selected{% endif %}>Oldest First</option>
                            <option value="actor" {% if selected_activity_sort == "actor" %}selected{% endif %}>User (A-Z)</option>
                            <option value="-actor" {% if selected_activity_sort == "-actor" %}selected{% endif %}>User (Z-A)</option>
                            <option value="action" {% if selected_activity_sort == "action" %}selected{% endif %}>Action (A-Z)</option>
                            <option value="-action" {% if selected_activity_sort == "-action" %}selected{% endif %}>Action (Z-A)</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-secondary" aria-label="Apply Activity Feed Filters">Filter Activity</button>
                    </div>
                    <div class="col-md-2">
                        <a href="?clear_filters=true" class="btn btn-outline-secondary" aria-label="Clear All Filters">Clear Filters</a>
                    </div>
                </div>
            </form>
            <div class="text-muted mb-2">
                Showing {{ activity_logs.start_index }} - {{ activity_logs.end_index }} of {{ activity_log_count }} activities — Page {{ activity_logs.number }} of {{ activity_paginator.num_pages }}
            </div>
            <div>
                <form method="get" class="form-inline">
                    <input type="hidden" name="q" value="{{ query }}">
                    <input type="hidden" name="status" value="{{ selected_status }}">
                    <input type="hidden" name="owner" value="{{ selected_owner }}">
                    <input type="hidden" name="show_deleted" value="{{ show_deleted }}">
                    <input type="hidden" name="activity_user" value="{{ selected_activity_user }}">
                    <input type="hidden" name="activity_action" value="{{ selected_activity_action }}">
                    <input type="hidden" name="activity_date_range" value="{{ selected_activity_date_range }}">
                    <input type="hidden" name="activity_sort" value="{{ selected_activity_sort }}">
                    <label for="activity_page_size" class="mr-2">Show:</label>
                    <select name="activity_page_size" id="activity_page_size" class="form-control form-control-sm" onchange="this.form.submit()">
                        <option value="5" {% if activity_page_size == 5 %}selected{% endif %}>5</option>
                        <option value="10" {% if activity_page_size == 10 %}selected{% endif %}>10</option>
                        <option value="25" {% if activity_page_size == 25 %}selected{% endif %}>25</option>
                        <option value="50" {% if activity_page_size == 50 %}selected{% endif %}>50</option>
                    </select>
                </form>
            </div>

            <div class="my-3">
                <strong>Recent Activity:</strong>
                <span class="badge bg-info">{{ recent_activity_count }} actions in the last 24 hours.</span>
            </div>

            <div class="my-3">
                <strong>Activity Summary:</strong>
                {% for action, count in activity_summary.items %}
                    <span class="badge bg-secondary">{{ action }}: {{ count }}</span>
                {% empty %}
                    <span class="text-muted">No activity in current view.</span>
                {% endfor %}
            </div>

            {% include 'core/_activity_feed.html' %}

            <!-- Activity Feed Pagination -->
            <nav aria-label="Activity Feed Pagination">
                <ul class="pagination justify-content-center">
                    {% if activity_logs.has_previous %}
                        <li class="page-item"><a class="page-link" href="?{% query_string request activity_page=1 %}" aria-label="First Page of Activity Feed">
                            <span aria-hidden="true">&laquo;&laquo;</span>
                        </a></li>
                        <li class="page-item"><a class="page-link" href="?{% query_string request activity_page=activity_logs.previous_page_number %}" aria-label="Previous Page of Activity Feed">
                            <span aria-hidden="true">&laquo;</span>
                        </a></li>
                    {% else %}
                        <li class="page-item disabled"><a class="page-link" href="#" aria-label="First Page of Activity Feed">
                            <span aria-hidden="true">&laquo;&laquo;</span>
                        </a></li>
                        <li class="page-item disabled"><a class="page-link" href="#" aria-label="Previous Page of Activity Feed">
                            <span aria-hidden="true">&laquo;</span>
                        </a></li>
                    {% endif %}

                    <li class="page-item active"><a class="page-link bg-primary text-white" href="#">{{ activity_logs.number }}</a></li>

                    {% if activity_logs.has_next %}
                        <li class="page-item"><a class="page-link" href="?{% query_string request activity_page=activity_logs.next_page_number %}" aria-label="Next Page of Activity Feed">
                            <span aria-hidden="true">&raquo;</span>
                        </a></li>
                        <li class="page-item"><a class="page-link" href="?{% query_string request activity_page=activity_paginator.num_pages %}" aria-label="Last Page of Activity Feed">
                            <span aria-hidden="true">&raquo;&raquo;</span>
                        </a></li>
                    {% else %}
                        <li class="page-item disabled"><a class="page-link" href="#" aria-label="Next Page of Activity Feed">
                            <span aria-hidden="true">&raquo;</span>
                        </a></li>
                        <li class="page-item disabled"><a class="page-link" href="#" aria-label="Last Page of Activity Feed">
                            <span aria-hidden="true">&raquo;&raquo;</span>
                        </a></li>
                    {% endif %}
                </ul>
            </nav>
            <div class="text-center">
                <span class="text-muted">Page {{ activity_logs.number }} of {{ activity_paginator.num_pages }}</span>
                <div class="d-inline-block ms-3">
                    <form method="get" class="form-inline">
                        <input type="hidden" name="q" value="{{ query }}">
                        <input type="hidden" name="status" value="{{ selected_status }}">
                        <input type="hidden" name="owner" value="{{ selected_owner }}">
                        <input type="hidden" name="show_deleted" value="{{ show_deleted }}">
                        <input type="hidden" name="activity_user" value="{{ selected_activity_user }}">
                        <input type="hidden" name="activity_action" value="{{ selected_activity_action }}">
                        <input type="hidden" name="activity_date_range" value="{{ selected_activity_date_range }}">
                        <input type="number" name="activity_page" min="1" max="{{ activity_paginator.num_pages }}" placeholder="Page" class="form-control form-control-sm d-inline-block" style="width: 80px;">
                        <button type="submit" class="btn btn-sm btn-primary">Go</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Page size selector -->
    <div class="d-flex justify-content-between mb-3">
        <div>
            <span class="text-muted">Showing {{ page_obj.start_index }} - {{ page_obj.end_index }} of {{ customer_count }} customers — Page {{ page_obj.number }} of {{ paginator.num_pages }}</span>
        </div>
        <div>
            <form method="get" class="form-inline">
                <input type="hidden" name="q" value="{{ query }}">
                <input type="hidden" name="status" value="{{ selected_status }}">
                <input type="hidden" name="owner" value="{{ selected_owner }}">
                <input type="hidden" name="show_deleted" value="{{ show_deleted }}">
                <label for="page_size" class="mr-2">Show:</label>
                <select name="page_size" id="page_size" class="form-control form-control-sm" onchange="this.form.submit()">
                    <option value="10" {% if page_size == 10 %}selected{% endif %}>10</option>
                    <option value="25" {% if page_size == 25 %}selected{% endif %}>25</option>
                    <option value="50" {% if page_size == 50 %}selected{% endif %}>50</option>
                    <option value="100" {% if page_size == 100 %}selected{% endif %}>100</option>
                </select>
            </form>
        </div>
    </div>

        <form method="post" action="{% url 'customer_bulk_action' %}">
        {% csrf_token %}
        <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th><input type="checkbox" id="select-all"></th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>Status</th>
                    <th>Owner</th>
                    <th>Last Contact</th>
                    <th>Opportunities</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                {% for customer in page_obj %}
                <tr data-customer-id="{{ customer.pk }}" class="{% if customer.pk in highlighted_customer_ids %}highlight-animation{% endif %}{% if is_filter_active and not customer.pk in highlighted_customer_ids %}highlight{% endif %}">
                    <td><input type="checkbox" name="selected_customers" value="{{ customer.pk }}"></td>
                    <td>{{ customer.name }}</td>
                    <td>{{ customer.email }}</td>
                    <td>{{ customer.phone }}</td>
                    <td>{{ customer.get_status_display }}</td>
                    <td>{{ customer.owner.email|default:"-" }}</td>
                    <td>{{ customer.last_contact|date:"Y-m-d"|default:"-" }}</td>
                    <td>{{ customer.opportunity_count }}</td>
                    <td>
                        <a href="{% url 'customer_detail' customer.pk %}" class="btn btn-sm btn-info mr-1">View</a>
                        <a href="{% url 'customer_edit' customer.pk %}" class="btn btn-sm btn-warning mr-1">Edit</a>
                        <a href="{% url 'customer_delete' customer.pk %}" class="btn btn-sm btn-danger">Delete</a>
                    </td>
                </tr>
                {% empty %}
                <tr>
                    <td colspan="9">No customers found.</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        </div>
        <button type="submit" name="action" value="restore" class="btn btn-success">Restore Selected</button>
        <button type="submit" name="action" value="delete" class="btn btn-danger">Delete Selected</button>
    </form>

    <!-- Pagination -->
    <nav aria-label="Customer Page navigation">
        <ul class="pagination justify-content-center">
            {% if page_obj.has_previous %}
                <li class="page-item"><a class="page-link" href="?{% query_string request page=1 %}" aria-label="First">
                    <span aria-hidden="true">&laquo;&laquo;</span>
                </a></li>
                <li class="page-item"><a class="page-link" href="?{% query_string request page=page_obj.previous_page_number %}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a></li>
            {% else %}
                <li class="page-item disabled"><a class="page-link" href="#" aria-label="First">
                    <span aria-hidden="true">&laquo;&laquo;</span>
                </a></li>
                <li class="page-item disabled"><a class="page-link" href="#" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a></li>
            {% endif %}

            <li class="page-item active"><a class="page-link bg-primary text-white" href="#">{{ page_obj.number }}</a></li>

            {% if page_obj.has_next %}
                <li class="page-item"><a class="page-link" href="?{% query_string request page=page_obj.next_page_number %}" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a></li>
                <li class="page-item"><a class="page-link" href="?{% query_string request page=paginator.num_pages %}" aria-label="Last">
                    <span aria-hidden="true">&raquo;&raquo;</span>
                </a></li>
            {% else %}
                <li class="page-item disabled"><a class="page-link" href="#" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a></li>
                <li class="page-item disabled"><a class="page-link" href="#" aria-label="Last">
                    <span aria-hidden="true">&raquo;&raquo;</span>
                </a></li>
            {% endif %}
        </ul>
    </nav>
    <div class="text-center">
        <span class="text-muted">Page {{ page_obj.number }} of {{ paginator.num_pages }}</span>
        <div class="d-inline-block ms-3">
            <form method="get" class="form-inline">
                <input type="hidden" name="q" value="{{ query }}">
                <input type="hidden" name="status" value="{{ selected_status }}">
                <input type="hidden" name="owner" value="{{ selected_owner }}">
                <input type="hidden" name="show_deleted" value="{{ show_deleted }}">
                <input type="number" name="page" min="1" max="{{ paginator.num_pages }}" placeholder="Page" class="form-control form-control-sm d-inline-block" style="width: 80px;">
                <button type="submit" class="btn btn-sm btn-primary">Go</button>
            </form>
        </div>
    </div>
</div>

<style>
    @keyframes fadeOutHighlight {
        from {
            background-color: #d4edda; /* Light green */
        }
        to {
            background-color: transparent;
        }
    }

    .highlight-animation {
        animation: fadeOutHighlight 3s ease-in-out;
    }

    .highlight {
        background-color: #f8f9fa; /* A light grey for filtered results */
    }
</style>

<script>
document.getElementById('select-all').onclick = function() {
    var checkboxes = document.getElementsByName('selected_customers');
    for (var checkbox of checkboxes) {
        checkbox.checked = this.checked;
    }
}

<div id="undo-container" class="alert alert-warning d-none">
    <span id="undo-message"></span>
    <a href="#" id="undo-link">Undo</a>
    <span id="undo-countdown"></span>
</div>

<script>
function startUndoCountdown(timeout, undoUrl) {
    const undoContainer = document.getElementById('undo-container');
    const undoMessage = document.getElementById('undo-message');
    const undoLink = document.getElementById('undo-link');
    const undoCountdown = document.getElementById('undo-countdown');

    undoMessage.textContent = 'Action successful.';
    undoLink.href = undoUrl;
    undoContainer.classList.remove('d-none');

    let timeLeft = timeout;
    undoCountdown.textContent = ` (Undo available for ${timeLeft} seconds)`;

    const timer = setInterval(() => {
        timeLeft--;
        undoCountdown.textContent = ` (Undo available for ${timeLeft} seconds)`;
        if (timeLeft <= 0) {
            clearInterval(timer);
            undoContainer.classList.add('d-none');
        }
    }, 1000);

    setTimeout(() => {
        clearInterval(timer);
        undoContainer.classList.add('d-none');
    }, timeout * 1000);
}

{% if messages %}
    {% for message in messages %}
        try {
            const data = JSON.parse('{{ message|escapejs }}');
            if (data.undo_url) {
                startUndoCountdown({{ undo_timeout }}, data.undo_url);
            } else {
                Swal.fire({
                    toast: true,
                    position: '{{ toast_position|default:"top-end" }}',
                    icon: data.icon || 'success',
                    title: data.message,
                    showConfirmButton: false,
                    timer: 3000,
                    timerProgressBar: true
                });
            }
        } catch (e) {
            // Not a JSON message, treat as plain text
            Swal.fire({
                toast: true,
                position: '{{ toast_position|default:"top-end" }}',
                icon: 'success',
                title: '{{ message|safe }}',
                showConfirmButton: false,
                timer: 3000,
                timerProgressBar: true
            });
        }
    {% endfor %}
{% endif %}
</script>
<script>
    flatpickr("input[name='activity_date_range']", {
        mode: "range",
        dateFormat: "Y-m-d",
        defaultDate: "{{ selected_activity_date_range }}"
    });

    function setDateRange(range) {
        const dateRangeInput = document.querySelector("input[name='activity_date_range']");
        const today = new Date();
        let startDate = new Date();
        const endDate = new Date().toISOString().slice(0, 10);

        if (range === 'today') {
            startDate.setDate(today.getDate());
        } else if (range === '7days') {
            startDate.setDate(today.getDate() - 7);
        } else if (range === '30days') {
            startDate.setDate(today.getDate() - 30);
        }
        
        const startDateStr = startDate.toISOString().slice(0, 10);
        
        const fp = flatpickr(dateRangeInput, {
            mode: "range",
            dateFormat: "Y-m-d",
        });
        fp.setDate([startDateStr, endDate]);
    }

    document.addEventListener('keydown', function(event) {
        if (event.key === 'ArrowLeft') {
            const prevLink = document.querySelector('a[aria-label="Previous Page of Activity Feed"]');
            if (prevLink) {
                prevLink.click();
            }
        } else if (event.key === 'ArrowRight') {
            const nextLink = document.querySelector('a[aria-label="Next Page of Activity Feed"]');
            if (nextLink) {
                nextLink.click();
            }
        }
    });

    document.addEventListener('keydown', function(event) {
        if (event.key === 'ArrowLeft') {
            const prevLink = document.querySelector('a[aria-label="Previous"]');
            if (prevLink) {
                prevLink.click();
            }
        } else if (event.key === 'ArrowRight') {
            const nextLink = document.querySelector('a[aria-label="Next"]');
            if (nextLink) {
                nextLink.click();
            }
        }
    });
</script>
<script>
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl)
    })
</script>
{% endblock %}
