{% extends 'atlas/base.html' %}
{% load case_widgets %}
{% load crispy_forms_tags %}

{% block content %}
    <script>
        (function($) {
            if ($ && $.fn && $.fn.select2) {
                var originalSelect2 = $.fn.select2;
                $.fn.select2 = function(options) {
                    if (options && typeof options === 'object') {
                        if (this.closest('#caseSeriesModal').length > 0) {
                            options.dropdownParent = $('#caseSeriesModal');
                        }
                    }
                    return originalSelect2.apply(this, arguments);
                };
            }
        })(window.jQuery);
    </script>
    <h2>Uploaded dicoms</h2>
    User: {{user}}<br/>
    <a href="{% url 'atlas:new_uploads' %}">Upload more dicoms</a><br/>
    {% if not case %}
        <div class="alert alert-info" role="alert">
            Series imported from here will be orphaned (not associated with a case). <br/>It is usually better to <a href="{% url 'atlas:case_create' %}">create a case</a> first and then import directly into the case.
        </div>
    {% endif %}

    Click to select cases to import. If no series are selected all will be selected/imported.<br/>


    {% if series_list %}
        <div id="series-list">
            {% if grouped_patients %}
                {% for patient in grouped_patients %}
                    <div class="patient-block mb-4 p-3 border rounded" style="background: rgba(255,255,255,0.015); border-color: rgba(255,255,255,0.08) !important;">
                        <div class="patient-header d-flex flex-wrap align-items-center justify-content-between pb-2 mb-3 border-bottom border-secondary">
                            <span>
                                <i class="bi bi-person-badge me-2 text-info"></i>
                                <strong>Patient ID:</strong> <span class="badge bg-secondary font-monospace">{{ patient.patient_id }}</span>
                            </span>
                            <div class="btn-group">
                                <button type="button" class="btn btn-sm btn-outline-primary select-all-patient-btn" title="Select all series for this patient">Select Patient Series</button>
                                <button type="button" class="btn btn-sm btn-outline-secondary deselect-all-patient-btn" title="Deselect all series for this patient">Deselect all</button>
                            </div>
                        </div>
                        
                        {% for study_uid, study in patient.studies %}
                            <details class="study-block {% if study.partial_imported_uids %}study-block--partial-import{% endif %}" open>
                                <summary>
                                    <strong>{{ study.description|default:"(no description)" }}</strong>
                                    <small class="text-muted"> ({{ study_uid }}) — {{ study.series|length }} series</small>
                                    <span class="ms-2">
                                        <button type="button" class="btn btn-sm btn-outline-secondary select-all-btn" title="Select all in study">Select all</button>
                                        <button type="button" class="btn btn-sm btn-outline-secondary deselect-all-btn" title="Deselect all in study">Deselect all</button>
                                    </span>
                                </summary>
                                {% if study.partial_imported_uids %}
                                    <div class="alert alert-warning py-2 mt-2 mb-2 d-flex flex-wrap align-items-center justify-content-between gap-2">
                                        <div>
                                            <strong>Partial import detected:</strong>
                                            {{ study.partial_imported_count }} series in this study already exist.
                                            The highlighted rows can finish importing the remaining images.
                                            {% if study.matched_existing_series %}
                                                <div class="small mt-1">
                                                    Existing series in Atlas:
                                                    {% for existing_series in study.matched_existing_series %}
                                                        <a href="{% url 'atlas:series_detail' existing_series.pk %}">{{ existing_series }}</a>{% if not forloop.last %}, {% endif %}
                                                    {% endfor %}
                                                </div>
                                            {% endif %}
                                        </div>
                                        <button
                                            type="button"
                                            class="btn btn-sm btn-warning import-partial-series-btn"
                                            data-series-uids="{{ study.partial_imported_uids|join:',' }}"
                                            {% if study.preferred_case_id %}data-case-id="{{ study.preferred_case_id }}"{% endif %}
                                        >Finish these imports</button>
                                    </div>
                                {% endif %}
                                {% if study.import_suggestions %}
                                    <div class="alert alert-info py-2 mt-2 mb-2">
                                        <strong>Study already imported:</strong>
                                        {% for suggestion in study.import_suggestions %}
                                            <div class="d-flex flex-wrap align-items-center gap-2 mt-1">
                                                <span>
                                                    Case:
                                                    <a href="{% url 'atlas:case_detail' suggestion.case.pk %}">{{ suggestion.case }}</a>
                                                    ({{ suggestion.already_imported_count }} series already imported)
                                                </span>
                                                <button
                                                    type="button"
                                                    class="btn btn-sm btn-outline-primary import-missing-series-btn"
                                                    data-case-id="{{ suggestion.case.pk }}"
                                                    data-series-uids="{{ suggestion.missing_uids|join:',' }}"
                                                >
                                                    Import remaining {{ suggestion.missing_uids|length }} series
                                                </button>
                                            </div>
                                        {% endfor %}
                                    </div>
                                {% endif %}
                                <ul class="study-series-list">
                                    {% for series, n, tags, date in study.series %}
                                        {% if series in study.partial_imported_uids %}
                                            {% if case %}
                                                {% include 'atlas/partials/_series_item.html' with show_tags_link=True series_is_partial=True series_item_classes='series-item--partial-import' import_case_id=case.pk %}
                                            {% else %}
                                                {% include 'atlas/partials/_series_item.html' with show_tags_link=True series_is_partial=True series_item_classes='series-item--partial-import' import_case_id=study.preferred_case_id %}
                                            {% endif %}
                                        {% else %}
                                            {% if case %}
                                                {% include 'atlas/partials/_series_item.html' with show_tags_link=True series_is_partial=False series_item_classes='' import_case_id=case.pk %}
                                            {% else %}
                                                {% include 'atlas/partials/_series_item.html' with show_tags_link=True series_is_partial=False series_item_classes='' %}
                                            {% endif %}
                                        {% endif %}
                                    {% endfor %}
                                </ul>
                            </details>
                        {% endfor %}
                    </div>
                {% endfor %}
            {% elif grouped_series %}
                {% for study_uid, study in grouped_series %}
                    <details class="study-block {% if study.partial_imported_uids %}study-block--partial-import{% endif %}" open>
                        <summary>
                            <strong>{{ study.description|default:"(no description)" }}</strong>
                            <small class="text-muted"> ({{ study_uid }}) — {{ study.series|length }} series</small>
                            <span class="ms-2">
                                <button type="button" class="btn btn-sm btn-outline-secondary select-all-btn" title="Select all in study">Select all</button>
                                <button type="button" class="btn btn-sm btn-outline-secondary deselect-all-btn" title="Deselect all in study">Deselect all</button>
                            </span>
                        </summary>
                        {% if study.partial_imported_uids %}
                            <div class="alert alert-warning py-2 mt-2 mb-2 d-flex flex-wrap align-items-center justify-content-between gap-2">
                                <div>
                                    <strong>Partial import detected:</strong>
                                    {{ study.partial_imported_count }} series in this study already exist.
                                    The highlighted rows can finish importing the remaining images.
                                    {% if study.matched_existing_series %}
                                        <div class="small mt-1">
                                            Existing series in Atlas:
                                            {% for existing_series in study.matched_existing_series %}
                                                <a href="{% url 'atlas:series_detail' existing_series.pk %}">{{ existing_series }}</a>{% if not forloop.last %}, {% endif %}
                                            {% endfor %}
                                        </div>
                                    {% endif %}
                                </div>
                                <button
                                    type="button"
                                    class="btn btn-sm btn-warning import-partial-series-btn"
                                    data-series-uids="{{ study.partial_imported_uids|join:',' }}"
                                    {% if study.preferred_case_id %}data-case-id="{{ study.preferred_case_id }}"{% endif %}
                                >Finish these imports</button>
                            </div>
                        {% endif %}
                        {% if study.import_suggestions %}
                            <div class="alert alert-info py-2 mt-2 mb-2">
                                <strong>Study already imported:</strong>
                                {% for suggestion in study.import_suggestions %}
                                    <div class="d-flex flex-wrap align-items-center gap-2 mt-1">
                                        <span>
                                            Case:
                                            <a href="{% url 'atlas:case_detail' suggestion.case.pk %}">{{ suggestion.case }}</a>
                                            ({{ suggestion.already_imported_count }} series already imported)
                                        </span>
                                        <button
                                            type="button"
                                            class="btn btn-sm btn-outline-primary import-missing-series-btn"
                                            data-case-id="{{ suggestion.case.pk }}"
                                            data-series-uids="{{ suggestion.missing_uids|join:',' }}"
                                        >
                                            Import remaining {{ suggestion.missing_uids|length }} series
                                        </button>
                                    </div>
                                {% endfor %}
                            </div>
                        {% endif %}
                        <ul class="study-series-list">
                            {% for series, n, tags, date in study.series %}
                                {% if series in study.partial_imported_uids %}
                                    {% if case %}
                                        {% include 'atlas/partials/_series_item.html' with show_tags_link=True series_is_partial=True series_item_classes='series-item--partial-import' import_case_id=case.pk %}
                                    {% else %}
                                        {% include 'atlas/partials/_series_item.html' with show_tags_link=True series_is_partial=True series_item_classes='series-item--partial-import' import_case_id=study.preferred_case_id %}
                                    {% endif %}
                                {% else %}
                                    {% if case %}
                                        {% include 'atlas/partials/_series_item.html' with show_tags_link=True series_is_partial=False series_item_classes='' import_case_id=case.pk %}
                                    {% else %}
                                        {% include 'atlas/partials/_series_item.html' with show_tags_link=True series_is_partial=False series_item_classes='' %}
                                    {% endif %}
                                {% endif %}
                            {% endfor %}
                        </ul>
                    </details>
                {% endfor %}
            {% else %}
                <ul>
                    {% for series, n, tags, date in series_list %}
                        {% if case %}
                            {% include 'atlas/partials/_series_item.html' with series_is_partial=False series_item_classes='' import_case_id=case.pk %}
                        {% else %}
                            {% include 'atlas/partials/_series_item.html' with series_is_partial=False series_item_classes='' %}
                        {% endif %}
                    {% endfor %}
                </ul>
            {% endif %}
        </div>

        {% if case %}
            <p>Importing into case: <a href='{% url "atlas:case_detail" case.pk %}'>{{case}}</a></p>
        {% endif %}
        <div class="upload-toolbar sticky-top mb-3">
            <div class="upload-toolbar__inner">
                <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-2">
                    <div>
                        <div id="selection-count" class="small text-muted">Selected: <span id="selected-count">0</span></div>
                        <div class="small text-warning-emphasis">Keep this page open while imports are running.</div>
                    </div>
                    <details class="upload-settings">
                        <summary>Upload settings</summary>
                        <form class="mt-2">
                            <fieldset>
                                <legend>Select how series should be ordered when uploaded</legend>
                                <div class="helptext">
                                    This will affect how series are displayed when viewing with the built in site viewer. By default when exporting from Insight the order is not maintained so you should choose to order either by slice location or instance number.
                                    If you are not sure, leave this as the default.
                                </div>
                                <div>
                                    <input type="radio" id="order-series-slice-location" value="order-series-slice-location" name="order-series" checked>
                                    <label for="order-series-slice-location">Order series by slice location</label>
                                </div>
                                <div>
                                    <input type="radio" id="order-series-instance-number" value="order-series-instance-number" name="order-series">
                                    <label for="order-series-instance-number">Order series by instance number</label>
                                </div>
                                <div>
                                    <input type="radio" id="order-series-none" value="order-series-none" name="order-series">
                                    <label for="order-series-none">None</label>
                                </div>
                            </fieldset>
                        </form>
                    </details>
                </div>

                <div id="import-progress" class="alert alert-warning d-none mb-3" role="alert">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-2">
                        <div>
                            <strong>Import running.</strong>
                            <span class="d-block">Do not leave this page until the progress bar completes.</span>
                        </div>
                        <div id="import-progress-text" class="small text-muted"></div>
                    </div>
                    <div class="progress" style="height: 1rem;">
                        <div id="import-progress-bar"
                             class="progress-bar progress-bar-striped progress-bar-animated bg-warning text-dark"
                             role="progressbar"
                             style="width: 0%"
                             aria-valuenow="0"
                             aria-valuemin="0"
                             aria-valuemax="100">0%</div>
                    </div>
                </div>

                <div id="selection-actions" class="d-flex flex-wrap align-items-center gap-2">
                    <button id="delete-uploads-button"
                            class="btn btn-outline-danger"
                            hx-post="{% url 'api-1:clear_dicoms' %}"
                            hx-include="[name='selection']"
                            hx-confirm="This will clear selected uploads, Continue?"
                            title="Delete selected uploads"
                    >Delete Uploads</button>

                    <button id="import-dicoms-sequential-button"
                            type="button"
                            class="btn btn-primary"
                    >Import {% if case %}into case{% endif %}</button>
                    <button id="import-into-case-button" type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#caseSelectModal">Import into case…</button>
                    <button id="import-case-series-button" type="button" class="btn btn-outline-success" data-bs-toggle="modal" data-bs-target="#caseSeriesModal" disabled>Import as case series…</button>
                </div>

                <div id="import-status" class="mt-3"></div>
            </div>
        </div>

        <div class="indicator"><div class="loader"></div>Loading...</div>

        <div class="imported">

        </div>
    {% else %}
        No uploads awaiting importing have been found.

    {% endif %}

    <p><a href="{% url 'atlas:series_view' %}?case=null&sort=-modified_date">View orphan series</a></p>


