{% extends "modern/base.html" %}

{% block title %}Search - BLOOM LIMS{% endblock %}

{% block content %}
<div class="page-header">
  <div>
    <h1><i class="fas fa-search"></i> Unified Search</h1>
    <p class="text-muted">
      {% if search_response.total > 0 %}
      Showing {{ results | length }} of {{ search_response.total }} result(s)
      {% elif query or types or record_types %}
      No results found
      {% else %}
      Search instances, templates, lineage, and audit records
      {% endif %}
    </p>
  </div>
  <div class="page-actions">
    {% if search_response.total > 0 %}
    <button type="button" class="btn btn-outline btn-sm" onclick="exportResults('tsv')">
      <i class="fas fa-file-csv"></i> Download TSV
    </button>
    <button type="button" class="btn btn-outline btn-sm" onclick="exportResults('json')">
      <i class="fas fa-file-code"></i> Download JSON
    </button>
    {% endif %}
  </div>
</div>

<div class="card mb-lg">
  <div class="card-body">
    <form action="/search" method="GET" id="searchForm">
      <div class="form-group mb-md">
        <label class="form-label">Search Query</label>
        <input
          type="text"
          class="form-input"
          name="q"
          id="searchQuery"
          value="{{ query }}"
          placeholder="Search by EUID, name, type, subtype, or metadata"
        >
      </div>

      <div class="form-group mb-md">
        <label class="form-label">Object Categories</label>
        <div class="filter-grid">
          {% for category in ['container', 'content', 'workflow', 'equipment', 'subject', 'data'] %}
          <label class="checkbox-label">
            <input type="checkbox" class="types-filter" value="{{ category }}" {% if category in selected_types %}checked{% endif %}>
            <span>{{ category }}</span>
          </label>
          {% endfor %}
        </div>
      </div>

      <div class="form-group mb-md">
        <label class="form-label">Record Types</label>
        <div class="filter-grid">
          {% for record_type in ['instance', 'template', 'lineage', 'audit'] %}
          <label class="checkbox-label">
            <input type="checkbox" class="record-type-filter" value="{{ record_type }}" {% if record_type in selected_record_types %}checked{% endif %}>
            <span>{{ record_type }}</span>
          </label>
          {% endfor %}
        </div>
      </div>

      <div class="form-actions">
        <button type="submit" class="btn btn-primary">
          <i class="fas fa-search"></i> Search
        </button>
        <button type="button" class="btn btn-outline" onclick="clearFilters()">
          <i class="fas fa-times"></i> Clear
        </button>
      </div>
    </form>
  </div>
</div>

{% if search_response.facets.record_type %}
<div class="card mb-lg">
  <div class="card-body">
    <h3 class="card-title mb-sm"><i class="fas fa-chart-bar"></i> Facets</h3>
    <div class="facet-row">
      {% for key, value in search_response.facets.record_type.items() %}
      <span class="facet-chip">{{ key }}: {{ value }}</span>
      {% endfor %}
    </div>
    {% if search_response.facets.category %}
    <div class="facet-row mt-sm">
      {% for key, value in search_response.facets.category.items() %}
      <span class="facet-chip facet-chip-category">{{ key }}: {{ value }}</span>
      {% endfor %}
    </div>
    {% endif %}
    {% if search_response.truncated %}
    <p class="text-warning mt-sm">Results were truncated by the configured scan cap.</p>
    {% endif %}
  </div>
</div>
{% endif %}

