{% extends "base.html" %}

{% block title %}Datasets — Langfuse Lens{% endblock %}
{% block page_title %}<span data-i18n="datasets.title">Langfuse Datasets</span>{% endblock %}

{% block topbar_actions %}
<button class="btn btn-sm btn-primary" id="btn-new-dataset" data-i18n="datasets.newDataset">+ New Dataset</button>
{% endblock %}

{% block content %}
<div class="card">
  <div class="card-header">
    <div>
      <div class="card-title" data-i18n="datasets.datasetManagement">Dataset Management</div>
      <div class="card-subtitle" data-i18n="datasets.datasetManagementDesc">Manage Langfuse datasets and import from traces</div>
    </div>
    <button class="btn btn-sm btn-secondary" id="btn-refresh" data-i18n="common.refresh">Refresh</button>
  </div>
  <div id="datasets-list">
    <div class="loading-center"><div class="spinner"></div></div>
  </div>
</div>

<div class="card mt-20 hidden" id="dataset-detail-panel">
  <div class="card-header">
    <div class="card-title" id="dataset-detail-name" data-i18n="datasets.datasetDetail">Dataset Detail</div>
    <div class="btn-group">
      <button class="btn btn-sm btn-primary" id="btn-upsert-items" data-i18n="datasets.upsertItems">Upsert Items</button>
      <button class="btn btn-sm btn-primary" id="btn-import-traces" data-i18n="datasets.importFromTraces">Import from Traces</button>
      <button class="btn btn-sm btn-secondary" id="btn-close-dataset" data-i18n="common.close">Close</button>
    </div>
  </div>
  <div id="dataset-detail-content"></div>
</div>
{% endblock %}

{% block scripts %}
<script type="module">
import { api } from '/static/js/api.js';
import { toast, formatDate, showLoading, showEmpty, escapeHtml, openModal, closeModal, t } from '/static/js/common.js';

let currentDatasetId = null;

async function loadDatasets() {
  const el = document.getElementById('datasets-list');
  showLoading(el);

  try {
    const data = await api.get('/api/langfuse/datasets');
    const items = data.datasets || data.items || data || [];
    if (!Array.isArray(items) || items.length === 0) {
      showEmpty(el, t('datasets.noDatasetsFound'));
      return;
    }
    el.innerHTML = `
      <div class="table-wrap">
        <table>
          <thead><tr><th>${t('common.name')}</th><th>${t('datasets.description')}</th><th>${t('datasets.items')}</th><th>${t('common.actions')}</th></tr></thead>
          <tbody>
            ${items.map(d => `
              <tr>
                <td><a href="#" class="view-dataset" data-id="${escapeHtml(d.id || d.dataset_id || d.name)}" data-name="${escapeHtml(d.name)}">${escapeHtml(d.name)}</a></td>
                <td class="text-sm text-muted truncate">${escapeHtml(d.description || '-')}</td>
                <td class="td-mono">${d.item_count ?? d.items?.length ?? '-'}</td>
                <td class="td-actions">
                  <button class="btn btn-sm btn-ghost view-dataset" data-id="${escapeHtml(d.id || d.dataset_id || d.name)}" data-name="${escapeHtml(d.name)}">${t('common.view')}</button>
                </td>
              </tr>
            `).join('')}
          </tbody>
        </table>
      </div>
    `;
    bindEvents();
  } catch (err) {
    showEmpty(el, `${t('common.error')}: ${err.message}`);
  }
}

function bindEvents() {
  document.querySelectorAll('.view-dataset').forEach(el => {
    el.addEventListener('click', (e) => { e.preventDefault(); viewDataset(el.dataset.id, el.dataset.name); });
  });
}

async function viewDataset(id, name) {
  currentDatasetId = id;
  const panel = document.getElementById('dataset-detail-panel');
  const content = document.getElementById('dataset-detail-content');
  panel.classList.remove('hidden');
  showLoading(content);
  document.getElementById('dataset-detail-name').textContent = name || id;

  try {
    const data = await api.get('/api/langfuse/datasets');
    const ds = (data.datasets || data.items || data || []).find(d => (d.id || d.dataset_id || d.name) === id);

    content.innerHTML = `
      <div class="detail-row"><div class="detail-label">ID</div><div class="detail-value td-mono">${escapeHtml(id)}</div></div>
      <div class="detail-row"><div class="detail-label">${t('common.name')}</div><div class="detail-value">${escapeHtml(ds?.name || name)}</div></div>
      <div class="detail-row"><div class="detail-label">${t('datasets.description')}</div><div class="detail-value">${escapeHtml(ds?.description || '-')}</div></div>
      ${ds?.metadata && Object.keys(ds.metadata).length > 0 ? `
        <div class="section-title mt-16">${t('datasets.metadata')}</div>
        <div class="pre-wrap">${escapeHtml(JSON.stringify(ds.metadata, null, 2))}</div>
      ` : ''}
    `;
    panel.scrollIntoView({ behavior: 'smooth' });
  } catch (err) {
    content.innerHTML = `<p class="text-muted">${err.message}</p>`;
  }
}