<!-- Global modal used for HTMX-loaded fragments (e.g. series tags) -->
    <div class="modal fade" id="seriesTagsModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Series DICOM Tags</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                <!-- HTMX will swap content here -->
                    <div class="text-muted">Loading…</div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Case select modal for importing into an existing case -->
    <div class="modal fade" id="caseSelectModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Import into case</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-2">
                        {% case_search_widget collection=None input_id='case-search-input-modal' target_id='case-search-results-modal' show_select_button=True %}
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="caseSeriesModal" aria-hidden="true" data-bs-focus="false">
        <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Import as linked case series</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="case-series-form">
                    {% csrf_token %}
                    <div class="modal-body">
                        <div class="alert alert-info small">
                            This creates one case per selected study, copies the same case details to each case, and links them with <em>previous case</em>.
                        </div>
                        {% crispy case_series_form %}
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <div id="case-series-submit-loading" class="d-none text-muted small me-2">
                            <span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
                            Creating linked cases...
                        </div>
                        <button id="case-series-submit-button" type="submit" class="btn btn-success">Create linked cases</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        const importCaseId = {% if case %}{{ case.pk }}{% else %}null{% endif %};

        // Update the selected count shown beside action buttons
        function updateSelectionCount() {
            const all = Array.from(document.querySelectorAll('input[name="selection"]'));
            const selected = all.filter(cb => cb.checked && !cb.disabled).length;
            const selectedStudies = new Set(all.filter(cb => cb.checked && !cb.disabled).map(cb => cb.dataset.studyUid).filter(Boolean));
            const el = document.getElementById('selected-count');
            if (el) el.textContent = `${selected} series across ${selectedStudies.size} studies`;
            // disable action buttons if none selected
            const deleteBtn = document.getElementById('delete-uploads-button');
            const importBtn = document.getElementById('import-dicoms-sequential-button');
            const importIntoCaseBtn = document.getElementById('import-into-case-button');
            const importCaseSeriesBtn = document.getElementById('import-case-series-button');
            if (deleteBtn) deleteBtn.disabled = selected === 0;
            if (importBtn) importBtn.disabled = selected === 0;
            if (importIntoCaseBtn) importIntoCaseBtn.disabled = selected === 0;
            if (importCaseSeriesBtn) importCaseSeriesBtn.disabled = selected === 0 || selectedStudies.size < 2;
        }

        function setImportButtonsDisabled(disabled) {
            document.querySelectorAll('#selection-actions button, .import-partial-series-btn, .import-missing-series-btn').forEach((button) => {
                button.disabled = disabled;
            });
        }

        function setImportProgress(completed, total, message) {
            const progress = document.getElementById('import-progress');
            const bar = document.getElementById('import-progress-bar');
            const text = document.getElementById('import-progress-text');
            if (!progress || !bar || !text) return;

            if (total <= 0) {
                progress.classList.add('d-none');
                bar.style.width = '0%';
                bar.setAttribute('aria-valuenow', '0');
                bar.textContent = '0%';
                text.textContent = '';
                return;
            }

            const percentage = Math.min(100, Math.round((completed / total) * 100));
            progress.classList.remove('d-none');
            bar.style.width = `${percentage}%`;
            bar.setAttribute('aria-valuenow', String(percentage));
            bar.textContent = `${percentage}%`;
            text.textContent = message || `${completed} of ${total} series imported`;
        }

        function appendImportStatus(html) {
            const statusDiv = document.getElementById('import-status');
            if (!statusDiv) return;
            const wrapper = document.createElement('div');
            wrapper.className = 'mb-2';
            wrapper.innerHTML = html;
            statusDiv.appendChild(wrapper);
        }

        function getImportUrl(caseId) {
            const targetCaseId = caseId || importCaseId;
            if (targetCaseId) {
                const importTemplate = "{% url 'atlas:uploads_import_case_htmx' 0 %}";
                return importTemplate.replace(/0\/?$/, targetCaseId);
            }
            return "{% url 'atlas:uploads_import_htmx' %}";
        }

        function getSelectedOrAllSeries() {
            const checkboxes = Array.from(document.querySelectorAll('input[name="selection"]:checked'));
            const allCheckboxes = Array.from(document.querySelectorAll('input[name="selection"]'));
            const selectableSeries = allCheckboxes.filter(cb => !cb.disabled).map(cb => cb.value);
            const selectedSeries = checkboxes.filter(cb => !cb.disabled).map(cb => cb.value);
            return selectedSeries.length ? selectedSeries : selectableSeries;
        }

        function getSelectedSeriesUids() {
            return Array.from(document.querySelectorAll('input[name="selection"]:checked'))
                .filter(cb => !cb.disabled)
                .map(cb => cb.value);
        }

        function getSelectedStudyUids() {
            return new Set(
                Array.from(document.querySelectorAll('input[name="selection"]:checked'))
                    .filter(cb => !cb.disabled)
                    .map(cb => cb.dataset.studyUid)
                    .filter(Boolean)
            );
        }

        async function runImport(selectionList, caseId) {
            const statusDiv = document.getElementById('import-status');
            if (!statusDiv) return;
            if (!selectionList.length) {
                alert('Please select at least one series to import.');
                return;
            }

            statusDiv.innerHTML = '';
            const orderSeries = (document.querySelector('input[name="order-series"]:checked') || {}).value || '';

            setImportButtonsDisabled(true);
            setImportProgress(0, 1, `Importing ${selectionList.length} series. Do not leave this page.`);

            try {
                await htmx.ajax('POST', getImportUrl(caseId), {
                    target: '#import-status',
                    swap: 'innerHTML',
                    values: {
                        selection: selectionList,
                        'order-series': orderSeries,
                    },
                });

                selectionList.forEach((seriesId) => {
                    markSeriesImported(seriesId);
                });
                setImportProgress(1, 1, `${selectionList.length} series import request completed.`);
            } catch (error) {
                appendImportStatus(`<div class="alert alert-danger mb-0">Import failed. ${error?.message || ''}</div>`);
            } finally {
                setTimeout(function () {
                    setImportProgress(0, 0);
                }, 1800);
                setImportButtonsDisabled(false);
                updateSelectionCount();
            }
        }

        // Keep count up-to-date on checkbox changes and attribute changes
        document.body.addEventListener('change', function (e) {
            if (e.target && e.target.name === 'selection') updateSelectionCount();
        });

        // Observe attribute changes (disabled) under the series list to update count
        (function () {
            const list = document.getElementById('series-list');
            if (!list) return;
            const mo = new MutationObserver(() => updateSelectionCount());
            mo.observe(list, { attributes: true, subtree: true, attributeFilter: ['disabled'] });
        })();

        // Initialize count on page load
        document.addEventListener('DOMContentLoaded', updateSelectionCount);
        // Show modal when HTMX swaps content into the modal body
        document.body.addEventListener('htmx:afterSwap', function (e) {
            try {
                var target = e.detail && e.detail.target ? e.detail.target : null;
                if (!target) return;
                // If the swapped target is (or is inside) the modal body, show modal
                var modalBody = document.querySelector('#seriesTagsModal .modal-body');
                if (modalBody && (modalBody === target || modalBody.contains(target))) {
                    var modalEl = document.getElementById('seriesTagsModal');
                    if (modalEl && window.bootstrap && bootstrap.Modal) {
                        bootstrap.Modal.getOrCreateInstance(modalEl).show();
                    }
                }
            } catch (err) {
                console.error('Error showing seriesTagsModal after HTMX swap', err);
            }
        });

        function markSeriesImported(seriesId) {
            const li = document.querySelector(`#series-list input[value="${seriesId}"]`)?.closest('li');
            if (!li || li.classList.contains('imported')) return;

            li.classList.add('imported');
            li.classList.remove('series-item--partial-import');
            const partialBadge = li.querySelector('.badge.bg-warning');
            if (partialBadge && partialBadge.textContent.trim() === 'Part imported') {
                partialBadge.remove();
            }
            const partialButton = li.querySelector('.import-partial-series-btn');
            if (partialButton) partialButton.remove();
            if (!li.querySelector('.badge.bg-success')) {
                const badge = document.createElement('span');
                badge.className = 'badge bg-success ms-2';
                badge.textContent = 'Imported';
                li.appendChild(badge);
            }

            const checkbox = li.querySelector('input[name="selection"]');
            if (checkbox) {
                checkbox.disabled = true;
                checkbox.checked = false;
            }

            const _sp = li.querySelector('span');
            if (_sp) _sp.onclick = null;
            li.style.pointerEvents = 'none';
            li.style.opacity = '0.7';
        }

        const importButton = document.getElementById('import-dicoms-sequential-button');
        if (importButton) {
            importButton.addEventListener('click', async function() {
                const toImport = getSelectedOrAllSeries();

                if (!toImport.length) {
                    alert('Please select at least one series to import (not already imported).');
                    return;
                }
                await runImport(toImport, importCaseId);
            });
        }

        const caseSeriesForm = document.getElementById('case-series-form');
        if (caseSeriesForm) {
            caseSeriesForm.addEventListener('submit', async function (event) {
                event.preventDefault();
                const submitBtn = document.getElementById('case-series-submit-button');
                const submitLoading = document.getElementById('case-series-submit-loading');
                const selectedSeries = getSelectedSeriesUids();
                const selectedStudies = getSelectedStudyUids();
                if (!selectedSeries.length || selectedStudies.size < 2) {
                    alert('Select series from at least two studies before creating a linked case series.');
                    return;
                }

                const formData = new FormData(caseSeriesForm);
                formData.delete('previous_case');
                selectedSeries.forEach((seriesUid) => formData.append('selection', seriesUid));
                const orderSeries = (document.querySelector('input[name="order-series"]:checked') || {}).value || '';
                if (orderSeries) {
                    formData.set('order-series', orderSeries);
                }

                setImportButtonsDisabled(true);
                if (submitBtn) {
                    submitBtn.classList.add('d-none');
                    submitBtn.disabled = true;
                }
                if (submitLoading) {
                    submitLoading.classList.remove('d-none');
                }
                try {
                    const response = await fetch("{% url 'atlas:uploads_import_case_series_htmx' %}", {
                        method: 'POST',
                        headers: {
                            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || '',
                            'X-Requested-With': 'XMLHttpRequest',
                        },
                        body: formData,
                    });
                    const html = await response.text();
                    appendImportStatus(html);
                    if (response.ok) {
                        selectedSeries.forEach((seriesUid) => markSeriesImported(seriesUid));
                        const modalEl = document.getElementById('caseSeriesModal');
                        if (modalEl && window.bootstrap && bootstrap.Modal) {
                            bootstrap.Modal.getInstance(modalEl)?.hide();
                        }
                    }
                } catch (error) {
                    appendImportStatus(`<div class="alert alert-danger mb-0">Linked case import failed. ${error?.message || ''}</div>`);
                } finally {
                    if (submitLoading) {
                        submitLoading.classList.add('d-none');
                    }
                    if (submitBtn) {
                        submitBtn.classList.remove('d-none');
                        submitBtn.disabled = false;
                    }
                    setImportButtonsDisabled(false);
                    updateSelectionCount();
                }
            });
        }

        // Select / Deselect all series within a study block or patient block
        document.addEventListener('click', function (e) {
            const target = e.target;
            if (target.matches('.select-all-btn')) {
                const detail = target.closest('.study-block');
                if (!detail) return;
                const inputs = detail.querySelectorAll('input[name="selection"]');
                inputs.forEach(cb => {
                    if (!cb.disabled) {
                        cb.checked = true;
                        const li = cb.closest('.series-item');
                        if (li) li.classList.add('selected');
                        cb.dispatchEvent(new Event('change', { bubbles: true }));
                    }
                });
                if (typeof updateSelectionCount === 'function') updateSelectionCount();
            }
            if (target.matches('.deselect-all-btn')) {
                const detail = target.closest('.study-block');
                if (!detail) return;
                const inputs = detail.querySelectorAll('input[name="selection"]');
                inputs.forEach(cb => {
                    if (!cb.disabled) {
                        cb.checked = false;
                        const li = cb.closest('.series-item');
                        if (li) li.classList.remove('selected');
                        cb.dispatchEvent(new Event('change', { bubbles: true }));
                    }
                });
                if (typeof updateSelectionCount === 'function') updateSelectionCount();
            }
            if (target.matches('.select-all-patient-btn')) {
                const patientBlock = target.closest('.patient-block');
                if (!patientBlock) return;
                const inputs = patientBlock.querySelectorAll('input[name="selection"]');
                inputs.forEach(cb => {
                    if (!cb.disabled) {
                        cb.checked = true;
                        const li = cb.closest('.series-item');
                        if (li) li.classList.add('selected');
                        cb.dispatchEvent(new Event('change', { bubbles: true }));
                    }
                });
                if (typeof updateSelectionCount === 'function') updateSelectionCount();
            }
            if (target.matches('.deselect-all-patient-btn')) {
                const patientBlock = target.closest('.patient-block');
                if (!patientBlock) return;
                const inputs = patientBlock.querySelectorAll('input[name="selection"]');
                inputs.forEach(cb => {
                    if (!cb.disabled) {
                        cb.checked = false;
                        const li = cb.closest('.series-item');
                        if (li) li.classList.remove('selected');
                        cb.dispatchEvent(new Event('change', { bubbles: true }));
                    }
                });
                if (typeof updateSelectionCount === 'function') updateSelectionCount();
            }
        });

        // Listen for `case:selected` events dispatched by the case-search widget and perform the import
        document.body.addEventListener('case:selected', async function (e) {
            try {
                const detail = e.detail || {};
                const casePk = detail.casePk;
                const caseTitle = detail.caseTitle || `#${casePk}`;
                if (!casePk) {
                    console.error('case:selected without casePk');
                    return;
                }

                // Gather selected series
                const checkboxes = Array.from(document.querySelectorAll('input[name="selection"]:checked'));
                const allCheckboxes = Array.from(document.querySelectorAll('input[name="selection"]'));
                const selectable = allCheckboxes.filter(cb => !cb.disabled).map(cb => cb.value);
                const selectionList = checkboxes.length ? checkboxes.map(cb => cb.value) : selectable;
                if (!selectionList.length) {
                    alert('Please select at least one series to import into the case.');
                    return;
                }

                const confirmMsg = `Import ${selectionList.length} series into case "${caseTitle}" (ID ${casePk})?`;
                if (!window.confirm(confirmMsg)) return;

                // Close modal and show result in import-status
                const modalEl = document.getElementById('caseSelectModal');
                if (modalEl && window.bootstrap && bootstrap.Modal) {
                    bootstrap.Modal.getInstance(modalEl)?.hide();
                }
                await runImport(selectionList, casePk);
            } catch (err) {
                console.error('Import handler error', err);
                alert('Import failed — check console for details.');
            }
        });

        document.body.addEventListener('click', async function (e) {
            const trigger = e.target.closest('.import-missing-series-btn');
            if (!trigger) return;

            const casePk = trigger.dataset.caseId;
            const seriesUids = (trigger.dataset.seriesUids || '')
                .split(',')
                .map(v => v.trim())
                .filter(Boolean);

            if (!casePk || !seriesUids.length) {
                alert('No remaining series found for this study.');
                return;
            }

            const confirmMsg = `Import ${seriesUids.length} remaining series into case ${casePk}?`;
            if (!window.confirm(confirmMsg)) return;

            await runImport(seriesUids, casePk);
        });

        document.body.addEventListener('click', async function (e) {
            const trigger = e.target.closest('.import-partial-series-btn');
            if (!trigger) return;

            const seriesUids = (trigger.dataset.seriesUids || '')
                .split(',')
                .map(v => v.trim())
                .filter(Boolean);

            if (!seriesUids.length) {
                alert('No partially imported series were found.');
                return;
            }

            const casePk = trigger.dataset.caseId || importCaseId;
            const confirmMsg = casePk
                ? `Finish importing ${seriesUids.length} series into case ${casePk}?`
                : `Finish importing ${seriesUids.length} series without linking to a case?`;
            if (!window.confirm(confirmMsg)) return;

            await runImport(seriesUids, casePk);
        });

    // Row click toggles selection when clicking any non-interactive part of the series card
        document.body.addEventListener('click', function (e) {
            const item = e.target.closest('.series-item');
            if (!item) return;
        // ignore clicks on links, buttons, inputs or forms inside the item
            if (e.target.closest('a,button,input,form')) return;
            const cb = item.querySelector('input[name="selection"]');
            if (!cb || cb.disabled) return;
            cb.checked = !cb.checked;
            item.classList.toggle('selected', cb.checked);
            cb.dispatchEvent(new Event('change', { bubbles: true }));
        });
    </script>

    <script>
        // Page-level safe HTMX error handler: avoid throwing if global container missing
        document.body.addEventListener('htmx:responseError', function (e) {
            const el = document.getElementById('htmx-error');
            if (!el) {
                console.error('htmx response error (no #htmx-error):', e.detail);
                return;
            }
            let error = e.detail && e.detail.xhr ? e.detail.xhr.response : 'Unknown error';
            el.innerHTML = error;
            el.classList.remove('hidden');
        });
    </script>

