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

{% block content %}
    <div class="mb-2"><small class="text-muted">Collection: <strong>{{collection}}</strong></small></div>

    <div class="d-flex justify-content-between align-items-start mb-3">
        <div>
            <h2 class="h4 mb-0">Case {{case_number|add:1}}

                {% if show_title %}
                    : {{case.title}}
                {% endif %}


                {% if question_completed %}
                    <span class="badge bg-warning text-dark ms-2 small">REVIEW</span>
                {% endif %}

            </h2>
        </div>

        <div class="d-flex align-items-center ms-3">
            <div class="dropdown">
                <a class="btn btn-outline-secondary btn-sm dropdown-toggle" href="#" role="button" id="caseJump" data-bs-toggle="dropdown" aria-expanded="false"
                   hx-get="{% url 'atlas:collection_case_jump_partial' pk=collection.pk %}?current={{case_number}}{% if cid %}&cid={{cid}}&passcode={{passcode}}{% endif %}"
                   hx-target="#case-jump-menu"
                   hx-swap="innerHTML"
                   hx-trigger="click">
                    Jump
                </a>
                <div class="dropdown-menu dropdown-menu-end" id="case-jump-menu">
                    <div class="px-3 py-2 text-muted">Loading...</div>
                </div>
            </div>
        </div>
    </div>

    {% if not question_completed and collection.question_time_limit is not None %}
        <div id="question-timer-block" class="mb-3" title="This question has a time limit of {{ collection.question_time_limit }} seconds. The timer will start when the page loads.">
            <div class="d-flex align-items-center gap-3">
                <div><strong>Time remaining:</strong> <span id="question-timer" aria-live="polite">&nbsp;</span></div>
                <div style="flex:1; max-width:320px;">
                    <div class="progress" style="height:10px;">
                        <div id="question-timer-progress-inner" class="progress-bar" role="progressbar" style="width:100%; background:var(--timer-color, #28a745);"></div>
                    </div>
                </div>
            </div>
            <div id="timer-htmx-target" style="display:none;"></div>
            <div id="autosubmit-toast-container" style="position:fixed; top:16px; right:16px; z-index:10500;"></div>
        </div>
    {% endif %}

{% comment %}     <details>
        <summary class="opacity-50">Help <i class="bi bi-info-circle"></i></summary>
    </details> {% endcomment %}


    {% if not question_completed %}
        {% if resources %}
            <h5 class="mt-3">Resources</h5>
            <ul class="list-group list-group-flush mb-3">
                {% for caseresource in resources %}
                    <li class="list-group-item py-1 small">{{caseresource.resource.get_display}}</li>
                {% endfor %}
            </ul>
        {% endif %}
    {% endif %}


    {% if show_description and case.description %}
        <div class="mb-3">
            <h6 class="mb-1">Description</h6>
            <p class="mb-0">{{case.description}}</p>
        </div>
    {% endif %}
    {% if show_history %}
        <div class="card mb-3">
            <div class="card-body p-2 d-flex justify-content-between align-items-start">
                <div class="me-3 small text-muted">History: {{casedetail.get_history_pre|linebreaks}}</div>
                {% if has_priors %}
                    <div class="ms-2">
                        <span title="This case has priors available for comparison" class="badge bg-secondary text-white rounded-pill small">Priors{% if prior_count %} ({{ prior_count }}){% endif %}</span>
                    </div>
                {% endif %}
            </div>
        </div>
    {% endif %}

    {% if collection.show_ohif_viewer %}
        <div>

            {% if question_completed %}
                <iframe id="viewer" style="width: 100%; height: 100%; border: none; padding: 0px; min-height: 700px" src="/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% if case_number %}{% url 'atlas:collection_case_dicom_json_review' collection.pk case_number %}{% else %}{% url 'atlas:collection_case_dicom_json_review_legacy' collection.pk case.pk %}{% endif %}"></iframe>
            {% else %}
                <iframe id="viewer" style="width: 100%; height: 100%; border: none; padding: 0px; min-height: 700px" src="/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% if case_number %}{% url 'atlas:collection_case_dicom_json' collection.pk case_number %}{% else %}{% url 'atlas:collection_case_dicom_json_legacy' collection.pk case.pk %}{% endif %}"></iframe>
            {% endif %}

        </div>
    {% endif %}


    {% if collection.show_ohif_viewer_link %}
        <div>
            {% if question_completed %}
                <a target="_blank" href="/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% if case_number %}{% url 'atlas:collection_case_dicom_json_review' collection.pk case_number %}{% else %}{% url 'atlas:collection_case_dicom_json_review_legacy' collection.pk case.pk %}{% endif %}" title="Click to open the case in the advanced viewer. This will open in a new tab/window."><button class="viewer"><i class="bi bi-collection"></i> Launch advanced viewer.</button></a>
            {% else %}
                <a target="_blank" href="/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% if case_number %}{% url 'atlas:collection_case_dicom_json' collection.pk case_number %}{% else %}{% url 'atlas:collection_case_dicom_json_legacy' collection.pk case.pk %}{% endif %}" title="Click to open the case in the advanced viewer. This will open in a new tab/window."><button class="viewer"><i class="bi bi-collection"></i> Launch advanced viewer.</button></a>
            {% endif %}
        </div>
    {% endif %}

    {% if collection.show_built_in_viewer %}

        <details id="dicom-viewer-details" open>
            <summary>Viewer</summary>
            <div id="main_viewer" class="dicom-viewer-root"
                 style="box-sizing: border-box; background: #222; width: 100%; height: 600px;"
                 data-auto-cache-stack="false"
                 data-named-stacks='{{casedetail.get_case_named_stacks}}'
            ></div>
        </details>

