{% extends "base.html" %}

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

{% block content %}
<div class="card">
  <div class="card-header">
    <div class="card-title" data-i18n="reports.title">Activity Reports</div>
    <button class="btn btn-sm btn-primary" id="btn-generate" data-i18n="reports.generate">Generate Report</button>
  </div>

  <!-- Filters -->
  <div class="filter-bar" style="display:flex; gap:.75rem; flex-wrap:wrap; padding:.75rem 1rem; border-bottom:1px solid var(--border);">
    <select id="filter-period" class="input" style="width:auto; min-width:120px;">
      <option value="" data-i18n="reports.periodType">Period</option>
      <option value="daily" data-i18n="reports.daily">Daily</option>
      <option value="weekly" data-i18n="reports.weekly">Weekly</option>
      <option value="monthly" data-i18n="reports.monthly">Monthly</option>
    </select>
    <input type="text" id="filter-user" class="input" placeholder="Target User ID" data-i18n-placeholder="reports.targetUser" style="width:auto; min-width:160px;" />
    <button class="btn btn-sm btn-secondary" id="btn-filter" data-i18n="common.refresh">Refresh</button>
  </div>

  <!-- Table -->
  <div id="reports-table">
    <div class="loading-center"><div class="spinner"></div></div>
  </div>

  <!-- Pagination -->
  <div class="pagination" id="reports-pagination" style="display:none; padding:.75rem 1rem; border-top:1px solid var(--border);">
    <button class="btn btn-sm" id="btn-prev" data-i18n="common.prev">Prev</button>
    <span id="page-info" class="page-info"></span>
    <button class="btn btn-sm" id="btn-next" data-i18n="common.next">Next</button>
  </div>
</div>

<!-- Generate modal -->
<div class="modal-overlay" id="generate-overlay" hidden>
  <div class="modal" style="max-width:480px;">
    <div class="modal-header">
      <h2 class="modal-title" data-i18n="reports.generate">Generate Report</h2>
      <button class="modal-close" id="generate-close" aria-label="Close">&times;</button>
    </div>
    <div class="modal-body">
      <div class="form-group">
        <label data-i18n="reports.targetUser">Target User</label>
        <input type="text" id="gen-user" class="input" required />
      </div>
      <div class="form-group">
        <label data-i18n="reports.periodType">Period</label>
        <select id="gen-period" class="input">
          <option value="daily" data-i18n="reports.daily">Daily</option>
          <option value="weekly" data-i18n="reports.weekly">Weekly</option>
          <option value="monthly" data-i18n="reports.monthly">Monthly</option>
        </select>
      </div>
      <div class="form-group">
        <label data-i18n="reports.periodStart">Start Date</label>
        <input type="date" id="gen-start" class="input" required />
      </div>
      <div class="form-actions" style="display:flex; gap:.5rem; justify-content:flex-end; margin-top:1rem;">
        <button class="btn btn-secondary" id="gen-cancel" data-i18n="common.cancel">Cancel</button>
        <button class="btn btn-primary" id="gen-submit" data-i18n="reports.generate">Generate</button>
      </div>
    </div>
  </div>
</div>

<!-- Detail modal -->
<div class="modal-overlay" id="detail-overlay" hidden>
  <div class="modal" style="max-width:720px;">
    <div class="modal-header">
      <h2 class="modal-title" data-i18n="reports.title">Report Detail</h2>
      <button class="modal-close" id="detail-close" aria-label="Close">&times;</button>
    </div>
    <div class="modal-body" id="detail-body">
      <div class="loading-center"><div class="spinner"></div></div>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script type="module">
import { api } from '/static/js/api.js';
import { t } from '/static/js/i18n.js';

const PAGE_SIZE = 20;
let currentPage = 0;

// --- Helpers ---
function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }

