{% if errors %}
<div class="alert alert-error mb-4">
    <ul>
        {% for obj_pk, error_list in errors %}
        {% for error in error_list %}
        <li>
            {% if obj_pk %}
            <strong>Object {{ obj_pk }}:</strong>
            {% endif %}
            {{ error }}
        </li>
        {% endfor %}
        {% endfor %}
    </ul>
</div>
{% endif %}

{# show the normal form #}
{% partial full_form %}

{% partialdef full_form %}
<div class="p-4">
    <h2 class="text-xl font-bold mb-4">Bulk Edit {{ selected_count }} {{ model_name_plural }}</h2>

    <form id="bulk-edit-form" method="post" hx-post="{{ request.path }}" hx-target="#powercrudModalContent"
        data-powercrud-form="bulk">
        {% csrf_token %}
        <input type="hidden" name="bulk_submit" value="1">

        <!-- Hidden field for selected IDs -->
        {% for id in selected_ids %}
        <input type="hidden" name="selected_ids[]" value="{{ id }}">
        {% endfor %}

        <!-- Main form content -->
        <div id="main-form-content">
            {% if bulk_fields %}
            <div class="mb-4">
                <p class="text-sm text-base-content/70 mb-2">
                    Select which fields to update and provide new values.
                    Only checked fields will be modified.
                </p>
            </div>

            <div class="space-y-4">
                {% for field_name, info in field_info.items %}
                <div class="form-control">
                    <label class="cursor-pointer label justify-start gap-4">
                        <input type="checkbox" name="fields_to_update" value="{{ field_name }}"
                            class="checkbox checkbox-primary field-toggle" onchange="toggleFieldInput(this)">
                        <span class="label-text font-medium">{{ info.verbose_name|title }}</span>
                    </label>

                    <div class="mt-2 pl-10 field-input-container" style="display: none;">
                        {% if info.type == 'BooleanField' %}
                        <!-- Boolean field -->
                        <select name="{{ field_name }}" class="select select-bordered w-full" disabled>
                            <option value="">-- No change --</option>
                            <option value="true">Yes</option>
                            <option value="false">No</option>
                        </select>

                        {% elif info.type == 'DateField' %}
                        <!-- Date field -->
                        <input type="date" name="{{ field_name }}" class="input input-bordered w-full" disabled>

                        {% elif info.type == 'DateTimeField' %}
                        <!-- DateTime field -->
                        <input type="datetime-local" name="{{ field_name }}" class="input input-bordered w-full"
                            disabled>

                        {% elif info.is_relation %}
                            {% if info.type == 'ForeignKey' or info.type == 'OneToOneField' %}
                            <select name="{{ field_name }}" class="select select-bordered w-full"
                                {% if info.searchable_select %}data-powercrud-searchable-select="true"{% endif %}
                                disabled>
                                <option value="">-- No change --</option>
                                {% if info.null %}
                                <option value="null">-- None --</option>
                                {% endif %}
                                {% for choice in info.bulk_choices %}
                                <option value="{{ choice.pk }}">{{ choice }}</option>
                                {% endfor %}
                            </select>
                            {% elif info.is_m2m %}
                                <select name="{{ field_name }}" class="select select-bordered w-full min-h-[150px] h-auto"
                                    multiple disabled>
                                    {% for choice in info.bulk_choices %}
                                    <option value="{{ choice.pk }}">{{ choice }}</option>
                                    {% endfor %}
                                </select>
                                <div class="text-xs mt-1">
                                    <label class="flex items-center">
                                        <input type="radio" name="{{ field_name }}_action" value="add"
                                            class="radio radio-xs mr-1" disabled>
                                        <span>Add selected</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="radio" name="{{ field_name }}_action" value="remove"
                                            class="radio radio-xs mr-1" disabled>
                                        <span>Remove selected</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="radio" name="{{ field_name }}_action" value="replace"
                                            class="radio radio-xs mr-1" disabled>
                                        <span>Replace with selected</span>
                                    </label>
                                </div>
                            {% endif %}
                        {% elif info.choices %}
                        <!-- Field with choices -->
                        <select name="{{ field_name }}" class="select select-bordered w-full"
                            {% if info.searchable_select %}data-powercrud-searchable-select="true"{% endif %}
                            disabled>
                            <option value="">-- No change --</option>
                            {% for value, label in info.choices %}
                            <option value="{{ value }}">{{ label }}</option>
                            {% endfor %}
                        </select>

                        {% elif info.type == 'IntegerField' or info.type == 'FloatField' or info.type == 'DecimalField'
                        %}
                        <!-- Numeric field -->
                        <input type="number" name="{{ field_name }}" class="input input-bordered w-full"
                            step="{% if info.type == 'IntegerField' %}1{% else %}any{% endif %}" disabled>

                        {% else %}
                        <!-- Default to text input -->
                        <input type="text" name="{{ field_name }}" class="input input-bordered w-full" disabled>
                        {% endif %}
                    </div>
                </div>
                {% endfor %}
            </div>

            <!-- Submit button for changes -->
            <div class="flex justify-end mt-6 pt-4">
                <button type="submit" class="btn btn-primary mx-auto"
                    data-form-save>
                    Apply Changes
                </button>
            </div>
            {% endif %}

            <!-- Delete section -->
            {% if enable_bulk_delete %}
                <div class="form-control mt-6 border-t pt-4 text-center">
                    <button type="button" class="btn btn-error mx-auto" onclick="showDeleteConfirmation()">
                        Delete All Selected Items
                    </button>
                    <p class="text-sm text-error/70 mt-2 text-center">
                        This will permanently delete all selected items.
                    </p>
                </div>
            {% endif %}
        </div>

        <!-- Delete confirmation section (initially hidden) -->
        <div id="delete-confirmation" class="hidden">
            <div class="p-4 border-t mt-2">
                <h3 class="text-lg font-bold text-error">Confirm Deletion</h3>
                <p class="my-4">
                    Are you sure you want to delete {{ selected_count }} selected {{ model_name_plural }}?
                    This action cannot be undone.
                </p>

                <div class="form-control">
                    <label class="cursor-pointer label justify-start gap-4">
                        <input type="checkbox" id="confirm-delete-checkbox" class="checkbox checkbox-error"
                            onchange="toggleDeleteButton()">
                        <span class="label-text">I understand this will permanently delete these items</span>
                    </label>
                </div>

                <div class="flex justify-end gap-4 mt-4">
                    <button type="button" class="btn btn-outline" onclick="hideDeleteConfirmation()">
                        Cancel
                    </button>
                    <button type="button" id="confirm-delete-button" class="btn btn-error" hx-post="{{ request.path }}"
                        hx-target="#powercrudModalContent" hx-include="#bulk-edit-form"
                        hx-vals='{"delete_selected": "1", "bulk_submit": "1"}'
                        data-powercrud-bulk-delete-submit disabled>
                        Delete Items
                    </button>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
    // Toggle input fields when checkboxes are clicked
    function toggleFieldInput(checkbox) {
        const container = checkbox.closest('.form-control').querySelector('.field-input-container');
        const inputs = container.querySelectorAll('input, select, textarea');

        if (checkbox.checked) {
            container.style.display = 'block';
            inputs.forEach(input => {
                input.disabled = false;
                if (input.tomselect) {
                    input.tomselect.enable();
                    const hasNoChangeValue = input.value === '';
                    if (hasNoChangeValue) {
                        input.tomselect.clear(true);
                        input.tomselect.setTextboxValue('');
                    }
                    requestAnimationFrame(() => {
                        if (!input.tomselect) {
                            return;
                        }
                        // Do not re-sync when "no change" is selected, because sync()
                        // would reselect the sentinel empty option in single-select mode.
                        if (!hasNoChangeValue) {
                            input.tomselect.sync();
                        }
                        input.tomselect.refreshOptions(true);
                        input.tomselect.positionDropdown();
                    });
                    return;
                }
                if (
                    window.initPowercrudSearchableSelects
                    && input.matches
                    && input.matches('select[data-powercrud-searchable-select="true"]')
                ) {
                    window.initPowercrudSearchableSelects(input);
                    if (input.tomselect) {
                        input.tomselect.enable();
                    }
                }
            });
        } else {
            container.style.display = 'none';
            inputs.forEach(input => {
                input.disabled = true;
                if (input.tomselect) {
                    input.tomselect.disable();
                }
            });
        }
    }

    // Show delete confirmation section
    function showDeleteConfirmation() {
        // Hide the main form content
        document.getElementById('main-form-content').classList.add('hidden');
        // Show the delete confirmation
        document.getElementById('delete-confirmation').classList.remove('hidden');
    }

    // Hide delete confirmation section
    function hideDeleteConfirmation() {
        // Show the main form content
        document.getElementById('main-form-content').classList.remove('hidden');
        // Hide the delete confirmation
        document.getElementById('delete-confirmation').classList.add('hidden');

        // Reset the confirmation checkbox
        document.getElementById('confirm-delete-checkbox').checked = false;
        document.getElementById('confirm-delete-button').disabled = true;
    }

    // Toggle delete button based on checkbox
    function toggleDeleteButton() {
        const checkbox = document.getElementById('confirm-delete-checkbox');
        const button = document.getElementById('confirm-delete-button');
        button.disabled = !checkbox.checked;
    }

</script>
{% endpartialdef full_form %}


{# partial to display in modal on successful async queuing #}
{% partialdef async_queue_success %}
<div class="p-4 text-center">
    <h2 id="async-status-heading" class="text-xl font-bold mb-4">Bulk Operation Queued</h2>
    <p class="text-lg mb-4">{{ message }}</p>
    <p class="text-sm text-base-content/70 mb-4">
        Your bulk operation is being processed in the background.
    </p>

    <!-- Progress Polling -->
    <div id="progress-container">
        <div id="progress-display"
             hx-get="{% url 'powercrud:async_progress' %}"
             hx-vals='{"task_name": "{{ task_name }}"}'
             hx-trigger="every 1s"
             hx-target="#progress-display"
             hx-swap="innerHTML"
             class="mb-4 p-4 bg-base-200 rounded-box">
            <div class="loading loading-spinner loading-lg mx-auto"></div>
            <p class="mt-2">Starting...</p>
        </div>
    </div>

    <button type="button" class="btn btn-outline" onclick="powercrudBaseModal.close()">
        Close
    </button>
</div>

<script>
document.body.addEventListener('htmx:afterSwap', function(evt) {
    if (evt.detail.target.id === 'progress-display') {
        try {
            const data = JSON.parse(evt.detail.xhr.responseText);
            const status = (data.status || '').toLowerCase();
            const triggerEl = evt.detail.elt;
            const heading = document.getElementById('async-status-heading');

            if (status === 'success' || status === 'completed') {
                if (heading) {
                    heading.textContent = 'Bulk Operation Completed';
                }
                evt.detail.target.innerHTML = `
                    <div class="alert alert-success">
                        <p>${data.progress || 'Completed successfully!'}</p>
                    </div>
                `;
                // Stop polling
                triggerEl.removeAttribute('hx-trigger');
                htmx.trigger(document.body, 'bulkEditSuccess', { taskName: data.task_name });
                htmx.trigger(document.body, 'refreshTable', { taskName: data.task_name });
            } else if (status === 'failed') {
                if (heading) {
                    heading.textContent = 'Bulk Operation Failed';
                }
                evt.detail.target.innerHTML = `
                    <div class="alert alert-error">
                        <p>${data.progress || 'Failed!'}</p>
                    </div>
                `;
                // Stop polling
                triggerEl.removeAttribute('hx-trigger');
            } else if (status === 'pending') {
                if (heading) {
                    heading.textContent = 'Bulk Operation Starting';
                }
                evt.detail.target.innerHTML = `
                    <div class="loading loading-spinner loading-lg mx-auto"></div>
                    <p class="mt-2">${data.progress || 'Preparing asynchronous job...'}</p>
                `;
            } else if (status === 'in_progress') {
                evt.detail.target.innerHTML = `
                    <div class="progress progress-primary w-full mb-2">
                        <div class="progress-bar" role="progressbar"></div>
                    </div>
                    <p>${data.progress || 'In progress...'}</p>
                `;
                // Adaptive polling if provided
                if (data.poll_interval && data.poll_interval !== 1000) {
                    triggerEl.setAttribute('hx-trigger', `every ${data.poll_interval}ms`);
                }
            }
        } catch (e) {
            console.error('Error parsing progress:', e);
            evt.detail.target.innerHTML = '<p class="text-error">Error loading progress.</p>';
        }
    }
});
</script>
{% endpartialdef async_queue_success %}
