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

{% block body %}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.js"></script>


    {% if no_deck_warning and not dismiss %}
{#      auto pop import when there is no deck#}
        <script type="text/javascript">
            function OpenBootstrapPopup() {
                $("#importModal").modal('show');
            }
            window.onload = function () {
                OpenBootstrapPopup();
            };
        </script>
    {% endif %}

    <div class="row">
        {% if script['script'] or script['prep'] or script['cleanup'] %}
            <div class="col-lg-6 col-sm-12" id="run-panel"  style="{{ 'display: none;'  if pause_status else '' }}">
                <ul class="nav nav-tabs" id="myTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <a class="nav-link {{ 'disabled' if config_list else '' }} {{ 'active' if not config_list else '' }}" id="tab1-tab" data-bs-toggle="tab" href="#tab1" role="tab" aria-controls="tab1" aria-selected="false">Repeat</a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link {{ 'disabled' if not config_list else '' }} {{ 'active' if config_list else '' }}" id="tab4-tab" data-bs-toggle="tab" href="#tab4" role="tab" aria-controls="tab4" aria-selected="false">Configuration</a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link {{ 'disabled' if not config_list or not return_list else '' }}" id="tab3-tab" data-bs-toggle="tab" href="#tab3" role="tab" aria-controls="tab3" aria-selected="false">Bayesian Optimization</a>
                    </li>
                </ul>
                <div class="tab-content" id="myTabsContent">
                    <div class="tab-pane fade {{ 'show active' if not config_list else '' }}" id="tab1" role="tabpanel" aria-labelledby="tab1-tab">
                        <p><h5>Control panel:</h5></p>
                        <form role="form" method='POST' name="run" action="{{url_for('design.experiment_run')}}">
                            <div class="input-group mb-3">
                                <label class="input-group-text" for="repeat">Repeat for </label>
                                <input class="form-control" type="number" id="repeat" name="repeat" min="1" max="1000" value="1">
                                <label class="input-group-text" for="repeat"> times</label>
                            </div>
                            <div class="input-group mb-3">
                                <button class="form-control" type="submit" class="btn btn-dark">Run</button>
                            </div>
                        </form>
                    </div>

{#TODO#}
<div class="tab-pane fade {{ 'show active' if config_list else '' }}" id="tab4" role="tabpanel" aria-labelledby="tab4-tab">
    <!-- File Management Section -->
    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h6 class="mb-0"><i class="bi bi-file-earmark-text"></i> Configuration File</h6>
            <small class="text-muted">
                <a href="{{ url_for('design.download', filetype='configure') }}">
                    <i class="bi bi-download"></i> Download Empty Template
                </a>
            </small>
        </div>
        <div class="card-body">
            <div class="row g-3">
                <!-- File Selection -->
                <div class="col-md-6">
                    <form name="filenameForm" id="filenameForm" method="GET" action="{{ url_for('design.experiment_run') }}" enctype="multipart/form-data">
                        <div class="input-group">
                            <label class="input-group-text"><i class="bi bi-folder2-open"></i></label>
                            <select class="form-select" name="filename" id="filenameSelect" onchange="document.getElementById('filenameForm').submit();">
                                <option {{ 'selected' if not filename else '' }} value="">-- Select existing file --</option>
                                {% for config_file in config_file_list %}
                                    <option {{ 'selected' if filename == config_file else '' }} value="{{ config_file }}">{{ config_file }}</option>
                                {% endfor %}
                            </select>
                        </div>
                    </form>
                </div>

                <!-- File Upload -->
                <div class="col-md-6">
                    <form method="POST" id="loadFile" name="loadFile" action="{{ url_for('design.upload') }}" enctype="multipart/form-data">
                        <div class="input-group">
                            <input class="form-control" name="file" type="file" accept=".csv" required="required" onchange="document.getElementById('loadFile').submit();">
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
       <!-- Configuration Table -->



    <div class="card mb-4">
        <div class="card-header position-relative">
            <div class="position-absolute top-50 end-0 translate-middle-y me-3">
                <span id="saveStatus" class="badge bg-success" style="display: none;">
                    <i class="bi bi-check-circle"></i> Auto-saved
                </span>
                <span id="modifiedStatus" class="badge bg-warning" style="display: none;">
                    <i class="bi bi-pencil"></i> Modified
                </span>
            </div>
        </div>
        <div class="card-body p-0">
            <form method="POST" name="online-config" id="online-config" action="{{url_for('design.experiment_run')}}">
                <div class="table-responsive">
                    <table id="dataInputTable" class="table table-striped table-hover mb-0">
                        <thead class="table-dark">
                        <tr>
                            <th style="width: 40px;">#</th>
                            {% for column in config_list %}
                                <th>{{ column }}</th>
                            {% endfor %}
                            <th></th>
                        </tr>
                        </thead>
                        <tbody id="tableBody">
                        </tbody>
                    </table>
                </div>
            <div class="card-footer">
            <div class="d-flex justify-content-between align-items-center">
                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-success" onclick="addRow()">
                        <i class="bi bi-plus-circle"></i> Add Row
                    </button>
                    <button type="button" class="btn btn-warning" onclick="clearAllRows()">
                        <i class="bi bi-trash"></i> Clear All
                    </button>
                    <button type="button" class="btn btn-info" onclick="resetToFile()" id="resetToFileBtn" style="display: none;">
                        <i class="bi bi-arrow-clockwise"></i> Reset to File
                    </button>
                </div>
                <button type="submit" name="online-config" class="btn btn-primary btn-lg">
                    <i class="bi bi-play-circle"></i> Run
                </button>
            </div>
            </div>
            </form>
        </div>
        <!-- Config Preview (if loaded from file) -->
        {% if config_preview %}
            <div class="alert alert-info">
                <small><i class="bi bi-info-circle"></i> {{ config_preview|length }} rows loaded from {{ filename }}</small>
            </div>
        {% endif %}
    </div>
</div>

                    <div class="tab-pane fade" id="tab3" role="tabpanel" aria-labelledby="tab3-tab">
                        <form method="POST" name="bo" action="{{ url_for('design.experiment_run') }}">
                            <div class="container py-2">
                                <!-- Parameters -->
                                <h6 class="fw-bold mt-2 mb-1">Parameters</h6>
                                {% for config in config_list %}
                                    <div class="row align-items-center mb-2">
                                        <div class="col-3 col-form-label-sm">
                                            {{ config }}:
                                        </div>
                                        <div class="col-6">
                                            <select class="form-select form-select-sm" id="{{config}}_type" name="{{config}}_type">
                                                <option selected value="range">range</option>
                                                <option value="choice">choice</option>
                                                <option value="fixed">fixed</option>
                                            </select>
                                        </div>
                                        <div class="col-3">
                                            <input type="text" class="form-control form-control-sm" id="{{config}}_value" name="{{config}}_value" placeholder="1, 2, 3">
                                        </div>
                                    </div>
                                {% endfor %}
                                <!-- Objective -->
                                <h6 class="fw-bold mt-3 mb-1">Objectives</h6>
                                {% for objective in return_list %}
                                    <div class="row align-items-center mb-2">
                                        <div class="col-3 col-form-label-sm">
                                            {{ objective }}:
                                        </div>
                                        <div class="col-6">
                                            <select class="form-select form-select-sm" id="{{objective}}_min" name="{{objective}}_min">
                                                <option selected>minimize</option>
                                                <option>maximize</option>
                                                <option>none</option>
                                            </select>
                                        </div>
                                    </div>
                                {% endfor %}
                                <h6 class="fw-bold mt-3 mb-1">Budget</h6>
                                <div class="input-group mb-3">
                                    <label class="input-group-text" for="repeat">Max iteration </label>
                                    <input class="form-control" type="number" id="repeat" name="repeat" min="1" max="1000" value="25">
                                </div>
                                {% if not no_deck_warning%}
                                    <div class="input-group mb-3">
                                        <button class="form-control" type="submit" name="bo">Run</button>
                                    </div>
                                {% endif %}
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        {% else %}
            <div class="col-lg-6 col-sm-12" id="placeholder-panel">
            </div>
        {% endif %}

        <div class="col-lg-6 col-sm-12" id="code-panel" style="{{ '' if pause_status else 'display: none;'}}">
            <p>
                <h5>Progress：</h5>
                {% if "prep" in line_collection.keys() %}
                    {% set stype = "prep" %}
                    <h6>Preparation：</h6>
                    {% for code in line_collection["prep"] %}
                        <pre style="margin: 0; padding: 0; line-height: 1;"><code class="python" id="{{ stype }}-{{ loop.index0 }}" >{{code}}</code></pre>
                    {% endfor %}
                {% endif %}
                {% if "script" in line_collection.keys() %}
                    {% set stype = "script" %}
                    <h6>Experiment：</h6>
                    {% for code in line_collection["script"] %}
                        <pre style="margin: 0; padding: 0; line-height: 1;"><code class="python" id="{{ stype }}-{{ loop.index0 }}" >{{code}}</code></pre>
                    {% endfor %}
                {% endif %}
                {% if "cleanup" in line_collection.keys() %}
                    {% set stype = "cleanup" %}
                    <h6>Cleanup：</h6>
                    {% for code in line_collection["cleanup"] %}
                        <pre style="margin: 0; padding: 0; line-height: 1;"><code class="python" id="{{ stype }}-{{ loop.index0 }}" >{{code}}</code></pre>
                    {% endfor %}
                {% endif %}
            </p>
        </div>
        <div class="col-lg-6 col-sm-12 logging-panel">
            <p>
                <div class="p d-flex justify-content-between align-items-center">
                    <h5>Progress：</h5>
                    <div class="d-flex gap-2 ms-auto">
                        <button id="pause-resume" class="btn btn-info text-white" data-bs-toggle="tooltip" title="Pause execution">
                            {% if pause_status %}
                                <i class="bi bi-play-circle"></i>
                            {% else %}
                                <i class="bi bi-pause-circle"></i>
                            {% endif %}
                        </button>
                        <button id="abort-current" class="btn btn-danger text-white" data-bs-toggle="tooltip" title="Stop execution after current step">
                            <i class="bi bi-stop-circle"></i>
                        </button>
                        <button id="abort-pending" class="btn btn-warning text-white" data-bs-toggle="tooltip" title="Stop execution after current iteration">
                            <i class="bi bi-hourglass-split"></i>
                        </button>
                    </div>
                </div>
                <div class="text-muted mt-2">
                    <small><strong>Note:</strong> The current step cannot be paused or stopped until it completes. </small>
                </div>

            <div class="progress" role="progressbar" aria-label="Animated striped example" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100">
                <div id="progress-bar-inner" class="progress-bar progress-bar-striped progress-bar-animated"></div>
            </div>
            <p><h5>Log：</h5></p>
            <div id="logging-panel"></div>
        </div>

    </div>





    <!-- Error Modal -->
    <div class="modal fade" id="error-modal" tabindex="-1" aria-labelledby="errorModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="errorModalLabel">Error Detected</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <p id="error-message">An error has occurred.</p>
            <p>Do you want to continue execution or stop?</p>
          </div>
          <div class="modal-footer">
              <button type="button" class="btn btn-primary" id="retry-btn" data-bs-dismiss="modal">Rerun Current Step</button>
              <button type="button" class="btn btn-success" id="continue-btn" data-bs-dismiss="modal">Continue</button>
              <button type="button" class="btn btn-danger" id="stop-btn" data-bs-dismiss="modal">Stop Execution</button>
          </div>
        </div>
      </div>
    </div>

    <script src="{{ url_for('static', filename='js/socket_handler.js') }}"></script>
    <script>
        var rowCount = 0;
        var configColumns = [
            {% for column in config_list %}
                '{{ column }}'{{ ',' if not loop.last else '' }}
            {% endfor %}
        ];
        var configTypes = {
            {% for column, type in config_type_list.items() %}
                '{{ column }}': '{{ type }}'{{ ',' if not loop.last else '' }}
            {% endfor %}
        };

        // State management
        var originalFileData = null;
        var isModifiedFromFile = false;
        var saveTimeout = null;
        var lastSavedData = null;

        function addRow(data = null, skipSave = false) {
            rowCount++;
            var tableBody = document.getElementById("tableBody");
            var newRow = tableBody.insertRow(-1);

            // Row number cell
            var rowNumCell = newRow.insertCell(-1);
            rowNumCell.innerHTML = '<span class="badge bg-secondary">' + rowCount + '</span>';

            // Data cells
            configColumns.forEach(function(column, index) {
                var cell = newRow.insertCell(-1);
                var value = data && data[column] ? data[column] : '';
                var placeholder = configTypes[column] || 'value';
                cell.innerHTML = '<input type="text" class="form-control form-control-sm" name="' +
                    column + '[' + rowCount + ']" value="' + value + '" placeholder="' + placeholder +
                    '" oninput="onInputChange()" onchange="onInputChange()">';
            });

            // Action cell
            var actionCell = newRow.insertCell(-1);
            actionCell.innerHTML = '<button type="button" class="btn btn-sm btn-outline-danger" onclick="removeRow(this)" title="Remove row">' +
                '<i class="bi bi-trash"></i></button>';

            if (!skipSave) {
                markAsModified();
                debouncedSave();
            }
        }

        function removeRow(button) {
            var row = button.closest('tr');
            row.remove();
            updateRowNumbers();
            markAsModified();
            debouncedSave();
        }

        function updateRowNumbers() {
            var tableBody = document.getElementById("tableBody");
            var rows = tableBody.getElementsByTagName('tr');
            for (var i = 0; i < rows.length; i++) {
                var badge = rows[i].querySelector('.badge');
                if (badge) {
                    badge.textContent = i + 1;
                }
            }
        }

        function clearAllRows() {
            if (confirm('Are you sure you want to clear all rows?')) {
                var tableBody = document.getElementById("tableBody");
                tableBody.innerHTML = '';
                rowCount = 0;
                markAsModified();
                clearSavedData();
                // Add 5 empty rows by default
                for (let i = 0; i < 5; i++) {
                    addRow(null, true);
                }
                debouncedSave();
            }
        }

        function resetToFile() {
            if (originalFileData && confirm('Reset to original file data? This will lose all manual changes.')) {
                loadDataFromSource(originalFileData, false);
                isModifiedFromFile = false;
                updateStatusIndicators();
                debouncedSave();
            }
        }

        function onInputChange() {
            markAsModified();
            debouncedSave();
        }

        function markAsModified() {
            if (originalFileData) {
                isModifiedFromFile = true;
                updateStatusIndicators();
            }
        }

        function updateStatusIndicators() {
            var modifiedStatus = document.getElementById('modifiedStatus');
            var resetBtn = document.getElementById('resetToFileBtn');

            if (isModifiedFromFile && originalFileData) {
                modifiedStatus.style.display = 'inline-block';
                resetBtn.style.display = 'inline-block';
            } else {
                modifiedStatus.style.display = 'none';
                resetBtn.style.display = 'none';
            }
        }

        function showSaveStatus() {
            var saveStatus = document.getElementById('saveStatus');
            saveStatus.style.display = 'inline-block';
            setTimeout(function() {
                saveStatus.style.display = 'none';
            }, 2000);
        }

        function debouncedSave() {
            clearTimeout(saveTimeout);
            saveTimeout = setTimeout(function() {
                saveFormData();
                showSaveStatus();
            }, 1000); // Save 1 second after user stops typing
        }

        function saveFormData() {
            var formData = getCurrentFormData();
            try {
                sessionStorage.setItem('configFormData', JSON.stringify(formData));
                sessionStorage.setItem('configModified', isModifiedFromFile.toString());
                lastSavedData = formData;
            } catch (e) {
                console.warn('Could not save form data to sessionStorage:', e);
            }
        }

        function getCurrentFormData() {
            var tableBody = document.getElementById("tableBody");
            var rows = tableBody.getElementsByTagName('tr');
            var data = [];

            for (var i = 0; i < rows.length; i++) {
                var inputs = rows[i].getElementsByTagName('input');
                var rowData = {};
                var hasData = false;

                for (var j = 0; j < inputs.length; j++) {
                    var input = inputs[j];
                    var name = input.name;
                    if (name) {
                        var columnName = name.substring(0, name.indexOf('['));
                        rowData[columnName] = input.value;
                        if (input.value.trim() !== '') {
                            hasData = true;
                        }
                    }
                }

                if (hasData) {
                    data.push(rowData);
                }
            }

            return data;
        }

        function loadSavedData() {
            try {
                var savedData = sessionStorage.getItem('configFormData');
                var savedModified = sessionStorage.getItem('configModified');

                if (savedData) {
                    var parsedData = JSON.parse(savedData);
                    isModifiedFromFile = savedModified === 'true';
                    return parsedData;
                }
            } catch (e) {
                console.warn('Could not load saved form data:', e);
            }
            return null;
        }

        function clearSavedData() {
            try {
                sessionStorage.removeItem('configFormData');
                sessionStorage.removeItem('configModified');
            } catch (e) {
                console.warn('Could not clear saved data:', e);
            }
        }

        function loadDataFromSource(data, isFromFile = false) {
            // Clear existing rows
            var tableBody = document.getElementById("tableBody");
            tableBody.innerHTML = '';
            rowCount = 0;

            // Add rows with data
            data.forEach(function(rowData) {
                addRow(rowData, true);
            });

            // Add a few empty rows for additional input
            for (let i = 0; i < 3; i++) {
                addRow(null, true);
            }

            if (isFromFile) {
                originalFileData = JSON.parse(JSON.stringify(data)); // Deep copy
                isModifiedFromFile = false;
                clearSavedData(); // Clear saved data when loading from file
            }

            updateStatusIndicators();
        }

        function loadConfigData() {
            // Check for saved form data first
            var savedData = loadSavedData();

            {% if config_preview %}
                var fileData = {{ config_preview | tojson | safe }};
                originalFileData = JSON.parse(JSON.stringify(fileData)); // Deep copy

                if (savedData && savedData.length > 0) {
                    // Load saved data if available
                    loadDataFromSource(savedData, false);
                    console.log('Loaded saved form data');
                } else {
                    // Load from file
                    loadDataFromSource(fileData, true);
                    console.log('Loaded file data');
                }
            {% else %}
                if (savedData && savedData.length > 0) {
                    // Load saved data
                    loadDataFromSource(savedData, false);
                    console.log('Loaded saved form data');
                } else {
                    // Add default empty rows
                    for (let i = 0; i < 5; i++) {
                        addRow(null, true);
                    }
                }
            {% endif %}
        }

        // Handle page unload
        window.addEventListener('beforeunload', function() {
            saveFormData();
        });

        // Initialize table when page loads
        document.addEventListener("DOMContentLoaded", function() {
            loadConfigData();
        });
    </script>
{% endblock %}