{% if results %}
<div class="card">
  <div class="card-header">
    <h3 class="card-title"><i class="fas fa-table"></i> Results</h3>
    <span class="text-muted text-sm">Page {{ search_response.page }} of {{ search_response.total_pages }}</span>
  </div>
  <div class="card-body">
    <div class="table-container">
      <table class="table" data-search-results-table="true">
        <thead>
          <tr>
            <th class="sortable-col" data-sort-index="0">Record</th>
            <th class="sortable-col" data-sort-index="1">Category</th>
            <th class="sortable-col" data-sort-index="2">Type</th>
            <th class="sortable-col" data-sort-index="3">Name</th>
            <th class="sortable-col" data-sort-index="4">Status</th>
            <th class="sortable-col" data-sort-index="5">Timestamp</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {% for result in results %}
          {% set metadata = result.metadata if result.metadata else {} %}
          {% set detail_euid = result.euid or metadata.get('rel_table_euid_fk', '') %}
          <tr>
            <td>
              <div class="text-sm"><strong>{{ result.record_type }}</strong></div>
              {% if detail_euid %}
              <a href="/euid_details?euid={{ detail_euid }}" class="badge badge-euid">{{ detail_euid }}</a>
              {% else %}
              <span class="text-muted">-</span>
              {% endif %}
            </td>
            <td>{{ result.category or '-' }}</td>
            <td>
              <span>{{ result.type or '-' }}</span>
              <span class="text-muted text-sm">/{{ result.subtype or '-' }}</span>
            </td>
            <td>{{ result.name or '-' }}</td>
            <td>{{ result.status or '-' }}</td>
            <td class="text-muted text-sm">{{ result.timestamp or result.created_dt or '-' }}</td>
            <td>
              {% if detail_euid %}
              <a href="/euid_details?euid={{ detail_euid }}" class="btn btn-sm btn-outline"><i class="fas fa-eye"></i></a>
              {% else %}
              <span class="text-muted">-</span>
              {% endif %}
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>

    {% if search_response.total_pages > 1 %}
    <div class="pagination-row mt-md">
      {% if search_response.page > 1 %}
      <a
        class="btn btn-outline btn-sm"
        href="/search?q={{ query | urlencode }}&types={{ types | urlencode }}&record_types={{ record_types | urlencode }}&page={{ search_response.page - 1 }}"
      >
        Previous
      </a>
      {% endif %}
      {% if search_response.page < search_response.total_pages %}
      <a
        class="btn btn-outline btn-sm"
        href="/search?q={{ query | urlencode }}&types={{ types | urlencode }}&record_types={{ record_types | urlencode }}&page={{ search_response.page + 1 }}"
      >
        Next
      </a>
      {% endif %}
    </div>
    {% endif %}
  </div>
</div>
{% elif query or types or record_types %}
<div class="card">
  <div class="card-body">
    <div class="empty-state">
      <div class="empty-state-icon"><i class="fas fa-search"></i></div>
      <h3>No Results Found</h3>
      <p class="text-muted">Try adjusting your query, category, or record type filters.</p>
    </div>
  </div>
</div>
{% else %}
<div class="card">
  <div class="card-body">
    <div class="empty-state">
      <div class="empty-state-icon"><i class="fas fa-search"></i></div>
      <h3>Enter Search Criteria</h3>
      <p class="text-muted">You can search free text and combine category/record-type filters.</p>
    </div>
  </div>
</div>
{% endif %}
{% endblock %}

{% block extra_css %}
<style>
.filter-grid {
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-sm);
  padding: var(--spacing-sm);
  background: var(--color-gray-700);
  border-radius: var(--radius-sm);
}
.checkbox-label {
  display: inline-flex;
  align-items: center;
  gap: var(--spacing-xs);
  cursor: pointer;
  font-size: 0.875rem;
}
.form-actions {
  display: flex;
  gap: var(--spacing-sm);
}
.facet-row {
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-sm);
}
.facet-chip {
  padding: 0.2rem 0.5rem;
  border-radius: var(--radius-sm);
  background: var(--color-gray-700);
  font-size: 0.8rem;
}
.facet-chip-category {
  background: var(--color-gray-600);
}
.table-container {
  overflow-x: auto;
}
.empty-state {
  text-align: center;
  padding: var(--spacing-2xl);
}
.empty-state-icon {
  font-size: 3rem;
  color: var(--color-gray-500);
  margin-bottom: var(--spacing-md);
}
.pagination-row {
  display: flex;
  justify-content: space-between;
}
.sortable-col {
  cursor: pointer;
  user-select: none;
}
.sortable-col::after {
  content: "\f0dc";
  font-family: "Font Awesome 6 Free";
  font-weight: 900;
  margin-left: var(--spacing-xs);
  font-size: 0.75rem;
  opacity: 0.35;
}
.sortable-col.sort-asc::after {
  content: "\f0de";
  opacity: 1;
}
.sortable-col.sort-desc::after {
  content: "\f0dd";
  opacity: 1;
}
</style>
{% endblock %}

{% block extra_js %}
<script>
function collectValues(selector) {
  return Array.from(document.querySelectorAll(selector + ':checked')).map((elem) => elem.value);
}

