{% extends "base.html" %}

{% block title %}Task Queue - Timmy Time{% endblock %}

{% block extra_styles %}{% endblock %}

{% block content %}
<div class="tasks-container py-3">

  <div class="tasks-header">
    <div class="tasks-title">TASK QUEUE</div>
    <button class="task-btn task-btn-approve" onclick="openCreateModal()" style="padding:6px 16px; font-size:0.8rem;">+ ADD TASK</button>
  </div>

  <div class="tasks-columns">
    <!-- PENDING APPROVAL -->
    <div class="card mc-panel">
      <div class="card-header mc-panel-header task-column-header">
        <span class="task-column-title">// PENDING APPROVAL</span>
        <span class="badge badge-warning" id="pending-count">{{ pending_count }}</span>
      </div>
      <div class="card-body p-2" id="pending-list"
           hx-get="/tasks/pending" hx-trigger="every 15s" hx-swap="innerHTML">
        {% if pending %}
          {% for task in pending %}
            {% include "partials/task_card.html" %}
          {% endfor %}
        {% else %}
          <div class="empty-column">No pending tasks</div>
        {% endif %}
      </div>
    </div>

    <!-- ACTIVE -->
    <div class="card mc-panel">
      <div class="card-header mc-panel-header task-column-header">
        <span class="task-column-title">// ACTIVE</span>
        <span class="badge badge-info" id="active-count">{{ active | length }}</span>
      </div>
      <div class="card-body p-2" id="active-list"
           hx-get="/tasks/active" hx-trigger="every 10s" hx-swap="innerHTML">
        {% if active %}
          {% for task in active %}
            {% include "partials/task_card.html" %}
          {% endfor %}
        {% else %}
          <div class="empty-column">No active tasks</div>
        {% endif %}
      </div>
    </div>

    <!-- COMPLETED -->
    <div class="card mc-panel">
      <div class="card-header mc-panel-header task-column-header">
        <span class="task-column-title">// COMPLETED</span>
        <span class="badge badge-secondary" id="completed-count">{{ completed | length }}</span>
      </div>
      <div class="card-body p-2" id="completed-list" style="max-height: 70vh; overflow-y: auto;"
           hx-get="/tasks/completed" hx-trigger="every 30s" hx-swap="innerHTML">
        {% if completed %}
          {% for task in completed %}
            {% include "partials/task_card.html" %}
          {% endfor %}
        {% else %}
          <div class="empty-column">No completed tasks yet</div>
        {% endif %}
      </div>
    </div>
  </div>

</div>

<!-- Create Task Modal -->
<div class="task-modal-overlay" id="create-modal">
  <div class="task-modal">
    <h3>Create Task</h3>
    <form id="create-task-form" hx-post="/tasks/create" hx-target="#pending-list" hx-swap="afterbegin" hx-on::after-request="closeCreateModal()">
      <label>Title</label>
      <input type="text" name="title" required placeholder="Short description of the task">

      <label>Description</label>
      <textarea name="description" placeholder="Full task details (optional)"></textarea>

      <label>Assign To</label>
      <select name="assigned_to" id="modal-assigned-to">
        {% for agent in agents %}
        <option value="{{ agent.name }}" {% if pre_assign == agent.name %}selected{% endif %}>{{ agent.name }}</option>
        {% endfor %}
      </select>

      <label>Priority</label>
      <select name="priority">
        <option value="low">Low</option>
        <option value="normal" selected>Normal</option>
        <option value="high">High</option>
        <option value="urgent">Urgent</option>
      </select>

      <div class="task-modal-actions">
        <button type="button" class="task-btn task-btn-cancel" onclick="closeCreateModal()">CANCEL</button>
        <button type="submit" class="task-btn task-btn-approve">CREATE</button>
      </div>
    </form>
  </div>
</div>

<script>
function openCreateModal(agentName) {
  document.getElementById('create-modal').classList.add('open');
  if (agentName) {
    var sel = document.getElementById('modal-assigned-to');
    for (var i = 0; i < sel.options.length; i++) {
      if (sel.options[i].value === agentName) { sel.selectedIndex = i; break; }
    }
  }
}
function closeCreateModal() {
  document.getElementById('create-modal').classList.remove('open');
  document.getElementById('create-task-form').reset();
}
// Close on overlay click
document.getElementById('create-modal').addEventListener('click', function(e) {
  if (e.target === this) closeCreateModal();
});
// Close on Escape
document.addEventListener('keydown', function(e) {
  if (e.key === 'Escape') closeCreateModal();
});

// Toggle result expansion
document.addEventListener('click', function(e) {
  if (e.target.classList.contains('task-result')) {
    e.target.classList.toggle('expanded');
  }
});

// WebSocket live updates for task events
(function() {
  var protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  var ws;
  function connectTaskWs() {
    try {
      ws = new WebSocket(protocol + '//' + window.location.host + '/swarm/live');
      ws.onmessage = function(event) {
        try {
          var msg = JSON.parse(event.data);
          if (msg.type === 'task_event') {
            // Refresh the relevant column
            htmx.trigger('#pending-list', 'htmx:trigger');
            htmx.trigger('#active-list', 'htmx:trigger');
            htmx.trigger('#completed-list', 'htmx:trigger');
          }
        } catch(e) {}
      };
      ws.onclose = function() {
        setTimeout(connectTaskWs, 5000);
      };
    } catch(e) {}
  }
  connectTaskWs();
})();

// Open create modal from URL param (?assign=timmy)
var params = new URLSearchParams(window.location.search);
if (params.get('assign')) {
  openCreateModal(params.get('assign'));
}
</script>
{% endblock %}