{% endblock %}


{% block css %}
    <style>
        /* Dark theme friendly styles for uploads page */
        :root {
            --bg: #0f1115;
            --panel: #111217;
            --muted: #9aa0a6;
            --border: #242629;
            --accent: #7c3aed;
            --success: #16a34a;
            --danger: #dc2626;
            --card: #0f1216;
        }

        body {
            background: var(--bg);
            color: #e6eef6;
        }

        .indicator { display: none; }
        .indicator.htmx-request { display: block; }

        .loader {
            width: 50px;
            aspect-ratio: 1;
            display: grid;
        }
        .loader::before,
        .loader::after {
            content: "";
            grid-area: 1/1;
            --c: no-repeat radial-gradient(farthest-side, var(--accent) 92%, #0000);
            background:
            var(--c) 50% 0,
            var(--c) 50% 100%,
            var(--c) 100% 50%,
            var(--c) 0 50%;
            background-size: 12px 12px;
            animation: l12 1s infinite;
            opacity: 0.95;
        }
        .loader::before { margin: 4px; filter: hue-rotate(45deg); background-size: 8px 8px; }
        @keyframes l12 { 100% { transform: rotate(.5turn) } }

        #series-list { user-select: none; }

        .study-block {
            margin: 8px 0;
            padding: 8px;
            border: 1px solid var(--border);
            border-radius: 8px;
            background: linear-gradient(180deg, rgba(255,255,255,0.02), rgba(255,255,255,0.01));
            box-shadow: 0 1px 0 rgba(255,255,255,0.02) inset;
        }

        .study-block--partial-import {
            border-color: rgba(245, 158, 11, 0.55);
            box-shadow: 0 0 0 1px rgba(245, 158, 11, 0.14) inset;
        }

        .upload-toolbar {
            top: 0.75rem;
            z-index: 1030;
        }

        .upload-toolbar__inner {
            padding: 0.75rem;
            border: 1px solid var(--border);
            border-radius: 12px;
            background: rgba(15, 17, 21, 0.94);
            backdrop-filter: blur(10px);
            box-shadow: 0 18px 40px rgba(0, 0, 0, 0.22);
        }

        .upload-settings summary {
            cursor: pointer;
            font-weight: 700;
        }

        .upload-settings fieldset {
            margin: 0;
        }

        .upload-settings legend {
            font-size: 0.95rem;
            margin-bottom: 0.35rem;
        }

        .study-block summary { font-size: 1rem; cursor: pointer; padding: 4px 6px; color: #e6eef6; }

        .study-series-list { list-style: none; margin: 8px 0 0 0; padding: 0; }

        .study-series-list li {
            padding: 10px;
            border-bottom: 1px solid rgba(255,255,255,0.03);
            background: transparent;
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            gap: 12px;
        }

        .study-series-list li:last-child { border-bottom: 0; }

        .series-meta { font-weight: 600; color: #f1f5f9; }
        .series-tags { font-size: 0.9rem; color: var(--muted); margin-top: 4px; }

        .series-block-popup-link a { color: var(--muted); text-decoration: underline; }

        /* Grid layout for series items: responsive flex-wrap cards */
        .study-series-list { display: flex; flex-wrap: wrap; gap: 12px; padding: 0; }
        .study-series-list ul { margin: 0; padding: 0; }
        .study-series-list li { list-style: none; }

        .series-item {
            box-sizing: border-box;
            width: calc(33.333% - 8px);
            display: flex;
            flex-direction: column;
            gap: 8px;
            padding: 12px;
            border: 1px solid var(--border);
            border-radius: 8px;
            background: linear-gradient(180deg, rgba(255,255,255,0.01), rgba(255,255,255,0.00));
            transition: box-shadow 120ms ease, transform 120ms ease;
            position: relative;
        }

        .series-item--partial-import {
            border-color: rgba(245, 158, 11, 0.7);
            background: linear-gradient(180deg, rgba(245, 158, 11, 0.10), rgba(255, 255, 255, 0.00));
        }

        .series-item:hover { box-shadow: 0 6px 18px rgba(0,0,0,0.4); transform: translateY(-2px); }

        .series-left { display: block; }
        .series-right { align-self: flex-end; text-align: right; }
        .series-title { margin: 0 0 6px 0; font-size: 1rem; font-weight: 700; }
        .series-meta div { line-height: 1.2; color: var(--muted); }

        /* Responsive breakpoints */
        @media (max-width: 991px) {
            .series-item { width: calc(50% - 8px); }
        }
        @media (max-width: 575px) {
            .series-item { width: 100%; }
            .series-right { text-align: left; }
        }

        /* Modality badge styling (top-right of card) */
        .modality-badge {
            position: absolute;
            top: 10px;
            right: 12px;
            display: inline-block;
            background: rgba(255,255,255,0.06);
            color: #e6eef6;
            padding: 0.25rem 0.5rem;
            border-radius: 0.375rem;
            font-size: 0.75rem;
            font-weight: 700;
            border: 1px solid rgba(255,255,255,0.03);
            backdrop-filter: blur(2px);
        }

        /* Selected state */
        #series-list .selected {
            color: #fff;
            background: linear-gradient(90deg, rgba(124,58,237,0.12), rgba(124,58,237,0.08));
            border: 1px solid rgba(124,58,237,0.25);
            border-radius: 6px;
            padding: 6px;
        }

        /* Imported badge */
        .badge.bg-success { background-color: var(--success); color: #000; }

        /* Placeholder for tags */
        .series-tags-placeholder { color: var(--muted); padding: 6px 0; }

        /* Buttons */
        button { background: transparent; color: #e6eef6; border: 1px solid var(--border); }
        button.btn-primary { background: var(--accent); border-color: var(--accent); color: #fff; }

        /* small helpers */
        .text-muted { color: var(--muted) !important; }

        #caseSeriesModal .modal-body {
            max-height: min(72vh, 760px);
            overflow-y: auto;
        }

        #caseSeriesModal select[multiple] {
            min-height: 14rem;
            background: #ffffff;
            color: #111827;
            border: 1px solid #ced4da;
        }

        #caseSeriesModal select[multiple] option {
            background: #ffffff;
            color: #111827;
        }

        #caseSeriesModal select[multiple] option:checked {
            background: #0d6efd;
            color: #ffffff;
        }

        .select2-container {
            width: 100% !important;
        }

        #series-list li {
        }
        #series-list .selected {
            color: white;
            border: 1px solid #52057b;
            user-select: none;
            margin: -1px;

        }
        .series-block-popup-link {
            float: right;
        }
        #series-list li.imported {
            border-color: #e6ffe6;
            opacity: 0.7;
        }
        /* Wider modal for long dicom tags and wrapping behaviour */
        #seriesTagsModal .modal-dialog {
            max-width: 95%;
            width: 95%;
        }

        /* Make tag table layout fixed so long values wrap neatly */
        #seriesTagsModal .series-tags-fragment table {
            table-layout: fixed;
            width: 100%;
        }

        #seriesTagsModal .series-tags-fragment th,
        #seriesTagsModal .series-tags-fragment td {
            white-space: normal !important;
            word-break: break-word;
            overflow-wrap: anywhere;
        }
    </style>

{% endblock css %}
