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

<h4 class="card-title">Query builder</h4>


{% if form.errors %}

{{form.errors}}

{% endif %}


<div class="d-flex mb-2 gap-3">
    <!-- Database icon -->
    <a
        class="pointer"
        data-bs-toggle="collapse"
        data-bs-target="#tablesSearchContainer"
    >
        <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="#modal_sql_query_ai"
    >
        <img src="{% static 'bloomerp/icons/magic-stick.svg' %}" alt="Magic" width=20 height=20>
    </a>
    <!--End magic icon-->


</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 collapse collapse-horizontal"
        id = "tablesSearchContainer"
        style="height:300px"
        >
        
        <input
            class="form-control form-control-sm my-1"
            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 dropdown-toggle mb-2"
                        type="button"
                        id="{{ table.0 }}"
                        onclick="document.getElementById('{{ table.0 }}_fields').classList.toggle('d-none')"
                    >
                        <span><i class="bi bi-table mx-2"></i></span> {{ table.0 }}
                    </a>
                    <div class="d-none pl-2" id="{{table.0}}_fields">
                        <ul style="list-style-type: none;">
                            <li 
                                    onclick="addFieldToEditor('{{ table.0 }}')"
                                    class="pointer mb-2"
                                    >
                                    <b>{{ table.0 }} (table)</b>
                                    
                                    <img src="{% static 'bloomerp/icons/insert-content.svg' %}" alt="Select" class="pointer" width=14 height=14>
                            </li>


                            {% for field in table.1 %}
                                <li 
                                    onclick="addFieldToEditor('{{field.0}}')"
                                    class="pointer mb-2"
                                    >
                                    {{ field.0 }} <span>({{ field.1}})</span>
                                    
                                    <img src="{% static 'bloomerp/icons/insert-content.svg' %}" alt="Select" class="pointer" width=14 height=14>
                                </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" value="{{ object.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>


<!-- 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 id='sql_query_ai' title='Generate SQL query' target="llm_output" query_type="sql" %}
<!-- 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";
            }
        }
    }

    


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

    // Add the generated query to the editor
    document.getElementById('llm_output_sql_query_ai').addEventListener('llm-inserted', function(e) {
        editor.setValue(e.target.innerHTML)
    });

</script>