{% comment %}         <div class="pre-whitespace multi-image-block">
            <details open>
                <summary>
                    Images
                </summary>
                {% for series, prior, relation in series_to_load %}
                    <span class="series-block
                                 {% if prior %}
                                     prior
                                 {% endif %}
                                ">
                        <a href="#" onclick='window.loadDicomViewer(window.images[{{forloop.counter0}}])'>
                            <span>
                                <span class="series-block-series-number">Series {{ forloop.counter }}:</span>
                                {{series.get_block}}
                            </span>
                            {% if prior %}
                                <br/><span class="relation">Prior: {{relation}}</span>
                            {% endif %}

                        </a>
                    </span>
                {% endfor %}
            </details>
        </div>

        <div>
            <div id="single-dicom-viewer" class="dicom-viewer" data-images="" data-annotations=''>
            </div>

        </div> {% endcomment %}
    {% else %}
    {% endif %}

    {% if show_discussion and case.discussion %}
        <details class="card mb-3">
            <summary class="card-header p-2" style="cursor: pointer;">
                <strong>Discussion</strong>
            </summary>
            <div class="card-body p-2 small">
                {{case.discussion|linebreaks}}
            </div>
        </details>
    {% endif %}
    {% if show_report and case.report %}
        <details class="card mb-3">
            <summary class="card-header p-2" style="cursor: pointer;">
                <strong>Report</strong>
            </summary>
            <div class="card-body p-2 small">
                {{case.report|linebreaks}}
            </div>
        </details>
    {% endif %}

    {% if question_completed %}
        {% if resources %}
            <h5>Resources</h4>
            <ul class="no-list-style">
                {% for caseresource in resources %}
                    <li>
                        {{caseresource.resource.get_display}}
                    </li>
                {% endfor %}
            </ul>
        {% endif %}


    {% endif %}
    <form method="POST" class="post-form{% if question_completed %} completed{% endif %}">{% csrf_token %}
        {% if collection.collection_type == "QUE" %}
            {% if question_completed %}
                <h3>Answers</h3>
                {% include "atlas/partials/collection_question_answer_block.html" %}

                {% if collection.self_review %}
                    <div>
                        <p>
                            <a href="{% url 'atlas:add_self_review' cid_user_exam.id case.id %}"><button type="button">Add self review</button></a>
                        </p>
                        {% if self_review %}
                            <h4>Self Feedback</h4>

                            {% for review in self_review %}
                                {{review.get_display_block}}

                            {% endfor %}
                        {% endif %}
                    </div>
                {% else %}
                    <h4>Answer score: {{answer.score}}</h4>
                    Answer feedback: {{answer.feedback|safe}}
                    <br/>
                {% endif %}

                <details><summary class="opacity-50">View questions</summary>
                    {{form.json.errors}}
                    <div class="form-contents">
                        <fieldset {% if question_completed %}disabled="disabled"{% endif %}>
                            {{form}}
                        </fieldset>
                    </div>
                </details>

            {% else %}

                {{form.json.errors}}
                <div class="form-contents">
                    <fieldset {% if question_completed %}disabled="disabled"{% endif %}>
                        {{form}}
                    </fieldset>
                </div>

            {% endif %}

        {% elif collection.collection_type == "REP" %}
            {{form.json.errors}}
            <div class="form-contents">
                <fieldset {% if question_completed %}disabled="disabled"{% endif %}>
                    {{form | crispy}}
                </fieldset>
            </div>

            {% if question_completed %}
                <div>
                    {% if collection.self_review %}
                        <p>
                            <a target="_blank" title="Add self review, this will open in a new page / tab" href="{% url 'atlas:add_self_review' cid_user_exam.id case.id %}"><button type="button">Add self review</button></a>
                        </p>
                        {% if self_review %}
                            <h4>Self Feedback</h4>

                            {% for review in self_review %}
                                {{review.get_display_block}}

                            {% endfor %}
                        {% endif %}
                    {% else %}
                        <h4>Answer score: {{answer.score}}</h4>
                        Answer feedback: {{answer.feedback|safe}}
                        <br/>
                    {% endif %}
                </div>
            {% endif %}

        {% endif %}
        <div class="mb-2">
            {% if previous %}
                <button type="submit" name="previous" class="btn btn-outline-secondary btn-sm me-2">Previous</button>
            {% endif %}
            {% if next %}
                <button type="submit" name="next" class="btn btn-primary btn-sm me-2">Next</button>
            {% elif collection.collection_type == "REP" %}
                {% if not exam.publish_results %}
                    <button type="submit" name="save" class="btn btn-primary btn-sm me-2">Save</button>
                {% endif %}
            {% endif %}
        </div>

        {% if collection.self_review and not collection.feedback_once_collection_complete and not question_completed %}
            <button type="submit" name="complete_case" class="btn btn-success btn-sm">Finish Case</button>
        {% endif %}


        <div class="mt-3">
            <button type="submit" name="finish" class="btn btn-outline-secondary btn-sm">Overview</button>
            <button type="submit" id="goto-button" value="test" name="goto" class="hide">goto</button>
        </div>
    </form>
    <style>
        label {
            vertical-align: top;

        }
        .series-block {
            border: darkblue solid 1px;
            padding: 1px;
            text-decoration: none;
            text-align: center;
        }
        .series-block a {
            all: unset;
        }
        .series-block:hover {
            background-color: darkblue;
        }

        .series-block.prior {
            border: darkgray solid 1px;
        }

        fieldset:disabled textarea {
            background-color: black;
        }

        form.completed {
        }

        .correct {
        }

        .correct h4::after {
            content: '✓';
            color: green;
        }

        .incorrect h4::after {
            content: '✗';
            color: orange;
        }

        .incorrect.automark h4::after {
            content: '✗';
            color: red;
        }

        .answer-block>div {
            padding-top: 10px;
        }

        .relation {
            opacity: 0.5;
            font-size: 0.8em;
        }

        .viewer {
            background-color: darkblue;
            color: white;
            border: none;
            border-radius: 5px;
            padding: 5px;
            opacity: 0.4;
        }

        .viewer:hover {
            opacity: 1;
            background-color: darkblue;

        }
    </style>