// --- Load reports ---
async function loadReports() {
  const period = document.getElementById('filter-period').value;
  const user = document.getElementById('filter-user').value.trim();
  const params = new URLSearchParams({ limit: PAGE_SIZE, offset: currentPage * PAGE_SIZE });
  if (period) params.set('period_type', period);
  if (user) params.set('target_user_id', user);

  const res = await api.get('/api/reports?' + params.toString());
  const container = document.getElementById('reports-table');

  if (!res?.ok || !res.data?.items?.length) {
    container.innerHTML = `<div class="empty-state" style="padding:2rem; text-align:center; color:var(--text-secondary);" data-i18n="reports.noReports">${t('reports.noReports') || 'No reports found'}</div>`;
    document.getElementById('reports-pagination').style.display = 'none';
    return;
  }

  const items = res.data.items;
  const total = res.data.total || 0;
  const totalPages = Math.ceil(total / PAGE_SIZE);

  let html = `<table class="data-table"><thead><tr>
    <th>ID</th>
    <th data-i18n="reports.targetUser">${t('reports.targetUser') || 'Target User'}</th>
    <th data-i18n="reports.periodType">${t('reports.periodType') || 'Period'}</th>
    <th data-i18n="reports.periodStart">${t('reports.periodStart') || 'Start'}</th>
    <th data-i18n="reports.traceCount">${t('reports.traceCount') || 'Traces'}</th>
    <th data-i18n="reports.totalCost">${t('reports.totalCost') || 'Cost'}</th>
    <th data-i18n="common.actions">${t('common.actions') || 'Actions'}</th>
  </tr></thead><tbody>`;

  for (const r of items) {
    html += `<tr>
      <td>${r.id}</td>
      <td>${esc(r.target_user_id)}</td>
      <td>${esc(r.period_type)}</td>
      <td>${esc(r.period_start)}</td>
      <td>${r.trace_count}</td>
      <td>${(r.total_cost || 0).toFixed(4)}</td>
      <td>
        <button class="btn btn-sm" data-view="${r.id}" data-i18n="common.view">${t('common.view') || 'View'}</button>
        <button class="btn btn-sm btn-danger" data-del="${r.id}" data-i18n="common.delete">${t('common.delete') || 'Delete'}</button>
      </td>
    </tr>`;
  }
  html += '</tbody></table>';
  container.innerHTML = html;

  // Pagination
  const pag = document.getElementById('reports-pagination');
  pag.style.display = totalPages > 1 ? 'flex' : 'none';
  document.getElementById('page-info').textContent = `${currentPage + 1} / ${totalPages}`;
  document.getElementById('btn-prev').disabled = currentPage === 0;
  document.getElementById('btn-next').disabled = currentPage >= totalPages - 1;

  // Event delegation
  container.querySelectorAll('[data-view]').forEach(btn => {
    btn.onclick = () => showDetail(btn.dataset.view);
  });
  container.querySelectorAll('[data-del]').forEach(btn => {
    btn.onclick = () => deleteReport(btn.dataset.del);
  });
}

// --- Detail ---
async function showDetail(id) {
  document.getElementById('detail-overlay').hidden = false;
  const body = document.getElementById('detail-body');
  body.innerHTML = '<div class="loading-center"><div class="spinner"></div></div>';

  const res = await api.get(`/api/reports/${id}`);
  if (!res?.ok) { body.innerHTML = '<p>Error loading report</p>'; return; }

  const r = res.data;
  const summary = r.summary || {};
  const sessions = r.sessions || [];
  const modelUsage = r.model_usage || {};
  const timeline = r.timeline || [];

  let html = `<div style="display:grid; gap:1rem;">`;

  // Summary card
  html += `<div class="card" style="padding:1rem;">
    <h3 style="margin:0 0 .5rem;" data-i18n="reports.title">Summary</h3>
    <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(140px,1fr)); gap:.5rem;">
      <div><strong>${t('reports.traceCount') || 'Traces'}:</strong> ${summary.count || 0}</div>
      <div><strong>${t('reports.totalCost') || 'Cost'}:</strong> $${(summary.total_cost || 0).toFixed(4)}</div>
      <div><strong>Error Rate:</strong> ${((summary.error_rate || 0) * 100).toFixed(1)}%</div>
      <div><strong>Avg Latency:</strong> ${summary.avg_latency_ms ? summary.avg_latency_ms.toFixed(0) + 'ms' : 'N/A'}</div>
    </div>
  </div>`;

  // LLM Analysis card
  const analysis = r.llm_analysis || '';
  if (analysis) {
    html += `<div class="card" style="padding:1rem;">
      <h3 style="margin:0 0 .5rem;" data-i18n="reports.llmAnalysis">${t('reports.llmAnalysis') || 'AI Deep Analysis'}</h3>
      <div style="white-space:pre-wrap; line-height:1.6; border-left:3px solid var(--accent); padding-left:1rem; color:var(--text-primary);">
        ${esc(analysis)}
      </div>
    </div>`;
  }

  // Sessions
  if (sessions.length) {
    html += `<div class="card" style="padding:1rem;">
      <h3 style="margin:0 0 .5rem;" data-i18n="reports.sessions">Sessions</h3>
      <table class="data-table"><thead><tr>
        <th>Session</th><th>Traces</th><th>Errors</th><th>Cost</th><th data-i18n="reports.activitySummary">Activity Summary</th>
      </tr></thead><tbody>`;
    for (const s of sessions.slice(0, 20)) {
      const summary = s.activity_summary || '';
      html += `<tr>
        <td style="font-size:.85em;word-break:break-all;max-width:180px;">${esc(s.session_id)}</td>
        <td>${s.trace_count}</td>
        <td>${s.error_count || 0}</td>
        <td>${(s.total_cost || 0).toFixed(4)}</td>
        <td style="font-size:.85em;white-space:pre-wrap;max-width:500px;">${esc(summary)}</td>
      </tr>`;
    }
    html += '</tbody></table></div>';
  }

  // Model usage
  const models = Object.values(modelUsage);
  if (models.length) {
    html += `<div class="card" style="padding:1rem;">
      <h3 style="margin:0 0 .5rem;" data-i18n="reports.modelUsage">Model Usage</h3>
      <table class="data-table"><thead><tr>
        <th>Model</th><th>Calls</th><th>Input Tokens</th><th>Output Tokens</th><th>Cost</th>
      </tr></thead><tbody>`;
    for (const m of models) {
      html += `<tr>
        <td>${esc(m.model)}</td>
        <td>${m.call_count}</td>
        <td>${(m.input_tokens || 0).toLocaleString()}</td>
        <td>${(m.output_tokens || 0).toLocaleString()}</td>
        <td>${(m.total_cost || 0).toFixed(4)}</td>
      </tr>`;
    }
    html += '</tbody></table></div>';
  }

  // Timeline
  if (timeline.length) {
    html += `<div class="card" style="padding:1rem;">
      <h3 style="margin:0 0 .5rem;" data-i18n="reports.timeline">Timeline</h3>
      <div style="display:flex; gap:2px; align-items:end; height:60px;">`;
    const maxT = Math.max(...timeline.map(t => t.trace_count || 0), 1);
    for (const t of timeline) {
      const h = Math.max(2, ((t.trace_count || 0) / maxT) * 56);
      const label = t.hour !== undefined ? t.hour + 'h' : ('D' + (t.day_index + 1));
      html += `<div title="${label}: ${t.trace_count} traces" style="flex:1; background:var(--accent); border-radius:2px 2px 0 0; height:${h}px;"></div>`;
    }
    html += `</div></div>`;
  }

  html += '</div>';
  body.innerHTML = html;
}

