{% extends 'anatomy/base.html' %}

{% block content %}
    {% load static %}
    {% include 'anatomy/question_link_header.html' %}

    <div class="row g-3">
        <div class="col-12 col-lg-6">
            <div class="card">
                <div class="card-body">
                    <div id="anatomy-dicom-image" class="dicom-image-legacy w-100" data-url="{{ question.get_image_url }}" data-annotations='{{question.image_annotations}}' data-edit_annotation="{{ can_edit|yesno:'true,false' }}" style="min-height:300px">
                    </div>
                    {% if not question.image_annotations %}
                        <div class="alert alert-warning mt-3" role="alert">
                            <strong>No image annotations defined.</strong>
                            <div class="small">If important markers or arrows are not burned onto the image, please add annotations using the image annotation tool and click <em>Save Annotations</em>. Please note not all questions required image annotations in which case you can ignore this message.</div>
                        </div>
                    {% endif %}
                    {% if can_edit %}
                        <div class="mt-3 align-items-start">
                            <div class="col" style="min-width:0;">
                                <details class="mb-0">
                                    <summary class="small text-muted"><i class="bi bi-info-circle"></i> Image annotation help</summary>
                                    <div class="small text-muted mt-2">Annotate the image using the right mouse button to click and drag an arrow. To remove an arrow drag it out of the image boundaries. Click <strong>Save Annotations</strong> to persist. If required use the middle button to zoom and the left button to pan.</div>
                                </details>
                            </div>
                            <div class="col-auto">
                                <div class="d-flex gap-2">
                                    <button id="save-annotations" class="btn btn-sm btn-primary">Save Annotations</button>
                                    <button id="delete-annotations" class="btn btn-sm btn-outline-danger">Delete Annotations</button>
                                </div>
                            </div>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>

        <div class="col-12 col-lg-6">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div>
                            <h5 class="card-title mb-1">Question</h5>
                            <div class="text-muted">Created: {{ question.created_date|date:"d/m/Y" }}</div>
                        </div>
                        <div class="text-end">
                            <h6 class="mb-0">Type: <span class="badge bg-secondary">{{ question.question_type }}</span></h6>
                        </div>
                    </div>

                    <h6 class="mt-2">Primary answer</h6>
                    {% if question.primary_answer %}
                        {% include 'anatomy/partials/primary_answer_display.html' %}
                    {% else %}
                        <div id="primary-answer-container" hx-get="{% url 'anatomy:primary_answer_htmx' pk=question.pk %}" hx-trigger="load" hx-swap="outerHTML"></div>
                    {% endif %}

                    <style>
                        .answer.correct { color: #155724; }
                        .answer.half-correct { color: #856404; }
                        .answer.incorrect { color: #721c24; }
                        .marked-correct { border-left: 4px solid #2a9d3f; }
                        .marked-half-correct { border-left: 4px solid #ffb020; }
                        .marked-incorrect { border-left: 4px solid #d3413a; }
                    </style>

                    <div class="d-flex justify-content-between align-items-start">
                        <h6 class="mb-0">Answers</h6>
                        <div>
                            {% if can_edit %}
                                <a class="btn btn-sm btn-outline-secondary" href="{% url 'anatomy:question_answer_update' pk=question.pk %}">Edit answers</a>
                            {% endif %}
                        </div>
                    </div>
                    <details class="mb-3">
                        <summary class="small">Show answers</summary>
                        <table class="table table-sm mt-2">
                            <thead>
                                <tr><th>Answer</th><th>Score</th><th></th></tr>
                            </thead>
                            <tbody>
                                {% for answer in question.answers.all|dictsortreversed:"status" %}
                                    {% comment %}Add visual mark state classes consistent with mark2{% endcomment %}
                                    <tr class="{% if answer.status == '2' %}marked-correct{% elif answer.status == '1' %}marked-half-correct{% elif answer.status == '0' %}marked-incorrect{% endif %}">
                                        <td {% if answer.proposed %}class="proposed-answer" data-aid="{{answer.pk}}" data-question-type="anatomy"{% endif %}>
                                            {% if answer.status == "0" %}
                                                <div class="d-flex align-items-start">
                                                    <button type="button" class="btn btn-sm btn-link text-muted p-0 toggle-words-btn me-2" title="Suggest words: show candidate words extracted from this stored answer (click to quick-add)" aria-expanded="false" aria-label="Suggest words"><i class="bi bi-lightbulb-fill"></i></button>
                                                    <div class="flex-grow-1">
                                                            <pre class="mb-0">{{ answer.answer }}</pre>
                                                        <div class="mt-1">
                                                            <div class="word-buttons d-none mt-2" aria-hidden="true"></div>
                                                        </div>
                                                    </div>
                                                </div>
                                            {% else %}
                                                    <pre class="mb-0">{{ answer.answer }}</pre>
                                            {% endif %}
                                        </td>
                                        <td>
                                            {% if answer.status == '2' %}
                                                <span class="answer correct">{{ answer.get_status_display|default:'Correct' }}</span>
                                            {% elif answer.status == '1' %}
                                                <span class="answer half-correct">{{ answer.get_status_display|default:'Half mark' }}</span>
                                            {% elif answer.status == '0' %}
                                                <span class="answer incorrect">{{ answer.get_status_display|default:'Incorrect' }}</span>
                                            {% else %}
                                                <span class="answer not-marked">{{ answer.get_status_display|default:'Unmarked' }}</span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            {% if answer.proposed and can_edit %}
                                                <div class="btn-group btn-group-sm" role="group">
                                                    <button class="btn btn-outline-success accept-button" data-aid={{answer.id}} hx-get="{% url 'anatomy:confirm_answer' answer.id %}" title="Accept">Accept</button>
                                                    <button class="btn btn-outline-danger delete-button" data-aid={{answer.id}} hx-get="{% url 'anatomy:delete_answer' answer.id %}" title="Delete">Delete</button>
                                                </div>
                                            {% endif %}
                                        </td>
                                    </tr>
                                {% empty %}
                                    <tr><td colspan="3" class="small text-muted">No stored answers</td></tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </details>

                    {% if question.answer_help %}
                        <div class="mb-3">
                            <h6>Answer help</h6>
                            <div class="small text-muted">{{ question.answer_help|safe }}</div>
                        </div>
                    {% endif %}

                    <div class="mb-2">
                        {% include 'anatomy/partials/suggest_incorrect_collapsed.html' %}
                    </div>

                    <div class="mb-2">
                        <h6>Description</h6>
                        <div class="small text-muted">{{ question.description }}</div>
                    </div>

                    <div class="row">
                        <div class="col-12 col-md-6">
                            <div class="mb-1"><strong>Modality:</strong> {{ question.modality }}</div>
                            <div class="mb-1"><strong>Region:</strong> {{ question.region }}</div>
                            <div class="mb-1"><strong>Structure:</strong> {{ question.structure }}</div>
                        </div>
                        <div class="col-12 col-md-6">
                            <div class="mb-1"><strong>Body part:</strong> {{ question.body_part }}</div>
                            <div class="mb-1"><strong>Open access:</strong> {{ question.open_access }}</div>
                            <div class="mb-1"><strong>Author:</strong> {% for author in question.author.all %}{{ author }}{% if not forloop.last %}, {% endif %}{% endfor %}</div>
                        </div>
                    </div>

                    <div class="mt-3">
                        <h6>Exams</h6>
                        {% include 'anatomy/partials/exam_links.html' %}
                        {% if can_edit %}
                            <div class="mt-2"><button class="btn btn-sm btn-outline-secondary" hx-get="{% url 'anatomy:question_add_exam' question_id=question.pk %}" hx-target="#exam-list" hx-swap="innerHTML">Edit exam(s)</button>
                                <span id="exam-list"></span>
                            </div>
                        {% endif %}
                    </div>

                    {% include 'question_notes.html' %}

                    <div class="mt-3">
                        <details>
                            <summary class="small">Annotation JSON</summary>
                            <div class="mt-2 small">
                                {% if question.image_annotations %}
                                    {% include 'atlas/partials/json_pretty.html' with json_value=question.image_annotations title='Image annotations' %}
                                {% else %}
                                    No saved annotations.
                                {% endif %}
                            </div>
                        </details>
                    </div>

                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(document).ready(function () {

        //$("#annotation-json-toggle").click(() => {
        //    $("#annotation-json-content").toggle()
        //});

        // send request to change the is_private state on customSwitches toggle
            $("#save-annotations").click(function () {
                json = getJsonToolStateNoId();
                $.ajax({
                    url: "{% url 'anatomy:question_save_annotation' pk=question.pk %}",
                    data: {
                        csrfmiddlewaretoken: "{{ csrf_token }}",
                        annotation: json,
                    },
                    type: "POST",
                    dataType: "json",
                    error: function (e) {
                        toastr.warning(`Error saving annotations`)
                        console.log(e);
                    },

                })
                // $.ajax().done(), $.ajax().fail(), $ajax().always() are upto you. Add/change accordingly
                    .done(function (data) {
                        console.log(data);
                    // show some message according to the response. 
                    // For eg. A message box showing that the status has been changed
                        if (data.status == "success") {
                            toastr.info('Annotations saved')
                        } else {
                            toastr.warning('Error saving annotations')
                        }
                    })
                    .always(function () {
                        console.log('[Done]');
                    })
            })
            $("#delete-annotations").click(function () {
                if (!confirm('Clear saved annotations for this question? This cannot be undone.')) return;
                $.ajax({
                    url: "{% url 'anatomy:question_clear_annotation' pk=question.pk %}",
                    data: {
                        csrfmiddlewaretoken: "{{ csrf_token }}",
                    },
                    type: "POST",
                    dataType: "json",
                })
                    .done(function (data) {
                        if (data.status == "success") {
                            toastr.info('Annotations cleared');
                                // Optionally reload part of the page or remove the annotation overlay
                            location.reload();
                        } else {
                            toastr.warning('Error clearing annotations');
                        }
                    })
                    .fail(function () {
                        toastr.warning('Error clearing annotations');
                    });
            });
        });


        function getJsonToolStateNoId() {
            const el = document.getElementById("anatomy-dicom-image");

            const c = cornerstone.getEnabledElement(el);

            const toolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager;

            const image_id = c.image.imageId;

            const state_with_id = toolStateManager.saveToolState()

            const json_tool_state = JSON.stringify(state_with_id[image_id]);

            return json_tool_state;

        }
    </script>
    <script>
        // HTMX quick-add helpers for word buttons inside the answers table
        var SUGGEST_URL = "{% url 'anatomy:question_suggest_incorrect_answers' question.pk %}";
        var CSRF_TOKEN = "{{ csrf_token }}";

        function toggleWords(btn) {
            var container = btn.nextElementSibling; // the flex-grow-1 wrapper
            if (!container) return;
            var wordContainer = container.querySelector('.word-buttons');
            if (!wordContainer) return;
            // populate if empty
            if (!wordContainer.dataset.populated) {
                var pre = container.querySelector('pre');
                var text = pre ? pre.textContent || pre.innerText : '';
                buildWordButtons(wordContainer, text);
                wordContainer.dataset.populated = '1';
            }
            var expanded = !wordContainer.classList.contains('d-none');
            if (expanded) {
                wordContainer.classList.add('d-none');
                btn.setAttribute('aria-expanded', 'false');
                wordContainer.setAttribute('aria-hidden', 'true');
            } else {
                wordContainer.classList.remove('d-none');
                btn.setAttribute('aria-expanded', 'true');
                wordContainer.setAttribute('aria-hidden', 'false');
            }
        }

        function buildWordButtons(container, text) {
            if (!text) return;
            var toks = (text.toLowerCase().match(/\w+/g) || []);
            var seen = {};
            toks.forEach(function(t){
                if (t.length < 3) return;
                if (seen[t]) return;
                seen[t]=true;
                var b = document.createElement('button');
                b.type = 'button';
                b.className = 'btn btn-sm btn-outline-primary me-1 mb-1';
                b.textContent = t;
                b.dataset.word = t;
                // do not attach inline handlers here; use delegated listener
                container.appendChild(b);
            });
            if (!Object.keys(seen).length) {
                var span = document.createElement('div');
                span.className = 'small text-muted';
                span.textContent = 'No suitable words';
                container.appendChild(span);
            }
        }

        // Delegated click handler to keep markup unobtrusive and work for HTMX swaps
        document.addEventListener('click', function(e){
            var toggle = e.target.closest('.toggle-words-btn');
            if (toggle) {
                e.preventDefault();
                toggleWords(toggle);
                return;
            }
            var wordBtn = e.target.closest('.word-buttons button');
            if (wordBtn) {
                e.preventDefault();
                var word = wordBtn.dataset.word || wordBtn.textContent.trim();
                if (word) addQuickSuggestion(word);
                return;
            }
        });

        function addQuickSuggestion(word) {
            if (!word) return;
            if (typeof htmx === 'undefined') {
                // Fallback: simple POST via fetch
                fetch(SUGGEST_URL, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken': CSRF_TOKEN },
                    body: new URLSearchParams({ suggestion: word, quick: '1' })
                }).then(function(r){ return r.text(); }).then(function(html){
                    var wrapper = document.getElementById('incorrect-answers');
                    if (wrapper) wrapper.innerHTML = html;
                });
                return;
            }

            htmx.ajax('POST', SUGGEST_URL, {
                values: { suggestion: word, quick: '1' },
                headers: { 'X-CSRFToken': CSRF_TOKEN },
                target: '#incorrect-answers',
                swap: 'innerHTML'
            });
        }
    </script>
{% endblock %}

{% block css %}
    <style>
        .proposed-answer::before {
            content: "\F505";
            font-family: bootstrap-icons;
        }
        /* Ensure pre-wrapped content inside cards and tables so long answers don't overflow */
        .card pre, .table pre { margin: 0; white-space: pre-wrap; word-break: break-word; }

        .card .mb-2, .card .mb-3 { margin-bottom: .75rem; }
    </style>
{% endblock css %}