{% endblock %}
{% block js %}
    {{ form.media }}
{% comment %} <script src="https://cdn.jsdelivr.net/npm/@json-editor/json-editor@latest/dist/jsoneditor.min.js"></script> {% endcomment %}
    <script type="text/javascript">

        // Question time limit countdown + auto-submit
        $(function () {

            function lockQuestion() {
                // Only disable save buttons to prevent further saves
                $form = $('form.post-form');
                var $saveBtns = $form.find('button[name="save"], #id_answer');
                if ($saveBtns.length) {
                    $saveBtns.prop('disabled', true);
                }

                // Visual feedback: set timer to Locked and progress to red
                $progressInner = $('#question-timer-progress-inner');
                $('#question-timer').text('Locked');
                $progressInner.css('background', '#dc3545');
                $progressInner.css('width', '0%');

                $("#question-timer-progress-outer").hide();
            }

            try {
                var timeLimit = {{ collection.question_time_limit|default:'null' }};
                var questionCompleted = {{ question_completed|yesno:"true,false" }};
                var answerStartedAtIso = "{{ answer_started_at_iso|default:'null' }}";
                console.debug('Timer init:', {timeLimit: timeLimit, questionCompleted: questionCompleted});

                if (!timeLimit || questionCompleted) {
                    return;
                }

                {% if answer %}
                    if ({{answer.completed|yesno:"true,false"}}) {
                        lockQuestion();
                        console.debug('Timer: answer already completed, aborting timer init');
                        return;
                    }
                {% endif %}

                var $timer = $('#question-timer');
                var $form = $('form.post-form');

                if ($timer.length === 0 || $form.length === 0) {
                    console.debug('Timer: required elements not found, aborting timer init');
                    return;
                }

                // Compute remaining based on the canonical start time (if provided)
                var remaining = parseInt(timeLimit, 10);
                if (answerStartedAtIso) {
                    try {
                        var started = new Date(answerStartedAtIso);
                        var now = new Date();
                        var elapsed = Math.floor((now - started) / 1000);
                        remaining = Math.max(0, remaining - elapsed);
                        console.debug('Timer: using started_at, elapsed seconds:', elapsed, 'remaining:', remaining);
                    } catch (e) {
                        console.debug('Timer: invalid started_at iso, falling back to full timeLimit', e);
                    }
                }

                // If time has already elapsed when the page loads, lock the question and do not autosubmit.
                if (remaining <= 0) {
                    console.debug('Timer: time already expired on load, locking without autosubmit');
                    lockQuestion();
                    $timer.text(formatTime(0));
                    return;
                }

                function formatTime(s) {
                    var mins = Math.floor(s / 60);
                    var secs = s % 60;
                    return mins + ':' + (secs < 10 ? '0' + secs : secs);
                }

                var $progressInner = $('#question-timer-progress-inner');
                $timer.text(formatTime(remaining));

                function updateProgress() {
                    var pct = Math.max(0, Math.min(100, Math.round((remaining / timeLimit) * 100)));
                    var widthPct = pct;
                    $progressInner.css('width', widthPct + '%');

                    // Smooth color transition: green (120) -> orange (30) -> red (0)
                    // We use a two-stage interpolation so the midpoint (~50%) is orange.
                    var hue = 0;
                    if (pct > 50) {
                        // interpolate from orange (30) to green (120)
                        var t = (pct - 50) / 50.0; // 0..1
                        hue = 30 + t * (120 - 30);
                    } else {
                        // interpolate from red (0) to orange (30)
                        var t = pct / 50.0; // 0..1
                        hue = 0 + t * (30 - 0);
                    }

                    var color = 'hsl(' + Math.round(hue) + ', 75%, 40%)';
                    $progressInner.css('background', color);
                }

                updateProgress();

                var intervalId = setInterval(function () {
                    remaining -= 1;
                    if (remaining <= 0) {
                        clearInterval(intervalId);
                        $timer.text('0:00');
                        $progressInner.css('width', '0%');
                        $progressInner.css('background', '#dc3545');
                        //var $next = $form.find('button[name="next"]');
                        //var $finish = $form.find('button[name="finish"]');

                        // Instead of navigating away, submit via fetch with timed_out flag
                        // Use HTMX to POST the timed_out flag and then lock the UI

                        var onAfter = function (evt) {
                            try {
                                var resp = null;
                                try {
                                    var xhr = evt && evt.detail && evt.detail.xhr;
                                    if (xhr && xhr.responseText) {
                                        resp = JSON.parse(xhr.responseText);
                                    }
                                } catch (e) {
                                    console.debug('No JSON response from timed_out request', e);
                                }

                                lockQuestion();

                                var msg = 'Answer auto-submitted';
                                if (resp && resp.submitted_at) {
                                    try {
                                        var dt = new Date(resp.submitted_at);
                                        msg += ' at ' + dt.toLocaleTimeString();
                                    } catch (e) {}
                                }
                                toastr.info(msg);
                            } catch (e) {
                                console.error('Error handling timed_out htmx response', e);
                            } finally {
                                htmx.off('htmx:afterRequest', onAfter);
                            }
                        };

                        htmx.on('htmx:afterRequest', onAfter);
                        // Serialize the entire form so the server receives the user's answers
                        // along with the timed_out flag. This ensures the form.save() path
                        // can validate and persist the submitted answers on timeout.
                        (function(){
                            var formValues = {};
                            try {
                                $.each($form.serializeArray(), function(i, field) {
                                    if (formValues[field.name] !== undefined) {
                                        if (!Array.isArray(formValues[field.name])) {
                                            formValues[field.name] = [formValues[field.name]];
                                        }
                                        formValues[field.name].push(field.value);
                                    } else {
                                        formValues[field.name] = field.value;
                                    }
                                });
                            } catch (e) {
                                console.debug('Failed to serialize form with jQuery, falling back to manual collection', e);
                                // Fallback: try to collect inputs manually
                                var inputs = $form.find('input, textarea, select').not(':disabled');
                                inputs.each(function () {
                                    var $el = $(this);
                                    var name = $el.attr('name');
                                    if (!name) return;
                                    var val = $el.val();
                                    if (formValues[name] !== undefined) {
                                        if (!Array.isArray(formValues[name])) {
                                            formValues[name] = [formValues[name]];
                                        }
                                        formValues[name].push(val);
                                    } else {
                                        formValues[name] = val;
                                    }
                                });
                            }

                            // Ensure the timed_out flag is included
                            formValues['timed_out'] = '1';

                            htmx.ajax('POST', window.location.href, {
                                values: formValues,
                                swap: 'none',
                                headers: {
                                    'X-CSRFToken': document.querySelector('input[name="csrfmiddlewaretoken"]').value,
                                },
                                target: "#timer-htmx-target",
                            });
                        })();
                    } else {
                        $timer.text(formatTime(remaining));
                        updateProgress();
                    }
                }, 1000);

                $form.on('submit', function () {
                    clearInterval(intervalId);
                });
            } catch (e) {
                console.error('Error initializing timer:', e);
            }
        });

    </script>

{% endblock js %}
