{% extends "atlas/base.html" %}
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
    {% include "atlas/question_link_header.html" %}
    <h2>Update Series for Case: {{ object.title }}</h2>
    <form method="post" enctype="multipart/form-data"  data-bs-theme="dark">
        {% csrf_token %}
        {% crispy form form.helper %}
        {{ series_formset.management_form }}
        <div id="series_formset">
            {% for form in series_formset %}
                <div class="card mb-3 series-form">
                    <div class="card-body">
                        {{ form.non_field_errors }}
                        {{ form.errors }}
                        {{ form|crispy }}
                        {% if form.can_delete %}
                            <div class="form-check mt-2">
                                {{ form.DELETE }} <label for="{{ form.DELETE.id_for_label }}">Delete</label>
                            </div>
                        {% endif %}
                    </div>
                </div>
            {% endfor %}
        <!-- Empty form template for JS -->
        <div id="empty-form" style="display:none;">
            <div class="card mb-3 series-form">
                <div class="card-body">
                    {{ series_formset.empty_form|crispy }}
                    {% if series_formset.empty_form.can_delete %}
                        <div class="form-check mt-2">
                            {{ series_formset.empty_form.DELETE }} <label for="{{ series_formset.empty_form.DELETE.id_for_label }}">Delete</label>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
        <button type="button" id="add-series" class="btn btn-secondary mt-2">Add Series</button>
        <button type="submit" class="btn btn-primary">Save</button>
    </form>

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const addBtn = document.getElementById("add-series");
            const formsetDiv = document.getElementById("series_formset");
            const emptyFormDiv = document.getElementById("empty-form");
            let totalForms = document.getElementById("id_seriesdetail_set-TOTAL_FORMS");

            addBtn.addEventListener("click", function() {
                let formIdx = parseInt(totalForms.value);
                let newFormHtml = emptyFormDiv.innerHTML.replace(/__prefix__/g, formIdx);
                let tempDiv = document.createElement('div');
                tempDiv.innerHTML = newFormHtml;
    // Clear the id field value for the new form
                let idInput = tempDiv.querySelector('input[name$="-id"]');
                if (idInput) {
                    idInput.value = "";
                }
                formsetDiv.appendChild(tempDiv.firstElementChild);
                totalForms.value = formIdx + 1;
            });
        });
    </script>
{% endblock %}