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

{% block content %}
    <div class="container py-4">
        <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
            <div>
                <h1 class="h2 mb-1">Linked Cases Overview</h1>
                <p class="text-muted mb-0">Review the full case chain around this study, with quick access to related cases and their linked series.</p>
            </div>
            <div class="d-flex flex-wrap gap-2">
                <a class="btn btn-outline-secondary" href="{{ current_case.get_absolute_url }}">Open current case</a>
                {% if direct_previous %}
                    <a class="btn btn-outline-secondary" href="{% url 'atlas:linked_cases_overview' direct_previous.pk %}">Previous in chain</a>
                {% endif %}
                {% if direct_next %}
                    <a class="btn btn-outline-secondary" href="{% url 'atlas:linked_cases_overview' direct_next.pk %}">Next in chain</a>
                {% endif %}
                {% if can_edit_chain and not show_case_editor %}
                    <a class="btn btn-outline-info" href="{% url 'atlas:linked_cases_overview' current_case.pk %}?show_editor=1">Open case series editor</a>
                {% endif %}
                {% if show_case_editor %}
                    <a class="btn btn-outline-secondary" href="{% url 'atlas:linked_cases_overview' current_case.pk %}">Hide case series editor</a>
                {% endif %}
                {% if can_edit_chain and not show_study_dates_editor %}
                    <a class="btn btn-outline-primary" href="{% url 'atlas:linked_cases_overview' current_case.pk %}?show_dates=1">Open study dates editor</a>
                {% endif %}
                {% if show_study_dates_editor %}
                    <a class="btn btn-outline-secondary" href="{% url 'atlas:linked_cases_overview' current_case.pk %}">Hide study dates editor</a>
                {% endif %}
                {% if can_edit_chain and not show_reorder_editor %}
                    <a class="btn btn-outline-warning" href="{% url 'atlas:linked_cases_overview' current_case.pk %}?show_reorder=1">Open case reorder editor</a>
                {% endif %}
                {% if show_reorder_editor %}
                    <a class="btn btn-outline-secondary" href="{% url 'atlas:linked_cases_overview' current_case.pk %}">Hide case reorder editor</a>
                {% endif %}
            </div>
        </div>

        {% if can_edit_chain and show_study_dates_editor %}
            <div class="card border-secondary-subtle shadow-sm mb-4">
                <div class="card-body">
                    <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
                        <div>
                            <h2 class="h5 mb-1">Study Dates</h2>
                            <p class="text-muted mb-0">Edit each case date directly, or use the copy action to apply one case date to the rest of the linked chain.</p>
                        </div>
                        {% if anchor_date %}
                            <div class="small text-muted">Relative offsets are measured from {{ anchor_date|date:"Y-m-d" }}.</div>
                        {% endif %}
                    </div>

                    <form method="post">
                        {% csrf_token %}
                        <input type="hidden" name="form_action" value="study_dates">
                        <div class="table-responsive">
                            <table class="table table-dark table-hover align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th scope="col">Case</th>
                                        <th scope="col" class="text-nowrap">Study date</th>
                                        <th scope="col" class="text-nowrap">Relative</th>
                                        <th scope="col" class="text-nowrap">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for row in linked_case_rows %}
                                        <tr class="{% if row.is_current %}table-primary{% endif %}">
                                            <td>
                                                <div class="fw-semibold">{{ row.case.title|default:"Untitled case" }}</div>
                                                <div class="small text-muted">Case {{ row.case.pk }}{% if row.is_current %} · current{% endif %}</div>
                                            </td>
                                            <td style="min-width: 14rem;">
                                                <input
                                                    type="date"
                                                    class="form-control form-control-sm"
                                                    name="study_date_{{ row.case.pk }}"
                                                    value="{% if row.study_date %}{{ row.study_date|date:'Y-m-d' }}{% endif %}"
                                                    {% if not row.can_edit %}disabled{% endif %}
                                                >
                                            </td>
                                            <td class="text-nowrap">
                                                {% if row.relative_label %}
                                                    {{ row.relative_label.text }}
                                                {% else %}
                                                    <span class="text-muted">No anchor</span>
                                                {% endif %}
                                            </td>
                                            <td class="text-nowrap">
                                                <button
                                                    type="submit"
                                                    class="btn btn-sm btn-outline-info"
                                                    name="apply_to_all_from"
                                                    value="{{ row.case.pk }}"
                                                    {% if not row.can_edit %}disabled{% endif %}
                                                >
                                                    Copy to others
                                                </button>
                                            </td>
                                        </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                        <div class="d-flex flex-wrap justify-content-end gap-2 mt-3">
                            <button type="submit" class="btn btn-primary">Save study dates</button>
                        </div>
                    </form>
                </div>
            </div>
        {% endif %}

        {% if can_edit_chain and show_reorder_editor %}
            <div class="card border-warning-subtle shadow-sm mb-4">
                <div class="card-body">
                    <h2 class="h5 mb-1 text-warning-emphasis">Reorder Cases</h2>
                    <p class="text-muted mb-3">Drag and drop cases to reorder them, or use the Up/Down buttons, then click Save.</p>

                    <form method="post" id="reorder-cases-form">
                        {% csrf_token %}
                        <input type="hidden" name="form_action" value="reorder_cases">
                        <ul id="cases-reorder-list" class="list-group mb-3">
                            {% for linked_case in chain_cases %}
                                <li class="list-group-item d-flex justify-content-between align-items-center {% if linked_case.pk == current_case.pk %}border-primary{% endif %}" data-case-id="{{ linked_case.pk }}">
                                    <span>
                                        <i class="bi bi-grip-vertical me-2 text-muted drag-handle" style="cursor: grab;"></i>
                                        <span class="fw-semibold">Case {{ linked_case.pk }}:</span> {{ linked_case.title|default:"Untitled case" }}
                                        {% if linked_case.pk == current_case.pk %}<span class="badge bg-primary ms-1">Current</span>{% endif %}
                                    </span>
                                    <span>
                                        <button type="button" class="btn btn-sm btn-outline-secondary move-up">↑</button>
                                        <button type="button" class="btn btn-sm btn-outline-secondary move-down">↓</button>
                                    </span>
                                    <input type="hidden" name="case_order" value="{{ linked_case.pk }}">
                                </li>
                            {% endfor %}
                        </ul>
                        <div class="d-flex justify-content-end">
                            <button type="submit" class="btn btn-warning">Save Case Order</button>
                        </div>
                    </form>
                </div>
            </div>
        {% endif %}

        {% if show_case_editor and case_editor_formset %}
            <div class="card border-info-subtle shadow-sm mb-4">
                <div class="card-body">
                    <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
                        <div>
                            <h2 class="h5 mb-1">Case Series Editor</h2>
                            <p class="text-muted mb-0">Edit full case details across this linked chain in one pass, then optionally copy a single field from one case to every other case.</p>
                        </div>
                        <div class="small text-muted">
                            Editable: {{ editable_case_count }}
                            {% if locked_case_count %} · Read-only: {{ locked_case_count }}{% endif %}
                        </div>
                    </div>

                    <form method="post">
                        {% csrf_token %}
                        <input type="hidden" name="form_action" value="case_series_editor">
                        {{ case_editor_formset.management_form }}

                        <div class="row g-2 align-items-end mb-3">
                            <div class="col-md-4">
                                <label class="form-label form-label-sm mb-1">Copy field from case</label>
                                <select class="form-select form-select-sm" name="apply_from_case">
                                    <option value="">No field propagation</option>
                                    {% for row in case_editor_rows %}
                                        <option value="{{ row.case.pk }}" {% if case_editor_selected_source == row.case.pk|stringformat:'s' %}selected{% endif %}>
                                            {{ row.case.pk }} · {{ row.case.title|default:"Untitled case" }}
                                        </option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="col-md-5">
                                <label class="form-label form-label-sm mb-1">Field to copy to all linked cases</label>
                                <select class="form-select form-select-sm" name="apply_field">
                                    <option value="">Choose a field</option>
                                    {% for value, label in case_editor_apply_field_choices %}
                                        <option value="{{ value }}" {% if case_editor_selected_field == value %}selected{% endif %}>{{ label }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="col-md-3">
                                <div class="small text-muted">Apply runs after saving any edits you make below.</div>
                            </div>
                        </div>

                        <div class="accordion" id="linked-case-editor-accordion">
                            {% for row in case_editor_rows %}
                                <div class="accordion-item mb-2 border-secondary-subtle">
                                    <h2 class="accordion-header" id="editor-heading-{{ row.case.pk }}">
                                        <button class="accordion-button {% if not row.is_current %}collapsed{% endif %}" type="button" data-bs-toggle="collapse" data-bs-target="#editor-body-{{ row.case.pk }}" aria-expanded="{% if row.is_current %}true{% else %}false{% endif %}" aria-controls="editor-body-{{ row.case.pk }}">
                                            <span class="fw-semibold">Case {{ row.case.pk }} · {{ row.case.title|default:"Untitled case" }}</span>
                                            {% if row.is_current %}<span class="badge text-bg-primary ms-2">Current</span>{% endif %}
                                        </button>
                                    </h2>
                                    <div id="editor-body-{{ row.case.pk }}" class="accordion-collapse collapse {% if row.is_current %}show{% endif %}" aria-labelledby="editor-heading-{{ row.case.pk }}" data-bs-parent="#linked-case-editor-accordion">
                                        <div class="accordion-body">
                                            {{ row.form|crispy }}
                                        </div>
                                    </div>
                                </div>
                            {% endfor %}
                        </div>

                        <div class="d-flex justify-content-end mt-3">
                            <button type="submit" class="btn btn-info">Save case series editor changes</button>
                        </div>
                    </form>
                </div>
            </div>
        {% endif %}

        <div class="row g-3 mb-4">
            <div class="col-lg-8">
                <div class="card border-secondary-subtle shadow-sm h-100">
                    <div class="card-body">
                        <div class="d-flex flex-wrap align-items-center gap-2 mb-2">
                            <span class="badge bg-primary">Current case</span>
                            <span class="badge bg-dark-subtle text-dark-emphasis">{{ current_index }} of {{ chain_total }}</span>
                            {% if previous_cases %}
                                <span class="badge text-bg-light border">{{ previous_cases|length }} previous</span>
                            {% endif %}
                            {% if next_cases %}
                                <span class="badge text-bg-light border">{{ next_cases|length }} follow-up</span>
                            {% endif %}
                        </div>
                        <h2 class="h4 mb-1">{{ current_case.title|default:"Untitled case" }}</h2>
                        <div class="small text-muted mb-3">Case {{ current_case.pk }}</div>
                        {% if current_case.description %}
                            <p class="mb-3">{{ current_case.description|striptags|truncatechars:280 }}</p>
                        {% elif current_case.history %}
                            <p class="mb-3">{{ current_case.history|striptags|truncatechars:280 }}</p>
                        {% endif %}

                        <div class="d-flex flex-wrap gap-2 small">
                            {% if current_case.open_access %}
                                <span class="badge bg-success">Open access</span>
                            {% else %}
                                <span class="badge bg-warning text-dark">Restricted</span>
                            {% endif %}
                            {% if current_case.verified %}
                                <span class="badge bg-info text-dark">Verified</span>
                            {% endif %}
                            {% if current_case.archive %}
                                <span class="badge bg-dark">Archived</span>
                            {% endif %}
                            {% if current_case.diagnostic_certainty %}
                                <span class="badge text-bg-light border">{{ current_case.get_diagnostic_certainty_display }}</span>
                            {% endif %}
                            <span class="badge text-bg-light border">{{ current_case.get_ordered_series|length }} series</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4">
                <div class="card border-secondary-subtle shadow-sm h-100">
                    <div class="card-body">
                        <h2 class="h5 mb-3">Chain Summary</h2>
                        <div class="list-group list-group-flush small">
                            {% for linked_case in chain_cases %}
                                <a href="{% url 'atlas:linked_cases_overview' linked_case.pk %}"
                                   class="list-group-item list-group-item-action d-flex justify-content-between align-items-center {% if linked_case.pk == current_case.pk %}active{% endif %}">
                                    <span class="text-truncate pe-3">{{ forloop.counter }}. {{ linked_case.title|default:"Untitled case" }}</span>
                                    <span class="badge {% if linked_case.pk == current_case.pk %}text-bg-light{% else %}text-bg-secondary{% endif %}">{{ linked_case.pk }}</span>
                                </a>
                            {% endfor %}
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-4">
            <div class="col-xl-6">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h2 class="h4 mb-0">Previous Cases</h2>
                    <span class="badge text-bg-light border">{{ previous_cases|length }}</span>
                </div>
                {% if previous_cases %}
                    <div class="d-flex flex-column gap-3">
                        {% for linked_case in previous_cases %}
                            {% include "atlas/partials/_linked_case_card.html" with relation_label="Earlier in the linked chain" relative_label=linked_case.relative_label is_current=False %}
                        {% endfor %}
                    </div>
                {% else %}
                    <div class="card border-secondary-subtle shadow-sm">
                        <div class="card-body text-muted">No previous linked cases.</div>
                    </div>
                {% endif %}
            </div>

            <div class="col-xl-6">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h2 class="h4 mb-0">Next Cases</h2>
                    <span class="badge text-bg-light border">{{ next_cases|length }}</span>
                </div>
                {% if next_cases %}
                    <div class="d-flex flex-column gap-3">
                        {% for linked_case in next_cases %}
                            {% include "atlas/partials/_linked_case_card.html" with relation_label="Later in the linked chain" relative_label=linked_case.relative_label is_current=False %}
                        {% endfor %}
                    </div>
                {% else %}
                    <div class="card border-secondary-subtle shadow-sm">
                        <div class="card-body text-muted">No follow-up linked cases.</div>
                    </div>
                {% endif %}
            </div>
        </div>
    </div>
{% endblock %}

{% block css %}
    <style>
        #cases-reorder-list .dragging {
            opacity: 0.55;
            box-shadow: 0 4px 16px rgba(255, 193, 7, 0.35);
        }
        #cases-reorder-list .drag-over {
            border: 2px dashed #ffc107 !important;
        }
    </style>
{% endblock %}

