{% load static %}
<!DOCTYPE html>
<html>
<head>
    <title>Test Package Builder</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="{% static 'css/uikit.min.css' %}">
    <style>
      .operation-card {
        border: 1px solid #dadada;
        border-radius: 8px;
        margin: 8px 0;
        padding: 12px;
        background: #fafbfc;
        position: relative;
      }
      .subtitle {
        font-size: 14px;
        color: #777;
      }
      table.reqtable { width:100%; font-size:14px; margin-bottom:8px; }
      table.reqtable th, table.reqtable td { padding:4px 6px; }
      table.reqtable input, table.reqtable select { min-width: 70px; }
      .remove-row { color: #d44; font-weight:bold; cursor:pointer; }
      .add-row-btn { font-size: 13px; margin-top: 2px; }
      summary { font-weight: bold; cursor:pointer; }
    </style>
</head>
<body>

<div class="uk-container uk-padding">
    <h1 class="uk-text-center uk-margin">Test Package Builder<br><span class="subtitle">Structured Table Entry UI</span></h1>
    <form id="package-test-form" 
          hx-post="{% if package %}/{{ system }}/package/{{ package.id }}{% else %}/{{ system }}/package/new{% endif %}"
          hx-trigger="submit"
          hx-target="#toast-dock"
          hx-swap="innerHTML"
          method="POST" autocomplete="off">
      {% csrf_token %}
      <div class="uk-margin">
        <label class="uk-form-label" for="package_name">Name</label>
        <input class="uk-input" id="package_name" name="package_name" type="text" value="{{package.package_name|default:''}}" required>
      </div>
      <div class="uk-margin">
        <label class="uk-form-label" for="package_type">Type</label>
        <input class="uk-input" id="package_type" name="package_type" type="text" value="{{package.package_type|default:''}}">
      </div>
      <div class="uk-width-1-1">
        <label class="uk-form-label" for="package_description">Description</label>
        <div class="uk-form-controls">
            <textarea class="uk-textarea" id="package_description" name="package_description" rows="3">{{package.package_description|default:''}}</textarea>
        </div>
      </div>
      <div class="uk-width-1-1">
        <label class="uk-form-label" for="package_doc_md">Documentation</label>
        <div class="uk-form-controls">
            <textarea class="uk-textarea" id="package_doc_md" name="package_doc_md" rows="3">{{package.package_doc_md|default:''}}</textarea>
        </div>
      </div>
      <div class="uk-margin">
        <div id="trait-dock"></div>
        <input id="trait-ajax-autocomplete" class="uk-input uk-input-small">
        <div id="trait-suggestions"></div>
      </div>
      <div class="uk-margin">
        <label class="uk-form-label">Package Requirements</label>
        <table id="reqtable" class="uk-table reqtable">
          <thead>
            <tr>
              <th>Attribute</th>
              <th>Condition</th>
              <th>Value</th>
            </tr>
          </thead>
          <tbody>
            {% for req in package.package_requirements %}
                <tr>
                  <td><input class="uk-input" type="text" value="{{ req.attr }}"></td>
                  <td>
                    <select class="uk-select">
                      <option value=="==" {% if req.condition == "==" %}selected{% endif %}>=</option>
                      <option value=">=" {% if req.condition == ">=" %}selected{% endif %}>&ge;</option>
                      <option value="<=" {% if req.condition == "<=" %}selected{% endif %}>&le;</option>
                      <option value="!=" {% if req.condition == "!=" %}selected{% endif %}>&ne;</option>
                    </select>
                  </td>
                  <td><input class="uk-input" type="text" value="{{ req.value }}"></td>
                </tr>
            {% endfor %}
          </tbody>
        </table>
        <button type="button" class="uk-button uk-button-default uk-button-xsmall add-row-btn" id="add-package-req-btn" onclick="addPackageRequirement()">Add Requirement</button>
      </div>
      <div>
        <ul uk-tab>
          <li><a href="#">Operations</a></li>
          <li><a href="#">Features</a></li>
        </ul>

        <div class="uk-switcher uk-margin">
          <div>
            <h3>Operations
              <button id="add-operation-btn" type="button" class="uk-button uk-button-primary uk-button-small uk-margin-small-left">
                  <span uk-icon="icon: plus"></span> Add Operation
              </button>
            </h3>
            <div id="operations-list"></div>
          </div>
          <div>
            <button type="button" class="uk-button" onclick="openFeatureSelect()">Add Feature</button>
            <table class="uk-table uk-table-striped">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Description</th>
                  <th>Status</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody id="features-table-body">
              </tbody>
            </table>
          </div>
        </div>
      </div>
      <div class="uk-margin">
        <button class="uk-button uk-button-primary uk-width-1-1">Submit Package</button>
      </div>
    </form>
</div>

<div id="featureSelectModal" class="uk-modal-container">
    <div class="uk-modal-dialog uk-modal-body">
        <h2 class="uk-modal-title">Select Feature...</h2>
        <button class="uk-modal-close-default" type="button" uk-close></button>
        <div class="uk-margin">
          <input onchange="changeFeatureSearchQuery()" id="feature-search-input" class="uk-input" placeholder="Search features...">
        </div>
        <div id="modal-feature-table-area">
            <table class="uk-table uk-table-divider uk-table-hover">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Description</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody id="featureSearchTable">
              </tbody>
            </table>
            <div id="featureSerachPage">
            </div>
        </div>
    </div>
</div>


<script src="{% static 'js/uikit.min.js' %}"></script>
<script src="{% static 'js/uikit-icons.min.js' %}"></script>
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
<script>
  var operations = {{ package.package_operations|default:'[]'|safe }};
  var selectedTraits = {{ traits|default:'[]'|safe }};
  var selectedFeatures = {{ features|default:'[]'|safe}};
  var system = "{{ system|escapejs }}";
  console.log(operations)
  renderOperations()
  renderTraitChips()
  renderFeatureTable(selectedFeatures)

  UIkit.modal(document.getElementById('featureSelectModal'));

  function openFeatureSelect(){
    querySearchFeatures()
    UIkit.modal(document.getElementById('featureSelectModal')).show()
  }

  function truncateWords(str, wordLimit) {
    if (!str) return '';
    const words = str.split(/\s+/);
    return words.length > wordLimit
      ? words.slice(0, wordLimit).join(' ') + '…'
      : str;
  }

  function renderFeatureTable(features){
    let featureTable = document.getElementById('features-table-body');
    featureTable.innerHTML = "";

    features.forEach(feat => {
      console.log(feat)
      let tableRow = document.createElement('tr');

      let nameCell = document.createElement('td');
      nameCell.innerHTML = feat.feature_name;

      let descriptionCell = document.createElement('td');
      descriptionCell.innerHTML = truncateWords(feat.feature_description, 30)

      let stateCell = document.createElement('td');
      if(selectedFeatures.some(selfeat => selfeat.id === feat.id)){
        console.log('true')
        stateCell.innerHTML = `<span class="uk-label uk-label-success">Added</span>`
      }

      let actionCell = document.createElement('td');

      tableRow.appendChild(nameCell)
      tableRow.appendChild(descriptionCell)
      tableRow.appendChild(stateCell)
      tableRow.appendChild(actionCell)

      featureTable.appendChild(tableRow)
    });

  }

  // Functions to handle Features searching!
  var currentFeaturePage = 1;
  var endFeaturePage = 1;
  var hasPrev = false;
  var hasNext = false;
  var searchFeatureQuery = "";

  async function querySearchFeatures() {
    const url = `/features/search/?system=${encodeURIComponent(system)}&q=${encodeURIComponent(searchFeatureQuery)}&page=${currentFeaturePage}`;
    const response = await fetch(url)
    const data = await response.json();
    currentFeaturePage = data.page;
    endFeaturePage = data.num_pages;
    hasPrev = data.has_previous;
    hasNext = data.has_next;
    renderSearchFeatureTable(data.results);
    renderSearchPagenation()
  }
  
  function changeFeatureSearchPage(page){
    currentFeaturePage = page;
    querySearchFeatures()
  }

  function debounce(func, wait) {
    let timeout;
    return function(...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(this, args), wait);
    }
  }

  const debouncedFeatureQuery = debounce(function(event) {
      const query = event.target.value.trim();

      if(query.length < 2){
        searchFeatureQuery = "";
        querySearchFeatures()
        return;
      }

      searchFeatureQuery = query;
      currentFeaturePage = 1;
      querySearchFeatures();
  }, 250);
  
  document.getElementById('feature-search-input').addEventListener('input', debouncedFeatureQuery);

  function renderSearchFeatureTable(features){
    console.log(features)
    let featureTable = document.getElementById('featureSearchTable');
    featureTable.innerHTML = "";

    features.forEach(feat => {
      console.log(feat)
      let tableRow = document.createElement('tr');

      let nameCell = document.createElement('td');
      nameCell.innerHTML = feat.feature_name;

      let descriptionCell = document.createElement('td');
      descriptionCell.innerHTML = truncateWords(feat.feature_description, 30)

      let actionCell = document.createElement('td');

      actionCell.innerHTML = `<button class="uk-button uk-button-primary" type="button">Select</button>`

      tableRow.appendChild(nameCell)
      tableRow.appendChild(descriptionCell)
      tableRow.appendChild(actionCell)

      featureTable.appendChild(tableRow)
    });

  }

  function renderSearchPagenation(){
    let pageDiv = document.getElementById('featureSerachPage')
    pageDiv.innerHTML = '';

    let unorderedList = document.createElement('ul')
    unorderedList.setAttribute('class', 'uk-pagination uk-flex-center')

    let firstEl = document.createElement('li')
    firstEl.innerHTML = `<a onclick="changeFeatureSearchPage(1)">First</a>`

    let prevEl = document.createElement('li')
    prevEl.innerHTML = `<a onclick="changeFeatureSearchPage(${currentFeaturePage - 1})">Prev</a>`

    if(!hasPrev){
      prevEl.setAttribute('class', 'uk-disabled')
      prevEl.setAttribute('class', 'uk-disabled')
    }

    let pageEl = document.createElement('li')
    pageEl.innerHTML = `<span>Page ${currentFeaturePage} of ${endFeaturePage}</span>`

    let nextEl = document.createElement('li')
    nextEl.innerHTML = `<a onclick="changeFeatureSearchPage(${currentFeaturePage + 1})">Next</a>`

    let lastEl = document.createElement('li')
    lastEl.innerHTML = `<a onclick="changeFeatureSearchPage(${endFeaturePage})">Last</a>`

    if(!hasNext){
      nextEl.setAttribute('class', 'uk-disabled')
      lastEl.setAttribute('class', 'uk-disabled')
    }

    unorderedList.appendChild(firstEl)
    unorderedList.appendChild(prevEl)
    unorderedList.append(pageEl)
    unorderedList.appendChild(nextEl)
    unorderedList.appendChild(lastEl)

    pageDiv.appendChild(unorderedList)
  }

  function renderTraitChips(){
    let traitDock = document.getElementById('trait-dock');
    traitDock.innerHTML = ""; 
    selectedTraits.forEach(tr => {
      let traitChip = document.createElement('span');
      traitChip.className = "uk-label uk-label-primary uk-margin-small-right uk-margin-small-bottom";
      traitChip.innerHTML = `${tr.trait_name}
        <a href='#' style='color:white;margin-left:6px' onclick='removeTrait("${tr.id}");return false;'>&times;</a>`;
      traitDock.appendChild(traitChip);
    });
  }
  
  function addTrait(trait){
    if (selectedTraits.some(t => t.id === trait.id)) return;
    selectedTraits.push(trait)
    renderTraitChips()
  }

  function removeTrait(id){
    selectedTraits = selectedTraits.filter(t => String(t.id) !== String(id));
    renderTraitChips()
  }

  document.getElementById('trait-ajax-autocomplete').addEventListener('input', function(){
  let query = this.value.trim();
  if(query.length < 2) return;
  fetch(`/traits/search/?system={{ system }}&q=${encodeURIComponent(query)}`)
    .then(resp => resp.json())
    .then(data => {
        let suggestionElement = document.getElementById('trait-suggestions')
        suggestionElement.innerHTML = ''
        if(data.length > 0){
          suggestionElement.innerHTML = '<strong>Here are some suggestions: </strong>'
        } 
        data.forEach(trait => {
          let a_link = document.createElement('a')
          a_link.href = "#";
          a_link.innerHTML = trait.trait_name
          a_link.onclick = function(e){
            e.preventDefault();
            addTrait(trait);
          }
          suggestionElement.appendChild(a_link)
          suggestionElement.appendChild(document.createTextNode(" "));
        });
        suggestionElement.style.display = 'block';
      });
  });

  function addPackageRequirement(){
    var table = document.getElementById(`reqtable`);
    var tbody = table.querySelector('tbody');
    var tblRow = document.createElement('tr');
    
    var attrCell = document.createElement('td');
    var attrInput = document.createElement('input');
    attrInput.type = 'text';
    attrInput.className = 'uk-input';
    attrCell.appendChild(attrInput);
    
    tblRow.appendChild(attrCell);
    
    var conditionCell = document.createElement('td');
    var conditionSelect = document.createElement('select');
    conditionSelect.className = 'uk-select';
    ['==','>=','<=','!='].forEach(function(opt) {
      var option = document.createElement('option');
      option.value = opt;
      option.text = (opt === '==') ? '=' : opt;
      conditionSelect.appendChild(option);
    });
    conditionCell.appendChild(conditionSelect);
    tblRow.appendChild(conditionCell);
    
    var valueCell = document.createElement('td');
    var valueInput = document.createElement('input');
    valueInput.type = 'text';
    valueInput.className = 'uk-input';
    valueCell.appendChild(valueInput);
    
    tblRow.appendChild(valueCell);
    tbody.appendChild(tblRow)
  }

  function makeOperationCard(operation, idx) {
  console.log(operation)
  const div = document.createElement('div');
  div.className = 'operation-card uk-grid-small';
  div.innerHTML += `<details ${operation._expanded ? 'open' : ''}>
  <summary>Operation #${idx+1}: ${operation.attr || '—'}<span class='subtitle'> (${operation.operation||''})</span></summary>
    <div class="uk-grid-small" uk-grid>
      <div class="uk-width-1-3">
        <label>Attribute
          <input id="operation-attr${idx}" class="uk-input op-attribute" placeholder="Attribute" type="text" value="${operation.attr||''}">
        </label>
      </div>
      <div class="uk-width-1-3">
        <label>Operation
          <select id="operation-operation${idx}" class="uk-select op-operation">
            <option value="add" ${operation.operation==='add'?'selected':''}>Add</option>
            <option value="subtract" ${operation.operation==='subtract'?'selected':''}>Subtract</option>
            <option value="multiply" ${operation.operation==='multiply'?'selected':''}>Multiply</option>
            <option value="divide" ${operation.operation==='divide'?'selected':''}>Divide</option>
            <option value="set" ${operation.operation==='set'?'selected':''}>Set</option>
          </select>
        </label>
      </div>
      <div class="uk-width-1-3">
        <label>Value
          <input id="operation-value${idx}" class="uk-input op-value" type="text" value="${operation.value||''}">
        </label>
      </div>
    </div>
    <hr></hr>
    <div class="uk-margin-small">
      <div style="margin-top:6px;">
        <table class="uk-table" id="limits-table-op${idx}">
          <caption>Operations Limits</caption>
          <thead>
              <tr>
                  <th>Attribute</th>
                  <th>Condition</th>
                  <th>Value</th>
              </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
        <button type="button" class="uk-button uk-button-default uk-width-1-2" onclick=addOperationLimits(${idx})>Add Limit</button>
      </div>
      <hr></hr>
      <div style="margin-top:6px;">
        <table class="uk-table uk-table-small" id="reqs-table-op${idx}">
          <caption>Operations Requirements</caption>
          <thead>
              <tr>
                  <th>Attribute</th>
                  <th>Condition</th>
                  <th>Value</th>
              </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
        <button type="button" class="uk-button uk-button-default uk-width-1-2" onclick=addOperationRequirement(${idx})>Add Requirement</button>
      </div>
    </div>
    <button type="button" class="uk-button uk-button-danger uk-button-xsmall remove-op-btn"><span uk-icon="icon: close"></span> Remove Operation</button>
  </details>`;
  return div;
  }

  function addOperationLimits(idx){
  var table = document.getElementById(`limits-table-op${idx}`);
  var tbody = table.querySelector('tbody');
  var tblRow = document.createElement('tr');
  var attrCell = document.createElement('td');
  var attrInput = document.createElement('input');
  attrInput.type = 'text';
  attrInput.className = 'uk-input';
  attrCell.appendChild(attrInput);
  tblRow.appendChild(attrCell);
  var conditionCell = document.createElement('td');
  var conditionSelect = document.createElement('select');
  conditionSelect.className = 'uk-select';
  ['==','>=','<=','!='].forEach(function(opt) {
  var option = document.createElement('option');
  option.value = opt;
  option.text = (opt === '==') ? '=' : opt;
  conditionSelect.appendChild(option);
  });
  conditionCell.appendChild(conditionSelect);
  tblRow.appendChild(conditionCell);
  var valueCell = document.createElement('td');
  var valueInput = document.createElement('input');
  valueInput.type = 'text';
  valueInput.className = 'uk-input';
  valueCell.appendChild(valueInput);
  tblRow.appendChild(valueCell);
  tbody.appendChild(tblRow)
  }

  function addOperationRequirement(idx){
  var table = document.getElementById(`reqs-table-op${idx}`);
  var tbody = table.querySelector('tbody');
  var tblRow = document.createElement('tr');
  var attrCell = document.createElement('td');
  var attrInput = document.createElement('input');
  attrInput.type = 'text';
  attrInput.className = 'uk-input';
  attrCell.appendChild(attrInput);
  tblRow.appendChild(attrCell);
  var conditionCell = document.createElement('td');
  var conditionSelect = document.createElement('select');
  conditionSelect.className = 'uk-select';
  ['==','>=','<=','!='].forEach(function(opt) {
  var option = document.createElement('option');
  option.value = opt;
  option.text = (opt === '==') ? '=' : opt;
  conditionSelect.appendChild(option);
  });
  conditionCell.appendChild(conditionSelect);
  tblRow.appendChild(conditionCell);
  var valueCell = document.createElement('td');
  var valueInput = document.createElement('input');
  valueInput.type = 'text';
  valueInput.className = 'uk-input';
  valueCell.appendChild(valueInput);
  tblRow.appendChild(valueCell);
  tbody.appendChild(tblRow)
  }

  function readRequestTableRows(tableId){
    const table = document.getElementById(tableId);
    if(!table) return [];
    const rows = table.querySelectorAll('tbody tr');
    let arr = [];
    rows.forEach(row => {
      const cells = row.querySelectorAll('td');
      if(cells.length>=3){
        const attr = cells[0].querySelector('input')?.value || "";
        const condition = cells[1].querySelector('select')?.value || "";
        const value = cells[2].querySelector('input')?.value || "";
        if(attr || condition || value){
          arr.push({attr, condition, value});
        }
      }
    })
    
    return arr;
  }

  function renderOperations() {
    const cont = document.getElementById('operations-list');
    cont.innerHTML = '';
    operations.forEach((op, i) => {
      cont.appendChild(makeOperationCard(op, i));
    });
  }

  document.getElementById('add-operation-btn').onclick = function() {
    operations.push({ attribute: '', operation: '', value: '', limits: [], requirements: [], _expanded:true });
    renderOperations();
  };

  document.getElementById('package-test-form').onsubmit = function(e) {
    operations.forEach((op, idx) => {
      op.attr = document.getElementById('operation-attr' + idx).value;
      op.operation = document.getElementById('operation-operation' + idx).value;
      op.value = document.getElementById('operation-value' + idx).value;
      op.limits = readRequestTableRows('limits-table-op' + idx);
      op.requirements = readRequestTableRows('reqs-table-op' + idx)
    })

    let package_requirements = readRequestTableRows('reqtable')

    let payload = {
      package_name: document.getElementById('package_name').value,
      package_description: document.getElementById('package_description').value,
      package_type: document.getElementById('package_type').value,
      package_doc_md: document.getElementById('package_doc_md').value,
      package_system: system,
      package_requirements: package_requirements,
      package_operations: operations.map(({_expanded, ...op})=>op),
      package_traits: selectedTraits,
      features: selectedFeatures
    };

    console.log(payload)

    let field = document.getElementById('package_payload');
    if (!field) {
      field = document.createElement('input');
      field.type = 'hidden';
      field.id = 'package_payload';
      field.name = 'package_payload';
      this.appendChild(field);
    }
    field.value = JSON.stringify(payload);
  };

</script>

<div id="toast-dock"></div>

</body>
</html>
