{% extends 'base.html' %}
{% block title %}IvoryOS | Design{% endblock %}

{% block body %}
    {# overlay block for text-to-code gen #}
    <div id="overlay" class="overlay">
        <div>
            <h3 id="overlay-text">Generating design, please wait...</h3>
            <div class="spinner-border" role="status"></div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-3 scroll-column" >

            {# select deck if this is online#}
            {% if off_line %}
                <form id="select-deck" method="POST" action="{{ url_for('design.import_pseudo') }}" enctype="multipart/form-data">
                    <div class="input-group mb-3">
{#                        <label for="pkl_name" class="form-label">Choose/Change deck:</label>#}
                        <select class="form-select" name="pkl_name" id="pkl_name" required onchange="document.getElementById('select-deck').submit();">
                            <option {{ '' if 'pseudo_deck' in session else 'selected' }} disabled hidden style="overflow-wrap: break-word;" name="pkl_name" id="pkl_name" value=""> -- choose deck --</option>
                            {% for connection in history %}
                                <option {{ 'selected' if session['pseudo_deck']==connection else '' }} style="overflow-wrap: break-word;" name="pkl_name" id="pkl_name" value="{{connection}}">{{connection.split('.')[0]}}</option>
                            {% endfor %}
                        </select>
                    </div>
                </form>
                <hr>
            {% endif %}

            {# edit action #}
            {% if session["edit_action"] %}
                {% with action = session["edit_action"] %}
                    <h5> {{ format_name(action['action']) }} </h5>
                    <form role="form" method='POST' name="{{instrument}}" action="{{ url_for('design.edit_action', uuid=session["edit_action"]['uuid']) }}">
                        {% if not action['args'] == None %}
                        <div class="form-group">
                            {% if not action['args'].__class__.__name__ == 'dict' %}
                                <div class="input-group mb-3">
                                    <label class="input-group-text">{{ action['action'] }}</label>
                                    <input class="form-control" type="text" id="arg" name="arg" placeholder="{{ action['arg_types']}}" value="{{ action['args'] }}" aria-labelledby="variableHelpBlock">
                                </div>
                            {% else %}
{#                                {% for arg in action['args'] %}#}
{#                                <div class="input-group mb-3">#}
{#                                    <label class="input-group-text">{{ format_name(arg) }}</label>#}
{#                                    <input class="form-control" type="text" id="{{ arg }}" name="{{ arg }}" placeholder="{{ action['arg_types'][arg] }}" value="{{ action['args'][arg] }}" aria-labelledby="variableHelpBlock">#}
{#                                </div>#}
{#                                {% endfor %}#}
{#                                <div class="input-group mb-3">#}
{#                                    <label class="input-group-text">Save Output?</label>#}
{#                                    <input class="form-control" type="text" id="return" name="return"  value="{{ action['return'] }}" aria-labelledby="variableHelpBlock">#}
{#                                </div>#}
                                {{ forms.hidden_tag() }}
                                {% for field in forms %}
                                    {% if field.type not in ['CSRFTokenField'] %}
                                        <div class="input-group mb-3">
                                            <label class="input-group-text">{{ field.label.text }}</label>
                                            {{ field(class="form-control") }}
                                            <div class="form-text">{{ field.description }} </div>
                                        </div>
                                    {% endif %}
                                {% endfor %}
                            {% endif %}
                        </div>
                        {% endif %}
                        <button class="btn btn-primary" type="submit">Save</button>
                        <button class="btn btn-primary" type="submit" name="back" id="back" value="back">Back</button>
                    </form>
                {% endwith %}


            {% elif instrument %}
                <div>
                    <div class="d-flex justify-content-between align-items-center " style="margin-bottom: 1vh;margin-top: 1vh;">
                        <a class="btn btn-primary" role="button" type="button" href="{{url_for('design.experiment_builder')}}"><i class="bi bi-arrow-return-left"></i></a>
                        {{ format_name(instrument) }}
                    </div>

                    {% if script.editing_type == "script" %}
                        {# Auto Fill Toggle #}
                        <div class="d-flex justify-content-between align-items-center " style="margin-bottom: 1vh;margin-top: 1vh;">
                            <div></div>
                            <form role="form" method='POST' name="autoFill" id="autoFill">
                                <div class="form-check form-switch">
                                    <input type="hidden" id="autofill" name="autofill" value="temp_value">
                                    <input class="form-check-input" type="checkbox" id="autoFillCheck" name="autoFillCheck" onchange="document.getElementById('autoFill').submit();"
                                           value="temp_value"
                                            {{ "checked" if session["autofill"] else "" }}>
                                    <label class="form-check-label" for="autoFillCheck">Auto fill</label>
                                </div>
                                <button type="submit" class="btn btn-default" style="display: none;">Auto fill </button>
                            </form>
                        </div>
                    {% endif %}

                        {# according for instrument #}
                        <div class="accordion accordion-flush" id="accordionActions" >
                            {% if use_llm and not instrument == "flow_control" %}
                                <div class="accordion-item text-to-code">
                                <h2 class="accordion-header">
                                    <button class="accordion-button text-to-code" type="button" data-bs-toggle="collapse" data-bs-target="#text-to-code" aria-expanded="false" aria-controls="collapseExample">
                                        Text-to-Code
                                    </button>
                                </h2>
                                <div id="text-to-code" class="accordion-collapse collapse show" data-bs-parent="#accordionActions">
                                    <div class="accordion-body">
                                        <form role="form" method='POST' name="generate" id="generate" action="{{url_for('design.generate_code')}}">
                                            <input type="hidden" id="instrument" name="instrument" value="{{instrument}}">
                                            <textarea class="form-control" id="prompt" name="prompt" rows="6" aria-describedby="promptHelpBlock">{{ session['prompt'][instrument] if instrument in session['prompt'] else '' }}</textarea>
                                            <div id="promptHelpBlock" class="form-text">
                                                This will overwrite current design.
                                            </div>
<!--                                               <button type="submit" class="btn btn-dark" id="clear" name="clear" onclick="submitForm('generate')">Clear</button>-->
                                            <button type="submit" class="btn btn-dark" id="gen" name="gen">Generate</button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            {% endif %}

                            {% for name, form in forms.items() %}
                                <div class="accordion-item design-control" draggable="true">
                                    <h2 class="accordion-header">
                                        <button class="accordion-button collapsed draggable-action"
                                                type="button" data-bs-toggle="collapse"
                                                data-bs-target="#{{name}}" aria-expanded="false"
                                                aria-controls="collapseExample"
                                                 data-action="{{ name }}">
                                            {{ format_name(name) }}
                                        </button>
                                    </h2>
                                    <div id="{{name}}" class="accordion-collapse collapse" data-bs-parent="#accordionActions">
                                        <div class="accordion-body">
                                            <form role="form" method='POST' name="add" id="add-{{name}}">
                                                <div class="form-group">
                                                    {{ form.hidden_tag() }}
                                                    {% for field in form %}
                                                        {% if field.type not in ['CSRFTokenField', 'HiddenField'] %}
                                                            <div class="input-group mb-3">
                                                                <label class="input-group-text">{{ field.label.text }}</label>
                                                                {% if field.type == "SubmitField" %}
                                                                    {{ field(class="btn btn-dark") }}
                                                                {% elif field.type == "BooleanField" %}
                                                                    {{ field(class="form-check-input") }}
                                                                {% elif field.type == "FlexibleEnumField" %}
                                                                   <input type="text" id="{{ field.id }}" name="{{ field.name }}" value="{{ field.data }}"
                                                                      list="{{ field.id }}_options" placeholder="{{ field.render_kw.placeholder if field.render_kw and field.render_kw.placeholder }}"
                                                                      class="form-control">
                                                                   <datalist id="{{ field.id }}_options">
                                                                      {% for key in field.choices %}
                                                                         <option value="{{ key }}">{{ key }}</option>
                                                                      {% endfor %}
                                                                   </datalist>

                                                                {% else %}
                                                                    {{ field(class="form-control") }}
                                                                {% endif %}
                                                            </div>
                                                        {% endif %}
                                                    {% endfor %}
                                                </div>
                                                <button type="submit" class="btn btn-dark">Add</button>
                                                {% if 'hidden_name' in form %}
                                                    <i class="bi bi-info-circle ms-2" data-bs-toggle="tooltip" data-bs-placement="top"
                                                       title='{{ form.hidden_name.description or "Docstring is not available" }}'>
                                                    </i>
                                                {% else %}
                                                    <!-- handle info tooltip for flow control / workflows -->
                                                {% endif %}

                                            </form>
                                        </div>
                                    </div>
                                </div>
                            {% endfor %}
                        </div>
                </div>


            {# according for all actions #}
            {% else %}
                <div style="margin-bottom: 4vh;"></div>
                <div class="accordion accordion-flush">

                    <div class="accordion-item design-control">
                        <h5 class="accordion-header">
                            <button class="accordion-button" data-bs-toggle="collapse" data-bs-target="#deck" role="button" aria-expanded="false" aria-controls="collapseExample">
                                Operations
                            </button>
                        </h5>
                        <div class="accordion-collapse collapse show" id="deck">
                            <ul class="list-group">
                                {% for instrument in defined_variables %}
                                    <form role="form" method='GET' name="{{instrument}}" action="{{url_for('design.experiment_builder',instrument=instrument)}}">
                                        <div>
                                            <button class="list-group-item list-group-item-action" type="submit">{{format_name(instrument)}}</button>
                                        </div>
                                    </form>
                                {% endfor %}
                            </ul>
                        </div>
                    </div>

                    {% if local_variables %}
                        <div class="accordion-item  design-control">
                            <h5 class="accordion-header">
                                <button class="accordion-button" data-bs-toggle="collapse" data-bs-target="#local" role="button" aria-expanded="false" aria-controls="collapseExample">
                                    Local Operations
                                </button>
                            </h5>
                            <div class="accordion-collapse collapse show" id="local">
                                <ul class="list-group">
                                    {% for instrument in local_variables %}
                                        <form role="form" method='GET' name="{{instrument}}" action="{{url_for('design.experiment_builder',instrument=instrument)}}">
                                            <div>
                                                <button class="list-group-item list-group-item-action" type="submit"  name="device" value="{{instrument}}" >{{instrument}}</button>
                                            </div>
                                        </form>
                                    {% endfor%}
                                </ul>
                            </div>
                        </div>
                    {% endif %}
                </div>
            {% endif %}
        </div>

        {# canvas #}
        <div class="col-md-9 scroll-column">
            <div class="d-flex align-items-center ">
{#                file dropdown menu    #}
                <ul class="nav nav-tabs">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">File tools <i class="bi bi-tools"></i></a>
                        <ul class="dropdown-menu">
                            <button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#newScriptModal">New</button>
                            <button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#jsonModal">Import (.json <i class="bi bi-filetype-json"></i>)</button>
                            <button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#renameModal">Rename</button>
                            <a role="button" class="dropdown-item {{'disabled' if not script.name or script.status == 'finalized'}}" type="button" href="{{url_for('database.publish')}}">Save</a></li>
                            <button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#saveasModal">Save as</button>
                            {% if not script.status == 'finalized' %}
                                <a role="button" class="dropdown-item" type="button" href="{{url_for('database.finalize')}}">Disable editing</a>
                            {% endif %}
                            <a  class="dropdown-item" role="button" type="button" href="{{url_for('design.download', filetype='script')}}">Export (.json <i class="bi bi-filetype-json"></i>)</a>
                        </ul>
                    </li>

                    <li class="nav-item"><a class="nav-link" aria-current="page" data-bs-toggle="collapse" href="#info">Info</a></li>
                    <li class="nav-item"><a class="{{'nav-link active' if script.editing_type=='prep' else 'nav-link'}}" aria-current="page" href="{{url_for('design.toggle_script_type', stype='prep') }}">Prep</a></li>
                    <li class="nav-item"><a class="{{'nav-link active' if script.editing_type=='script' else 'nav-link'}}" aria-current="page" href="{{url_for('design.toggle_script_type', stype='script') }}">Experiment</a></li>
                    <li class="nav-item"><a class="{{'nav-link active' if script.editing_type=='cleanup' else 'nav-link'}}" aria-current="page" href="{{url_for('design.toggle_script_type', stype='cleanup') }}">Clean up</a></li>
                </ul>

                <div class="form-check form-switch ms-auto">
                    <input class="form-check-input" type="checkbox" id="toggleLineNumbers" onchange="toggleLineNumbers()">
                    <label class="form-check-label" for="toggleLineNumbers">Show Line Numbers</label>
                </div>

            </div>

            <div class="canvas" droppable="true">
                <div class="collapse" id="info">
                    <table class="table script-table">
                        <tbody>
                            <tr><th scope="row">Deck Name</th><td>{{script.deck}}</td></tr>
                            <tr><th scope="row">Script Name</th><td>{{ script.name }}</td></tr>
                            <tr>
                                <th scope="row">Editing status <a role="button" data-bs-toggle="popover" data-bs-title="How to use:" data-bs-content="You can choose to disable editing, so the script is finalized and cannot be edited. Use save as to rename the script"><i class="bi bi-info-circle"></i></a></th>
                                <td>{{script.status}}</td>
                            </tr>
                            <tr>
                                <th scope="row">Output Values <a role="button" data-bs-toggle="popover" data-bs-title="How to use:" data-bs-content="This will be your output data. If the return data is not a value, it will save as None is the result file"><i class="bi bi-info-circle"></i></a></th>
                                <td>
                                    {% for i in script.config_return()[1] %}
                                        <input type="checkbox">{{i}}
                                    {% endfor %}
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">Config Variables <a role="button" data-bs-toggle="popover" data-bs-title="How to use:" data-bs-content="This shows variables you want to configure later using .csv file"><i class="bi bi-info-circle"></i></a></th>
                                <td>
                                    <ul>
                                        {% for i in script.config("script")[0] %}
                                            <li>{{i}}</li>
                                        {% endfor %}
                                    </ul>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="list-group" id="list" style="margin-top: 20px">
                    <ul class="reorder">
                    {% for button in buttons %}
                        <li id="{{ button['id'] }}" style="list-style-type: none;">
                            <span class="line-number d-none">{{ button['id'] }}.</span>
                            <a href="{{ url_for('design.edit_action', uuid=button['uuid']) }}" type="button" class="btn btn-light" style="{{ button['style'] }}">{{ button['label'] }}</a>
                            {% if not button["instrument"] in ["if","while","repeat"] %}
                                <a href="{{ url_for('design.duplicate_action', id=button['id']) }}" type="button" class="btn btn-light"><span class="bi bi-copy"></span></a>
                            {% endif %}
                            <a href="{{ url_for('design.delete_action', id=button['id']) }}" type="button" class="btn btn-light"><span class="bi bi-trash"></span></a>
                        </li>
                    {% endfor %}
                    </ul>

                </div>
            </div>
            <div>
                <a class="btn btn-dark {{ 'disabled' if not script.name or script.status == "finalized" else ''}}" href="{{url_for('database.publish')}}">Quick Save</a>
                <a class="btn btn-dark " href="{{ url_for('design.experiment_run') }}">Compile and Run</a>
            </div>
        </div>
    </div>

{# modals #}
<div class="modal fade" id="newScriptModal" tabindex="-1" aria-labelledby="newScriptModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="newScriptModalLabel">Save your current editing!</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                The current editing won't be saved. Are you sure you want to proceed?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"> Continue editing </button>
                <a role="button" class="btn btn-primary" href="{{url_for('design.clear')}}"> Already saved, clear all </a>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="saveasModal" tabindex="-1" aria-labelledby="saveasModal" aria-hidden="true" >
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="saveasModal">Save your script as </h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" name="run_name" action="{{ url_for('database.save_as') }}">
                <div class="modal-body">
                    <div class="input-group mb-3">
                        <label class="input-group-text" for="run_name">Run Name</label>
                        <input class="form-control" type="text" name="run_name" id="run_name" placeholder="{{script['name']}}" required="required">
                    </div>
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" name="register_workflow" id="register_workflow">
                        <label class="input-group-label" for="register_workflow">Register this workflow</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"> Close </button>
                    <button type="submit"  class="btn btn-primary"> Save </button>
                </div>
            </form>
        </div>
    </div>
</div>
<div class="modal fade" id="renameModal" tabindex="-1" aria-labelledby="renameModal" aria-hidden="true" >
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="renameModal">Rename your script</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" name="run_name" action="{{ url_for('database.edit_run_name') }}">
                <div class="modal-body">
                    <div class="input-group mb-3">
                        <label class="input-group-text" for="run_name">Run Name</label>
                        <input class="form-control" type="text" name="run_name" id="run_name" placeholder="{{script['name']}}" required="required">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"> Close </button>
                    <button type="submit"  class="btn btn-primary"> Save </button>
                </div>
            </form>
        </div>
    </div>
</div>
<div class="modal fade" id="jsonModal" tabindex="-1" aria-labelledby="jsonModal" aria-hidden="true" >
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="jsonModal">Import from JSON</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="{{ url_for('design.load_json') }}" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="input-group mb-3">
                        <input class="form-control" type="file" name="file" required="required">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"> Close </button>
                    <button type="submit" class="btn btn-primary"> Upload </button>
                </div>
            </form>
        </div>
    </div>
</div>
<!-- Bootstrap Modal -->
<div class="modal fade" id="dropModal" tabindex="-1" aria-labelledby="dropModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="dropModalLabel">Configure Action</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>Drop Position ID: <strong id="modalDropTarget"></strong></p>

                <!-- Form will be dynamically inserted here -->
                <div id="modalFormFields"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>


{% if instrument and use_llm %}
    <script>
        const buttonIds = {{ ['generate'] | tojson }};
    </script>
    <script src="{{ url_for('static', filename='js/overlay.js') }}"></script>
{% endif %}

<script>
    const updateListUrl = "{{ url_for('design.update_list') }}";

    // Toggle visibility of line numbers
    function toggleLineNumbers(save = true) {
        const show = document.getElementById('toggleLineNumbers').checked;
        document.querySelectorAll('.line-number').forEach(el => {
            el.classList.toggle('d-none', !show);
        });

        if (save) {
            localStorage.setItem('showLineNumbers', show ? 'true' : 'false');
        }
    }

    // Restore state on page load
    document.addEventListener('DOMContentLoaded', () => {
        const savedState = localStorage.getItem('showLineNumbers');
        const checkbox = document.getElementById('toggleLineNumbers');

        if (savedState === 'true') {
            checkbox.checked = true;
        }

        toggleLineNumbers(false);  // don't overwrite localStorage on load

        checkbox.addEventListener('change', () => toggleLineNumbers());
    });
</script>


<script src="{{ url_for('static', filename='js/sortable_design.js') }}"></script>

{% endblock %}