{% extends 'base/layout.html' %}
{% load form_helpers %}

{% block title %}Generate — {{ object.name }}{% endblock %}

{% block content %}
<nav aria-label="breadcrumb" class="mb-3">
    <ol class="breadcrumb">
        <li class="breadcrumb-item">
            <a href="{% url 'plugins:netbox_atlassian:template_list' %}">Document Library</a>
        </li>
        <li class="breadcrumb-item">
            <a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
        </li>
        <li class="breadcrumb-item active">Generate</li>
    </ol>
</nav>

<div class="row">
    <!-- Left: form -->
    <div class="col-md-4">
        <div class="card mb-3">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="mdi mdi-file-document-outline text-primary"></i>
                    {{ object.name }}
                </h5>
            </div>
            <div class="card-body">
                {% if object.description %}
                <p class="text-muted small">{{ object.description }}</p>
                {% endif %}

                <form method="post" id="generate-form">
                    {% csrf_token %}
                    {% render_field form.tag %}
                    {% render_field form.devices %}
                    {% render_field form.virtual_machines %}
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Extra Variables</label>
                        {{ form.extra_vars }}
                        <div class="form-text">
                            One per line: <code>key=value</code><br>
                            e.g. <code>change_request=ITSUP-1234</code>
                        </div>
                    </div>
                    <button type="submit" name="action" value="generate" class="btn btn-primary w-100">
                        <i class="mdi mdi-play"></i> Generate Document
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- Right: output -->
    <div class="col-md-8">
        {% if error %}
        <div class="alert alert-danger">
            <i class="mdi mdi-alert-circle"></i>
            <strong>Template error:</strong> {{ error }}
        </div>
        {% endif %}

        {% if confluence_url %}
        <div class="alert alert-success">
            <i class="mdi mdi-check-circle"></i>
            Page created in Confluence:
            <a href="{{ confluence_url }}" target="_blank" rel="noopener">{{ confluence_url }}</a>
        </div>
        {% endif %}

        {% if rendered %}
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">
                    <i class="mdi mdi-text-box-check-outline text-success"></i> Generated Output
                </h5>
                <button type="button" class="btn btn-sm btn-outline-secondary" id="copy-btn"
                        onclick="copyOutput()">
                    <i class="mdi mdi-content-copy"></i> Copy to Clipboard
                </button>
            </div>
            <div class="card-body p-0">
                <textarea id="output-text" class="form-control font-monospace border-0 rounded-0"
                          rows="30" readonly
                          style="resize:vertical; font-size:0.8rem;">{{ rendered }}</textarea>
            </div>
            {% if object.confluence_parent_page_id %}
            <div class="card-footer">
                <form method="post" id="confluence-form" class="d-flex gap-2 align-items-end">
                    {% csrf_token %}
                    <div class="flex-grow-1">
                        <label class="form-label small mb-1">Page Title</label>
                        <input type="text" name="confluence_title" class="form-control form-control-sm"
                               value="{{ confluence_title|default:'' }}"
                               placeholder="Enter a title for the Confluence page" required>
                    </div>
                    <button type="submit" name="action" value="post_to_confluence" class="btn btn-sm btn-primary text-nowrap">
                        <i class="mdi mdi-cloud-upload-outline"></i> Post to Confluence
                    </button>
                </form>
            </div>
            {% endif %}
        </div>
        {% else %}
        <div class="card">
            <div class="card-body text-center text-muted py-5">
                <i class="mdi mdi-text-box-outline" style="font-size:3rem;"></i>
                <p class="mt-2">Select devices and click <strong>Generate Document</strong> to see output here.</p>
            </div>
        </div>
        {% endif %}
    </div>
</div>

<script>
function copyOutput() {
    const textarea = document.getElementById('output-text');
    textarea.select();
    textarea.setSelectionRange(0, textarea.value.length);
    navigator.clipboard.writeText(textarea.value).then(function() {
        const btn = document.getElementById('copy-btn');
        const original = btn.innerHTML;
        btn.innerHTML = '<i class="mdi mdi-check"></i> Copied!';
        btn.classList.remove('btn-outline-secondary');
        btn.classList.add('btn-success');
        setTimeout(function() {
            btn.innerHTML = original;
            btn.classList.remove('btn-success');
            btn.classList.add('btn-outline-secondary');
        }, 2000);
    });
}

/**
 * Copy generate form values into the Confluence post form before submit.
 */
var cfForm = document.getElementById('confluence-form');
if (cfForm) {
    cfForm.addEventListener('submit', function() {
        // Remove any previously-copied hidden fields
        cfForm.querySelectorAll('input.copied-field').forEach(function(el) { el.remove(); });
        // Copy all values from the generate form
        var genForm = document.getElementById('generate-form');
        var formData = new FormData(genForm);
        for (var pair of formData.entries()) {
            var hidden = document.createElement('input');
            hidden.type = 'hidden';
            hidden.name = pair[0];
            hidden.value = pair[1];
            hidden.className = 'copied-field';
            cfForm.appendChild(hidden);
        }
    });
}

/**
 * Auto-fill devices/VMs when a tag is selected.
 * Watches the tag TomSelect for changes, fetches all matching objects
 * from the NetBox API, and adds them to the devices/VMs TomSelect instances.
 */
document.addEventListener('DOMContentLoaded', function() {
    // Wait for TomSelect to initialize on the widgets
    setTimeout(function() {
        const tagSelect = document.getElementById('id_tag');
        const deviceSelect = document.getElementById('id_devices');
        const vmSelect = document.getElementById('id_virtual_machines');

        if (!tagSelect || !tagSelect.tomselect) return;

        const tagTS = tagSelect.tomselect;
        const deviceTS = deviceSelect ? deviceSelect.tomselect : null;
        const vmTS = vmSelect ? vmSelect.tomselect : null;

        tagTS.on('change', function() {
            const tagIds = tagTS.getValue();
            if (!tagIds || (Array.isArray(tagIds) && tagIds.length === 0) || tagIds === '') return;

            const tagIdParam = Array.isArray(tagIds) ? tagIds.join('&tag_id=') : tagIds;

            // Fetch devices matching the tag(s)
            if (deviceTS) {
                fetch(`/api/dcim/devices/?tag_id=${tagIdParam}&limit=500&brief=true`)
                    .then(r => r.json())
                    .then(data => {
                        (data.results || []).forEach(function(dev) {
                            // Add option if not already present, then select it
                            if (!deviceTS.options[dev.id]) {
                                deviceTS.addOption({value: dev.id, text: dev.display || dev.name});
                            }
                            deviceTS.addItem(dev.id, true);
                        });
                    });
            }

            // Fetch VMs matching the tag(s)
            if (vmTS) {
                fetch(`/api/virtualization/virtual-machines/?tag_id=${tagIdParam}&limit=500&brief=true`)
                    .then(r => r.json())
                    .then(data => {
                        (data.results || []).forEach(function(vm) {
                            if (!vmTS.options[vm.id]) {
                                vmTS.addOption({value: vm.id, text: vm.display || vm.name});
                            }
                            vmTS.addItem(vm.id, true);
                        });
                    });
            }
        });
    }, 500);
});
</script>
{% endblock %}
