{% extends "layouts/base.html" %}
{% from 'helpers/_forms.html' import render_field %}

{% block title %} New Stacks {% endblock %}

<!-- Specific Page CSS goes HERE  -->
{% block stylesheets %}{% endblock stylesheets %}
{% block content %}
<main class="content">

    {% include 'includes/navigation.html' %}
    <div class="preloader bg-soft flex-column justify-content-center align-items-center">
        <img class="loader-element animate__animated animate__jackInTheBox" src="/static/assets/img/brand/light.svg" height="90" alt="Volt logo">
    </div>

    <div class="py-4">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb breadcrumb-dark breadcrumb-transparent">
                <li class="breadcrumb-item"><a href="#"><span class="fas fa-home"></span></a></li>
                <li class="breadcrumb-item"><a href="/stacks-list">Stacks</a></li>
                <li class="breadcrumb-item active" aria-current="page">New</li>
            </ol>
        </nav>
        <div class="d-flex justify-content-between w-100 flex-wrap">
            <div class="mb-3 mb-lg-0">
                <h1 class="h4">Add New Stack</h1>
                <p class="mb-0">Add reusable stacks or modules built to provide easy way to deployment infra</p>
            </div>
            <div>
                <a href="" class="btn btn-outline-gray"><i class="far fa-question-circle mr-1"></i> Stack Docs</a>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12 mb-4">
            <div class="card border-light shadow-sm components-section">
                <div class="card-body">
                    <div class="row mb-4">
                        <div class="col-lg-4 col-sm-6">
                            <!-- Form -->
                            <div class="col-md-12 col-md-offset-1">
                                <form class="" id="stackForm" method="post" onsubmit="return checkForm(this);">
                                    <div class="form-group">
                                        {{ render_field(form.name, autocomplete="off", class='form-control', placeholder='Stack name') }}
                                    </div>

                                    <div class="form-group">
                                        {{ render_field(form.git, autocomplete="off", class='form-control', placeholder='Git repo') }}
                                    </div>

                                    <div class="form-group">
                                        {{ render_field(form.branch, autocomplete="off", class='form-control', placeholder='Set git ref tag version or branch') }}
                                    </div>

                                    <div class="form-group">
                                        {{ render_field(form.squad_access, autocomplete="off", class='form-control') }}
                                    </div>
                                    <div class="form-group">
                                        {{ render_field(form.iac_type, id='iacTypeSelector', class='form-control') }}
                                    </div>

                                    <div class="form-group">
                                        {{ render_field(form.tf_version, id='versionSelector', class='form-control') }}
                                    </div>
                                    <div class="form-group">
                                        {{ render_field(form.project_path, autocomplete="off", class='form-control', 
                                           placeholder='Only complete if you use monorepo') }}
                                    </div>

                                    <div class="form-group">
                                        {{ render_field(form.description, autocomplete="off", class='form-control', placeholder='Description') }}
                                    </div>
                                    <div class="form-group">
                                    
                                        <label for="iconSelector">Choose an Icon:</label>
                                        <select id="iconSelector" name="icon_path" class="form-control" onchange="previewIcon()">
                                            <!-- JavaScript will populate this -->
                                        </select>
                                        <div id="iconPreview" class="mt-2">
                                            <!-- Icon preview will be displayed here -->
                                        </div>
                                    </div>

                                    <input class="btn btn-primary" type="submit" name="stackButton" value="Create Stack">
                                </form>
                                <!-- End Form -->

                                <div class="input-group">
                                </div>
                            </div>
                        </div>
                    </div>

                    {% include 'includes/footer.html' %}

</main>

{% endblock content %}

<!-- Specific Page JS goes HERE  -->
{% block javascripts %}
<script type="text/javascript">

    function checkForm(form) // Submit button clicked
{

    form.stackButton.disabled = true;
    form.stackButton.value = "Please wait...";
    return true;
}

</script>

<script type="text/javascript">
    // Populate the icon selector and implement preview functionality
    document.addEventListener('DOMContentLoaded', function () {
        var iconsBasePath = '/static/assets/img/gallery/';
        var iconsData = {{ icons | safe }};
        var selector = document.getElementById('iconSelector');
        var preview = document.getElementById('iconPreview');

        // Populate the dropdown with icons
        for (var category in iconsData) {
            if (iconsData.hasOwnProperty(category)) {
                iconsData[category].forEach(function(iconFilename) {
                    var fullPath = iconsBasePath + category + '/' + iconFilename;
                    var option = document.createElement('option');
                    option.value = fullPath;
                    option.text = category + '/' + iconFilename; // Displaying category/filename
                    selector.appendChild(option);
                });
            }
        }

        // Preview selected icon
        window.previewIcon = function() {
            var selectedIcon = selector.value;
            preview.innerHTML = '<img src="' + selectedIcon + '" alt="Icon Preview" style="max-width:100px;"/>'; // Adjust size as needed
        };
    });
</script>

<script type="text/javascript">
    // Función para obtener las versiones de los releases de GitHub
    function fetchReleaseVersions(repoUrl) {
        return fetch(repoUrl)
            .then(response => response.json())
            .then(data => data.map(release => release.tag_name));
    }

    // Actualiza las opciones de versión de IaC basadas en el tipo de IaC seleccionado
    function updateVersionOptions(iacType) {
        let repoUrl;
        switch(iacType) {
            case 'terraform':
                repoUrl = 'https://api.github.com/repos/hashicorp/terraform/releases';
                break;
            case 'terragrunt':
                repoUrl = 'https://api.github.com/repos/gruntwork-io/terragrunt/releases';
                break;
            case 'tofu':
                repoUrl = 'https://api.github.com/repos/opentofu/opentofu/releases';
                break;
            default:
                return;
        }

        fetchReleaseVersions(repoUrl).then(versions => {
            const versionSelector = document.getElementById('versionSelector'); // Asegúrate de tener este ID en tu selector de versiones
            versionSelector.innerHTML = ''; // Limpia las opciones existentes

            versions.forEach(version => {
                const option = document.createElement('option');
                option.value = version;
                option.text = version;
                versionSelector.appendChild(option);
            });
        });
    }

    // Evento al cargar el documento
    document.addEventListener('DOMContentLoaded', function () {
        // Agrega un listener al selector de IaC Type
        const iacTypeSelector = document.getElementById('iacTypeSelector'); // Asegúrate de tener este ID en tu selector de IaC Type
        iacTypeSelector.addEventListener('change', function() {
            updateVersionOptions(this.value);
        });

        // ... código existente para la selección de iconos ...
    });
</script>

{% endblock javascripts %}
