{% extends 'generic/object_edit.html' %}
{% load static %}
{% load form_helpers %}
{% load i18n %}

{% block form %}
    {# Render hidden fields #}
    {% for field in form.hidden_fields %}
        {{ field }}
    {% endfor %}

    {# Render regular fieldsets #}
    {% for fieldset in form.fieldsets %}
        {% if fieldset.name != "Test Expression" %}
            {% render_fieldset form fieldset %}
        {% else %}
            {# Custom rendering for Test Expression fieldset with button #}
            <div class="bg-info-subtle border border-info rounded-1 pt-3 px-3 mb-3">
                <div class="field-group mb-3">
                    <div class="row">
                        <h2 class="col-9 offset-3">
                            {% trans "Test Expression" %}
                        </h2>
                        <p class="text-muted small mb-3  offset-3">
                                Test this filter expression against a live IP Fabric source to verify it returns the expected results.
                            </p>
                    </div>



                    {# Render the fields in this fieldset (test_source and test_endpoint) #}
                    {% render_field form.test_source %}
                    {% render_field form.test_endpoint %}
                </div>

                {# Test button section #}
                <div class="mb-3">
                    <div class="row">
                        <div class="col-9 offset-3">
                            <button type="button"
                                    id="test-expression-btn"
                                    class="btn btn-primary"
                                    onclick="testExpression('{{ object.pk|default:"" }}', '{{ csrf_token }}')">
                                 {% trans "Test Expression" %}
                            </button>

                            <div id="test-result" class="mt-3"></div>
                        </div>
                    </div>
                </div>
            </div>
        {% endif %}
    {% endfor %}

    {# Custom fields #}
    {% if form.custom_fields %}
        <div class="field-group mb-5">
            <div class="row">
                <h2 class="col-9 offset-3">{% trans "Custom Fields" %}</h2>
            </div>
            {% render_custom_fields form %}
        </div>
    {% endif %}

    {# Comments #}
    {% if form.comments %}
        <div class="field-group mb-5">
            {% render_field form.comments %}
        </div>
    {% endif %}

    {# Changelog message #}
    {% if form.changelog_message %}
        <div class="bg-primary-subtle border border-primary rounded-1 pt-3 px-3 mb-3">
            {% render_field form.changelog_message %}
        </div>
    {% endif %}

    {# Load JavaScript for AJAX testing - inlined to ensure it's always available #}
    <script>
    /**
     * Test filter expression against IP Fabric API
     */
    function testExpression(pk, csrfToken) {
        const btn = document.getElementById('test-expression-btn');
        const result = document.getElementById('test-result');
        const testSource = document.getElementById('id_test_source')?.value;
        const testEndpoint = document.getElementById('id_test_endpoint')?.value;
        const expression = document.getElementById('id_expression')?.value;

        // Clear any previous result message
        result.innerHTML = '';

        // Validate required fields
        if (!testSource) {
            result.innerHTML = '<div class="alert alert-warning"><strong>Required:</strong> Please select a Test Source.</div>';
            return;
        }

        if (!testEndpoint) {
            result.innerHTML = '<div class="alert alert-warning"><strong>Required:</strong> Please select a Test Endpoint.</div>';
            return;
        }

        if (!expression) {
            result.innerHTML = '<div class="alert alert-warning"><strong>Required:</strong> Please enter an expression to test.</div>';
            return;
        }

        // Show loading
        btn.disabled = true;
        btn.innerHTML = '<i class="mdi mdi-loading mdi-spin"></i> Testing...';

        // Use the same endpoint logic for both saved and unsaved expressions
        const url = pk
            ? `/plugins/ipfabric/filter-expression/${pk}/test/`
            : `/plugins/ipfabric/filter-expression/test/`;

        // Make AJAX request
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRFToken': csrfToken
            },
            body: new URLSearchParams({
                test_source: testSource,
                test_endpoint: testEndpoint,
                expression: expression
            })
        })
        .then(response => response.json())
        .then(data => {
            btn.disabled = false;
            btn.innerHTML = '<i class="mdi mdi-test-tube"></i> {% trans "Test Expression" %}';

            if (data.success) {
                result.innerHTML = `<div class="alert alert-success"><strong>Success!</strong> ${data.message}</div>`;
            } else {
                result.innerHTML = `<div class="alert alert-danger"><strong>Error:</strong> ${data.error}</div>`;
            }
        })
        .catch(error => {
            btn.disabled = false;
            btn.innerHTML = '<i class="mdi mdi-test-tube"></i> {% trans "Test Expression" %}';
            result.innerHTML = `<div class="alert alert-danger"><strong>Error:</strong> ${error.message}</div>`;
        });
    }
    </script>
{% endblock form %}
