{% extends "base.html" %}

{% block content %}
    <h1>Manage Questions for {{ assessment.name }}</h1>

    <hr>
    <h2>Bulk Upload Questions</h2>
    <p>Download the template file, fill it out, and upload it to add questions in bulk.</p>
    <a href="{{ url_for('admin.download_question_template', assessment_id=assessment.id) }}"
       class="btn btn-secondary mb-3"
       target="_blank"
       rel="noopener"
       download="{{ assessment.assessment_type.replace(' ', '_') }}_question_template.xlsx">
       Download Excel Template
    </a>
    <button type="button" class="btn btn-outline-secondary mb-3 ml-2" onclick="downloadTemplateViaFetch()">Download (Fallback)</button>
    <br>
    <form method="POST" action="{{ url_for('admin.manage_questions', assessment_id=assessment.id) }}" enctype="multipart/form-data" class="mb-4">
        <div class="form-group">
            <label for="file">Upload File:</label>
            <input type="file" name="file" id="file" accept=".xlsx" class="form-control-file">
        </div>
        <button type="submit" class="btn btn-primary">Upload Questions</button>
    </form>
    <hr>
    
    <h2>Add New Question Manually</h2>
    <form method="POST" class="mb-4">
        <div class="form-group">
            <label for="text">Question Text:</label>
            <textarea id="text" name="text" class="form-control" rows="3" required></textarea>
        </div>
        <div class="form-group">
            <label for="question_type">Question Type:</label>
            <select id="question_type" name="question_type" class="form-control">
                <option value="multiple_choice">Multiple Choice</option>
                <option value="yes_no">Yes/No</option>
                <option value="likert">Likert Scale</option>
                <option value="blank">Fill in the Blank</option>
            </select>
        </div>
        <div class="form-group">
            <label for="domain">Domain (Optional):</label>
            <input type="text" id="domain" name="domain" class="form-control">
        </div>
        <div class="form-group">
            <label for="choices_and_scores">Choices and Scores (e.g., Option A:1|Option B:2):</label>
            <input type="text" id="choices_and_scores" name="choices_and_scores" class="form-control">
            <small class="form-text text-muted">Separate choices with '|' and text from score with ':' (e.g., Yes:1|No:0)</small>
        </div>
        <button type="submit" class="btn btn-primary">Add Question</button>
    </form>

    <h2>Existing Questions</h2>
    <form id="delete-questions-form" method="POST" action="{{ url_for('admin.delete_questions', assessment_id=assessment.id) }}">
        <button type="submit" class="btn btn-danger mb-3">Delete Selected</button>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th><input type="checkbox" id="select-all"></th>
                    <th>Question Text</th>
                    <th>Type</th>
                    <th>Domain</th>
                    <th>Choices & Scores</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                {% for question in questions %}
                <tr>
                    <td><input type="checkbox" name="question_ids" value="{{ question.id }}"></td>
                    <td>{{ question.text }}</td>
                    <td>{{ question.question_type }}</td>
                    <td>{{ question.domain if question.domain else 'N/A' }}</td>
                    <td>
                        {% for choice in question.choices %}
                            {{ choice.text }}:{{ choice.weightage }}{% if not loop.last %}|{% endif %}
                        {% else %}
                            N/A
                        {% endfor %}
                    </td>
                    <td>
                        <a href="#" class="btn btn-sm btn-info">Manage Choices</a>
                        <a href="{{ url_for('admin.edit_question', assessment_id=assessment.id, question_id=question.id) }}" class="btn btn-sm btn-warning">Edit</a>
                        <a href="{{ url_for('admin.delete_question', assessment_id=assessment.id, question_id=question.id) }}" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this question?');">Delete</a>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </form>
{% endblock %}

{% block scripts %}
<script>
    document.getElementById('select-all').addEventListener('change', function(event) {
        const checkboxes = document.querySelectorAll('input[name="question_ids"]');
        checkboxes.forEach(checkbox => {
            checkbox.checked = event.target.checked;
        });
    });

    document.getElementById('delete-questions-form').addEventListener('submit', function(event) {
        const checked = document.querySelectorAll('input[name="question_ids"]:checked');
        if (checked.length === 0) {
            alert('Please select at least one question to delete.');
            event.preventDefault();
        } else if (!confirm('Are you sure you want to delete the selected questions?')) {
            event.preventDefault();
        }
    });
</script>
<script>
    function downloadTemplateViaFetch() {
        const url = "{{ url_for('admin.download_question_template', assessment_id=assessment.id) }}";
        fetch(url)
            .then(resp => resp.blob())
            .then(blob => {
                const a = document.createElement('a');
                const urlObj = URL.createObjectURL(blob);
                a.href = urlObj;
                a.download = "{{ assessment.assessment_type.replace(' ', '_') }}_question_template.xlsx";
                document.body.appendChild(a);
                a.click();
                URL.revokeObjectURL(urlObj);
                a.remove();
            })
            .catch(() => alert('Failed to download template. Please try again.'));
    }
</script>
{% endblock %}