function clearFilters() {
  document.getElementById('searchQuery').value = '';
  document.querySelectorAll('.types-filter, .record-type-filter').forEach((elem) => {
    elem.checked = false;
  });
}

function appendHidden(form, name, value) {
  const hidden = document.createElement('input');
  hidden.type = 'hidden';
  hidden.name = name;
  hidden.value = value;
  form.appendChild(hidden);
}

function compareCellValues(aRaw, bRaw) {
  const aText = (aRaw || '').trim().replace(/\s+/g, ' ');
  const bText = (bRaw || '').trim().replace(/\s+/g, ' ');

  const aTimestamp = Date.parse(aText);
  const bTimestamp = Date.parse(bText);
  if (!Number.isNaN(aTimestamp) && !Number.isNaN(bTimestamp)) {
    return aTimestamp - bTimestamp;
  }

  const aNumeric = Number(aText.replace(/,/g, ''));
  const bNumeric = Number(bText.replace(/,/g, ''));
  if (aText !== '' && bText !== '' && !Number.isNaN(aNumeric) && !Number.isNaN(bNumeric)) {
    return aNumeric - bNumeric;
  }

  return aText.localeCompare(bText, undefined, { numeric: true, sensitivity: 'base' });
}

function enableSearchResultSorting() {
  const table = document.querySelector('[data-search-results-table="true"]');
  if (!table) {
    return;
  }

  const body = table.querySelector('tbody');
  if (!body) {
    return;
  }

  let activeSortIndex = null;
  let activeSortDirection = 'asc';
  const sortableHeaders = table.querySelectorAll('th.sortable-col[data-sort-index]');

  sortableHeaders.forEach((header) => {
    header.addEventListener('click', function onHeaderClick() {
      const columnIndex = Number(this.dataset.sortIndex);
      if (Number.isNaN(columnIndex)) {
        return;
      }

      if (activeSortIndex === columnIndex) {
        activeSortDirection = activeSortDirection === 'asc' ? 'desc' : 'asc';
      } else {
        activeSortIndex = columnIndex;
        activeSortDirection = 'asc';
      }

      const rows = Array.from(body.querySelectorAll('tr'));
      rows.sort((rowA, rowB) => {
        const aCell = rowA.cells[columnIndex];
        const bCell = rowB.cells[columnIndex];
        const result = compareCellValues(
          aCell ? aCell.innerText : '',
          bCell ? bCell.innerText : ''
        );
        return activeSortDirection === 'asc' ? result : -result;
      });

      rows.forEach((row) => body.appendChild(row));
      sortableHeaders.forEach((th) => th.classList.remove('sort-asc', 'sort-desc'));
      this.classList.add(activeSortDirection === 'asc' ? 'sort-asc' : 'sort-desc');
    });
  });
}

document.addEventListener('DOMContentLoaded', enableSearchResultSorting);

document.getElementById('searchForm').addEventListener('submit', function onSubmit() {
  this.querySelectorAll('input[name="types"], input[name="record_types"]').forEach((elem) => elem.remove());

  const categories = collectValues('.types-filter');
  const recordTypes = collectValues('.record-type-filter');

  if (categories.length > 0) {
    appendHidden(this, 'types', categories.join(','));
  }
  if (recordTypes.length > 0) {
    appendHidden(this, 'record_types', recordTypes.join(','));
  }
});

async function exportResults(format) {
  const query = document.getElementById('searchQuery').value;
  const categories = collectValues('.types-filter');
  const recordTypes = collectValues('.record-type-filter');

  const payload = {
    search: {
      query: query,
      categories: categories,
      record_types: recordTypes,
      page: 1,
      page_size: 500,
      max_scan: 10000,
      sort_by: 'timestamp',
      sort_order: 'desc'
    },
    format: format,
    include_metadata: true,
    max_export_rows: 10000
  };

  try {
    const response = await fetch('/api/v1/search/v2/export', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });

    if (!response.ok) {
      throw new Error('Export failed with status ' + response.status);
    }

    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    const contentDisposition = response.headers.get('Content-Disposition') || '';
    const fileNameMatch = contentDisposition.match(/filename="([^"]+)"/);
    link.href = url;
    link.download = fileNameMatch ? fileNameMatch[1] : ('bloom_search_v2.' + format);
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(url);
  } catch (error) {
    console.error(error);
    alert('Export failed. Please try again.');
  }
}
</script>
{% endblock %}