{% block js %}
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            // Move up/down logic
            document.querySelectorAll("#cases-reorder-list .move-up, #cases-reorder-list .move-down").forEach(function(btn) {
                btn.addEventListener("click", function(e) {
                    e.preventDefault();
                    const li = btn.closest("li");
                    if (btn.classList.contains("move-up") && li.previousElementSibling) {
                        li.parentNode.insertBefore(li, li.previousElementSibling);
                    }
                    if (btn.classList.contains("move-down") && li.nextElementSibling) {
                        li.parentNode.insertBefore(li.nextElementSibling, li);
                    }
                });
            });

            // On submit, update the hidden inputs to match the new order
            const reorderCasesForm = document.getElementById("reorder-cases-form");
            if (reorderCasesForm) {
                reorderCasesForm.addEventListener("submit", function(e) {
                    const lis = document.querySelectorAll("#cases-reorder-list li");
                    lis.forEach((li, idx) => {
                        const input = li.querySelector("input[name='case_order']");
                        if (input) {
                            input.setAttribute("name", "case_order_" + idx);
                        }
                    });
                });
            }

            // Drag and drop reordering for cases list
            const reorderList = document.getElementById("cases-reorder-list");
            let draggedItem = null;

            if (reorderList) {
                reorderList.querySelectorAll("li").forEach(function(li) {
                    li.setAttribute("draggable", "true");

                    li.addEventListener("dragstart", function(e) {
                        draggedItem = li;
                        li.classList.add("dragging");
                        e.dataTransfer.effectAllowed = "move";
                    });

                    li.addEventListener("dragend", function() {
                        draggedItem = null;
                        li.classList.remove("dragging");
                        reorderList.querySelectorAll("li").forEach(el => el.classList.remove("drag-over"));
                    });

                    li.addEventListener("dragover", function(e) {
                        e.preventDefault();
                        e.dataTransfer.dropEffect = "move";
                        li.classList.add("drag-over");
                    });

                    li.addEventListener("dragleave", function() {
                        li.classList.remove("drag-over");
                    });

                    li.addEventListener("drop", function(e) {
                        e.preventDefault();
                        li.classList.remove("drag-over");
                        if (draggedItem && draggedItem !== li) {
                            const rect = li.getBoundingClientRect();
                            const next = (e.clientY - rect.top) / (rect.bottom - rect.top) > 0.5;
                            li.parentNode.insertBefore(draggedItem, next ? li.nextElementSibling : li);
                        }
                    });
                });
            }
        });
    </script>
{% endblock %}