// New dataset
document.getElementById('btn-new-dataset')?.addEventListener('click', () => {
  openModal(t('datasets.createDataset'), `
    <form id="new-ds-form">
      <div class="form-group"><label class="form-label">${t('common.name')}</label><input class="form-input" id="nd-name" required placeholder="${t('datasets.datasetName')}" /></div>
      <div class="form-group"><label class="form-label">${t('datasets.description')}</label><input class="form-input" id="nd-desc" placeholder="${t('datasets.datasetDesc')}" /></div>
      <div class="modal-footer" style="padding:12px 0 0"><button type="submit" class="btn btn-primary">${t('common.create')}</button></div>
    </form>
  `);
  document.getElementById('new-ds-form')?.addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
      await api.post('/api/langfuse/datasets', {
        name: document.getElementById('nd-name').value,
        description: document.getElementById('nd-desc').value,
      });
      closeModal(); toast(t('datasets.datasetCreated'), 'success'); loadDatasets();
    } catch (err) { toast(err.message, 'error'); }
  });
});

// Upsert items
document.getElementById('btn-upsert-items')?.addEventListener('click', () => {
  if (!currentDatasetId) return;
  openModal(t('datasets.upsertItems'), `
    <form id="upsert-form">
      <div class="form-group"><label class="form-label">${t('datasets.itemsJsonArray')}</label>
        <textarea class="form-textarea" id="ui-items" rows="8" placeholder='[{"input": "hello", "expected_output": "world"}]' required></textarea>
      </div>
      <div class="modal-footer" style="padding:12px 0 0"><button type="submit" class="btn btn-primary">${t('datasets.upsert')}</button></div>
    </form>
  `);
  document.getElementById('upsert-form')?.addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
      const items = JSON.parse(document.getElementById('ui-items').value);
      await api.post(`/api/langfuse/datasets/${currentDatasetId}/items:upsert`, { items });
      closeModal(); toast(t('datasets.itemsUpserted'), 'success');
    } catch (err) { toast(err.message, 'error'); }
  });
});

// Import from traces
document.getElementById('btn-import-traces')?.addEventListener('click', () => {
  if (!currentDatasetId) return;
  openModal(t('datasets.importFromTraces'), `
    <form id="import-form">
      <div class="form-group"><label class="form-label">${t('datasets.traceIdsComma')}</label>
        <textarea class="form-textarea" id="it-traces" rows="4" placeholder="trace_abc123, trace_def456" required></textarea>
      </div>
      <div class="form-group"><label class="form-label">${t('datasets.itemTemplateOptional')}</label>
        <textarea class="form-textarea" id="it-template" rows="4" placeholder='{"metadata": {"source": "trace"}}'></textarea>
      </div>
      <div class="modal-footer" style="padding:12px 0 0"><button type="submit" class="btn btn-primary">${t('datasets.import')}</button></div>
    </form>
  `);
  document.getElementById('import-form')?.addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
      const traceIds = document.getElementById('it-traces').value.split(',').map(s=>s.trim()).filter(Boolean);
      let template = {};
      const tmplText = document.getElementById('it-template').value.trim();
      if (tmplText) template = JSON.parse(tmplText);
      await api.post(`/api/langfuse/datasets/${currentDatasetId}/import-from-traces`, { trace_ids: traceIds, item_template: template });
      closeModal(); toast(t('datasets.importedFromTraces'), 'success');
    } catch (err) { toast(err.message, 'error'); }
  });
});

document.getElementById('btn-close-dataset')?.addEventListener('click', () => {
  document.getElementById('dataset-detail-panel').classList.add('hidden');
});
document.getElementById('btn-refresh')?.addEventListener('click', loadDatasets);

loadDatasets();
</script>
{% endblock %}
