{% load crispy_forms_tags %}
{% load crispy_forms_field %}
{% load bloomerp %}
{% load static %}

{% breadcrumb title='Query builder' model=model %}

<div class="card text-start">
    <div class="card-body">
        <h4 class="card-title">Query builder</h4>
        
        <div class="d-flex mb-2 gap-3">
            <!-- Database icon -->
            <a
                class="pointer"
                onclick="document.getElementById('tablesSearchContainer').classList.toggle('fade'); document.getElementById('tablesSearchContainer').classList.toggle('d-none')"
            >
                <img src="{% static 'bloomerp/icons/database.svg' %}" alt="SQL" width=20 height=20>
            </a>
            <!-- End database icon -->

            <!--Magic icon-->
            <a
                class="pointer"
                data-bs-toggle="modal"
                data-bs-target="#sqlQueryGenerateModal"
            >
                <img src="{% static 'bloomerp/icons/magic-stick.svg' %}" alt="Magic" width=20 height=20>
            </a>
        </div>

        <div
            class="row justify-content-between align-items-start g-2"
        >
            <div class="col">
                <!-- Query editor -->
                <div id="editor" style="height:300px" class="border">{% if object %}{{ object.query }}{% else %}SELECT * FROM table_name;{% endif %}</div>
                <!-- End query editor -->
            </div>
            
            <!-- Database tables search -->
            <div 
                class="col-6 overflow-auto fade d-none"
                id = "tablesSearchContainer"
                >
                
                <input
                    class="form-control form-control-sm"
                    type="text"
                    id="search"
                    placeholder="Search database tables"
                    oninput="filterTables()"
                    >

                <div id="tablesContainer">
                    {% for table in db_tables_and_columns %}
                        <div class="table-item">
                            <a
                                class="pointer"
                                type="button"
                                id="{{ table.0 }}"
                                onclick="document.getElementById('{{ table.0 }}_fields').classList.toggle('d-none')"
                            >
                                {{ table.0 }}
                            </a>
                            <div class="d-none pl-2" id="{{table.0}}_fields">
                                <ul>
                                    {% for field in table.1 %}
                                        <li onclick="addFieldToEditor('{{field.0}}')">{{ field.0 }}</li>
                                    {% endfor %}
                                </ul>
                            </div>
                        </div>
                    {% endfor %}
                </div>
            </div>
            <!-- End database tables search -->
        </div>
        
        <div class="gap-2 d-flex justify-content-center my-2">
            <!-- Run query button -->
            <form 
                id="queryForm"
                hx-get="{% url "components_execute_sql_query" %}" 
                hx-trigger="click" 
                hx-target="#queryOutput"
                >
                <input type="hidden" id="sql_query_value" name="sql_query">
                <button 
                    class="btn btn-primary" 
                    href="#queryOutput"
                    type="submit"
                    >Run query
                </button>
            </form>  
            <!-- End run query button -->  
            
            <button
                type="button"
                class="btn btn-secondary"
                data-bs-toggle="modal"
                data-bs-target="#saveQueryModal"
            >
                Save query
            </button>
        </div>   

        <!-- Query output -->
        <div id="queryOutput" class="overflow-auto"></div>
        
    </div>
</div>

<!-- Save query modal -->
<div
    class="modal fade"
    id="saveQueryModal"
    tabindex="-1"
    data-bs-backdrop="static"
    data-bs-keyboard="false"

    role="dialog"
    aria-labelledby="modalTitleId"
    aria-hidden="true"
    >
    <div
        class="modal-dialog modal-dialog-centered modal-md"
        role="document"
    >
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitleId">
                    Save Query
                </h5>
                <button
                    type="button"
                    class="btn-close"
                    data-bs-dismiss="modal"
                    aria-label="Close"
                ></button>
            </div>
            <form 
                hx-post=""
                hx-target="#main-content"
                hx-swap="innerHTML"
                hx-push-url="true"
            >
                {% csrf_token %}
                <div class="modal-body">
                    {{form.name | as_crispy_field}}
                    <input type="hidden" id="form_sql_query_value" name="query" value="">
                </div>
                <div class="modal-footer">
                    <button
                        type="button"
                        class="btn btn-secondary"
                        data-bs-dismiss="modal"
                    >
                        Close
                    </button>
                    <button type="submit" data-bs-dismiss="modal" class="btn btn-primary">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>
<!-- End Save query modal -->

<!-- Magic modal -->
{% include 'snippets/llm_modal_snippet.html' with modal_id='sqlQueryGenerateModal' title='Generate SQL query' target="#llm_output" query_type="sql" %}
<textarea class="d-none" id="llm_output"></textarea>
<!-- End Magic modal -->

<script>
    // Initialize the Ace editor
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/chrome");
    editor.session.setMode("ace/mode/sql");
    
    editor.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: false,
        fontSize: "16px"

    });


    // Update the hidden input field whenever the editor content changes
    editor.session.on('change', function(delta) {
        document.getElementById('sql_query_value').setAttribute('value', editor.getValue());
        document.getElementById('form_sql_query_value').setAttribute('value', editor.getValue());
    });

    // Filter tables based on search input and limit to 10 tables
    function filterTables() {
        var input, filter, container, items, a, i, txtValue;
        input = document.getElementById('search');
        filter = input.value.toUpperCase();
        container = document.getElementById('tablesContainer');
        items = container.getElementsByClassName('table-item');
        var count = 0;

        for (i = 0; i < items.length; i++) {
            a = items[i].getElementsByTagName("a")[0];
            txtValue = a.textContent || a.innerText;
            if (txtValue.toUpperCase().indexOf(filter) > -1 && count < 10) {
                items[i].style.display = "";
                count++;
            } else {
                items[i].style.display = "none";
            }
        }
    }

    // Initially display only 10 items
    document.addEventListener('DOMContentLoaded', function() {
        filterTables();
    });

    // Listen to change of LLM output
    document.addEventListener('htmx:afterSwap', function(event) {
        if (event.detail.target.id == 'llm_output') {
            editor.setValue(document.getElementById('llm_output').value);
        }
    });

    // Add the selected table and field to the editor
    function addFieldToEditor(field) {
        editor.insert(field);
    }

</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js" type="text/javascript" charset="utf-8"></script>