// --- Delete ---
async function deleteReport(id) {
  if (!confirm(t('reports.deleteConfirm') || 'Delete this report?')) return;
  await api.del(`/api/reports/${id}`);
  loadReports();
}

// --- Generate ---
function openGenerate() {
  document.getElementById('generate-overlay').hidden = false;
  const today = new Date().toISOString().split('T')[0];
  document.getElementById('gen-start').value = today;
}

async function submitGenerate() {
  const userId = document.getElementById('gen-user').value.trim();
  const period = document.getElementById('gen-period').value;
  const start = document.getElementById('gen-start').value;
  if (!userId || !start) return;

  const btn = document.getElementById('gen-submit');
  btn.disabled = true;
  btn.textContent = t('reports.generating') || 'Generating...';

  try {
    await api.post('/api/reports/generate', {
      target_user_id: userId,
      period_type: period,
      period_start: start,
    });
    document.getElementById('generate-overlay').hidden = true;
    loadReports();
  } catch (e) {
    alert('Error: ' + (e.message || e));
  } finally {
    btn.disabled = false;
    btn.textContent = t('reports.generate') || 'Generate';
  }
}

// --- Events ---
document.getElementById('btn-generate').onclick = openGenerate;
document.getElementById('gen-submit').onclick = submitGenerate;
document.getElementById('gen-cancel').onclick = () => { document.getElementById('generate-overlay').hidden = true; };
document.getElementById('generate-close').onclick = () => { document.getElementById('generate-overlay').hidden = true; };
document.getElementById('detail-close').onclick = () => { document.getElementById('detail-overlay').hidden = true; };
document.getElementById('btn-filter').onclick = () => { currentPage = 0; loadReports(); };
document.getElementById('btn-prev').onclick = () => { if (currentPage > 0) { currentPage--; loadReports(); } };
document.getElementById('btn-next').onclick = () => { currentPage++; loadReports(); };

// Click overlay to close
document.getElementById('generate-overlay').onclick = (e) => { if (e.target.id === 'generate-overlay') e.target.hidden = true; };
document.getElementById('detail-overlay').onclick = (e) => { if (e.target.id === 'detail-overlay') e.target.hidden = true; };

// Initial load
loadReports();
</script>
{% endblock %}
