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

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

{% block content %}
<div class="page-header">
  <div>
    <h1>Administration</h1>
    <p class="text-muted">System settings, user preferences, and integrations</p>
  </div>
  <div class="page-actions">
  </div>
</div>

{% if saved %}
<div class="card" style="margin-bottom: var(--spacing-md); border-color: var(--color-success);">
  <div class="card-body" style="display: flex; align-items: center; gap: var(--spacing-sm);">
    <i class="fas fa-check-circle" style="color: var(--color-success);"></i>
    <span>Preferences saved.</span>
  </div>
</div>
{% endif %}

{% if zebra_started %}
<div class="card" style="margin-bottom: var(--spacing-md); border-color: var(--color-success);">
  <div class="card-body" style="display: flex; align-items: center; gap: var(--spacing-sm);">
    <i class="fas fa-check-circle" style="color: var(--color-success);"></i>
    <span>zebra_day start command launched in background mode.</span>
  </div>
</div>
{% endif %}

{% if zebra_running %}
<div class="card" style="margin-bottom: var(--spacing-md); border-color: var(--color-info);">
  <div class="card-body" style="display: flex; align-items: center; gap: var(--spacing-sm);">
    <i class="fas fa-info-circle" style="color: var(--color-info);"></i>
    <span>zebra_day service is already running.</span>
  </div>
</div>
{% endif %}

{% if zebra_error %}
<div class="card" style="margin-bottom: var(--spacing-md); border-color: var(--color-warning);">
  <div class="card-body" style="display: flex; align-items: center; gap: var(--spacing-sm);">
    <i class="fas fa-exclamation-triangle" style="color: var(--color-warning);"></i>
    <span>
      {% if zebra_error == "command_not_found" %}
      Could not find <code>zday</code> or <code>zday_start</code> on this host.
      {% elif zebra_error == "launch_failed" %}
      Failed to launch zebra_day service in background mode.
      {% elif zebra_error == "start_failed" %}
      zebra_day service start command returned an error.
      {% else %}
      zebra_day service start failed.
      {% endif %}
    </span>
  </div>
</div>
{% endif %}

<div class="grid grid-2">
  <!-- User Preferences -->
  <div class="card">
    <div class="card-header">
      <h3 class="card-title"><i class="fas fa-user-cog"></i> User Preferences</h3>
    </div>
    <div class="card-body">
      <form action="/admin" method="POST" id="preferences-form">
        <div class="form-group">
          <label class="form-label">Default Print Lab</label>
          <select class="form-select" name="print_lab">
            {% for lab in printer_info.get('print_lab', []) %}
            <option value="{{ lab }}" {% if user_data.get('print_lab') == lab %}selected{% endif %}>{{ lab }}</option>
            {% endfor %}
          </select>
        </div>

        <div class="form-group">
          <label class="form-label">Default Printer</label>
          <select class="form-select" name="printer_name">
            {% for printer in printer_info.get('printer_name', []) %}
            <option value="{{ printer }}" {% if user_data.get('printer_name') == printer %}selected{% endif %}>{{ printer }}</option>
            {% endfor %}
          </select>
        </div>

        <div class="form-group">
          <label class="form-label">Label Style</label>
          <select class="form-select" name="label_zpl_style">
            {% for style in printer_info.get('label_zpl_style', []) %}
            <option value="{{ style }}" {% if user_data.get('label_zpl_style') == style %}selected{% endif %}>{{ style }}</option>
            {% endfor %}
          </select>
        </div>

        <div class="form-group">
          <label class="form-label">UI Theme</label>
          <select class="form-select" name="ui_theme" id="theme-selector">
            <option value="dark">Dark</option>
            <option value="light">Light</option>
          </select>
          <div class="form-text text-muted" style="font-size: 0.75rem; margin-top: var(--spacing-xs);">Theme is saved automatically to your browser</div>
        </div>

        <button type="submit" class="btn btn-primary">
          <i class="fas fa-save"></i> Save Preferences
        </button>
      </form>
    </div>
  </div>

  <!-- Quick Links -->
  <div class="card">
    <div class="card-header">
      <h3 class="card-title"><i class="fas fa-link"></i> Quick Links</h3>
    </div>
  <div class="card-body">
      <div class="list-group">
        <a href="/object_templates_summary" class="list-item">
          <span><i class="fas fa-cubes"></i> Object Templates</span>
          <i class="fas fa-chevron-right text-muted"></i>
        </a>
        <a href="/database_statistics" class="list-item">
          <span><i class="fas fa-chart-bar"></i> Database Statistics</span>
          <i class="fas fa-chevron-right text-muted"></i>
        </a>
        <a href="/user_home" class="list-item">
          <span><i class="fas fa-user"></i> User Home</span>
          <i class="fas fa-chevron-right text-muted"></i>
        </a>
        <a href="/admin/metrics" class="list-item">
          <span><i class="fas fa-chart-line"></i> TapDB Metrics</span>
          <i class="fas fa-chevron-right text-muted"></i>
        </a>
      </div>
    </div>
  </div>
</div>

<h2 class="section-title" style="margin-top: var(--spacing-xl);"><i class="fas fa-key"></i> API Token Administration</h2>
<div class="grid grid-2">
  <div class="card">
    <div class="card-header">
      <h3 class="card-title"><i class="fas fa-users-cog"></i> API Access Users</h3>
    </div>
    <div class="card-body">
      <form id="api-access-user-form" class="input-group" style="margin-bottom: var(--spacing-md);">
        <input type="text" id="api-access-user-id" class="form-input" placeholder="User ID (email, subject, or service ID)" style="flex: 1;">
        <button type="submit" class="btn btn-primary btn-sm">Add API User</button>
      </form>
      <div id="api-access-user-status" class="text-sm text-muted" style="margin-bottom: var(--spacing-sm);"></div>
      <div class="table-container">
        <table class="table">
          <thead>
            <tr>
              <th>User ID</th>
              <th>Active</th>
            </tr>
          </thead>
          <tbody id="api-access-users-body">
            <tr><td colspan="2" class="text-muted">Loading...</td></tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div class="card">
    <div class="card-header">
      <h3 class="card-title"><i class="fas fa-key"></i> Issue Token</h3>
    </div>
    <div class="card-body">
      <form id="issue-token-form">
        <div class="form-group">
          <label class="form-label">Token Owner (API user)</label>
          <select id="issue-token-user-id" class="form-select" required>
            <option value="">Select API user</option>
          </select>
        </div>
        <div class="form-group">
          <label class="form-label">Token Name</label>
          <input type="text" id="issue-token-name" class="form-input" required placeholder="e.g. bloom-admin-cli">
        </div>
        <div class="form-group">
          <label class="form-label">Scope</label>
          <select id="issue-token-scope" class="form-select">
            <option value="internal_ro">internal_ro</option>
            <option value="internal_rw">internal_rw</option>
          </select>
        </div>
        <div class="form-group">
          <label class="form-label">Expires In (days)</label>
          <input type="number" id="issue-token-days" class="form-input" value="30" min="1" max="3650">
        </div>
        <button type="submit" class="btn btn-primary btn-sm">Issue Token</button>
      </form>
      <div id="issue-token-result" class="text-sm text-muted" style="margin-top: var(--spacing-md);"></div>
    </div>
  </div>
</div>

<div class="grid grid-2" style="margin-top: var(--spacing-md);">
  <div class="card">
    <div class="card-header">
      <h3 class="card-title"><i class="fas fa-plug"></i> Enable Atlas API</h3>
    </div>
    <div class="card-body">
      <form id="atlas-api-user-form" class="input-group" style="margin-bottom: var(--spacing-md);">
        <input type="text" id="atlas-api-user-id" class="form-input" placeholder="User ID to grant ENABLE_ATLAS_API" style="flex: 1;">
        <button type="submit" class="btn btn-primary btn-sm">Enable</button>
      </form>
      <div id="atlas-api-user-status" class="text-sm text-muted" style="margin-bottom: var(--spacing-sm);"></div>
      <div class="table-container">
        <table class="table">
          <thead>
            <tr>
              <th>User ID</th>
              <th>Active</th>
            </tr>
          </thead>
          <tbody id="atlas-api-users-body">
            <tr><td colspan="2" class="text-muted">Loading...</td></tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div class="card">
    <div class="card-header">
      <h3 class="card-title"><i class="fas fa-dna"></i> Enable Ursa API</h3>
    </div>
    <div class="card-body">
      <form id="ursa-api-user-form" class="input-group" style="margin-bottom: var(--spacing-md);">
        <input type="text" id="ursa-api-user-id" class="form-input" placeholder="User ID to grant ENABLE_URSA_API" style="flex: 1;">
        <button type="submit" class="btn btn-primary btn-sm">Enable</button>
      </form>
      <div id="ursa-api-user-status" class="text-sm text-muted" style="margin-bottom: var(--spacing-sm);"></div>
      <div class="table-container">
        <table class="table">
          <thead>
            <tr>
              <th>User ID</th>
              <th>Active</th>
            </tr>
          </thead>
          <tbody id="ursa-api-users-body">
            <tr><td colspan="2" class="text-muted">Loading...</td></tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<div class="card" style="margin-top: var(--spacing-md);">
  <div class="card-header">
    <h3 class="card-title"><i class="fas fa-users"></i> Group Membership Management</h3>
  </div>
  <div class="card-body">
    <div class="grid grid-2" style="margin-bottom: var(--spacing-md);">
      <div class="form-group">
        <label class="form-label">Group</label>
        <select id="group-management-select" class="form-select">
          <option value="">Loading groups...</option>
        </select>
      </div>
      <div class="form-group">
        <label class="form-label">Add User To Selected Group</label>
        <form id="group-management-add-form" class="input-group">
          <input type="text" id="group-management-user-id" class="form-input" placeholder="User ID (email, subject, or service ID)" style="flex: 1;">
          <button type="submit" class="btn btn-primary btn-sm">Add</button>
        </form>
      </div>
    </div>
    <div id="group-management-status" class="text-sm text-muted" style="margin-bottom: var(--spacing-sm);"></div>
    <div class="table-container">
      <table class="table">
        <thead>
          <tr>
            <th>User ID</th>
            <th>Active</th>
            <th></th>
          </tr>
        </thead>
        <tbody id="group-management-members-body">
          <tr><td colspan="3" class="text-muted">Select a group to view members</td></tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="card" style="margin-top: var(--spacing-lg);">
  <div class="card-header">
    <h3 class="card-title"><i class="fas fa-fingerprint"></i> Issued Tokens</h3>
  </div>
  <div class="card-body">
    <div class="table-container">
      <table class="table">
        <thead>
          <tr>
            <th>Token Name</th>
            <th>User ID</th>
            <th>Prefix</th>
            <th>Status</th>
            <th>Expires</th>
            <th></th>
          </tr>
        </thead>
        <tbody id="admin-tokens-body">
          <tr><td colspan="6" class="text-muted">Loading...</td></tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- External Integrations -->
<h2 class="section-title" style="margin-top: var(--spacing-xl);"><i class="fas fa-plug"></i> External Integrations</h2>
<div class="grid grid-2">
  <!-- zebra_day - Printer Management -->
  <div class="card integration-card">
    <div class="card-header">
      <h3 class="card-title">
        <i class="fas fa-print"></i> zebra_day
        <span class="badge {% if dependency_info.zebra_day.status == 'available' %}badge-success{% else %}badge-warning{% endif %}">
          {{ dependency_info.zebra_day.version }}
        </span>
      </h3>
    </div>
    <div class="card-body">
      <p class="text-muted">{{ dependency_info.zebra_day.description }}</p>
      {% if dependency_info.zebra_day.admin_url %}
      <div class="integration-actions">
        <a href="{{ dependency_info.zebra_day.admin_url }}" target="_blank" class="btn btn-outline btn-sm">
          <i class="fas fa-external-link-alt"></i> Open Admin Interface
        </a>
        <form action="/admin/zebra/start" method="POST" style="display: inline;">
          <button type="submit" class="btn btn-primary btn-sm">
            <i class="fas fa-play"></i> Start Zebra Service
          </button>
        </form>
        <span class="text-sm text-muted">Port 8118</span>
      </div>
      {% endif %}
    </div>
  </div>

  <!-- Carrier Tracking -->
  <div class="card integration-card">
    <div class="card-header">
      <h3 class="card-title">
        <i class="fas fa-truck"></i> daylily-carrier-tracking
        <span class="badge {% if dependency_info.carrier_tracking.status == 'available' %}badge-success{% else %}badge-warning{% endif %}">
          {{ dependency_info.carrier_tracking.version }}
        </span>
      </h3>
    </div>
    <div class="card-body">
      <p class="text-muted">{{ dependency_info.carrier_tracking.description }}</p>
      <div class="tracking-form">
        <form id="tracking-form" onsubmit="trackPackage(event)">
          <div class="input-group" style="gap: var(--spacing-sm);">
            <select id="tracking-carrier" class="form-select" style="width: 120px;">
              <option value="FedEx">FedEx</option>
              <option value="UPS">UPS</option>
              <option value="USPS">USPS</option>
              <option value="Other">Other</option>
            </select>
            <input type="text" id="tracking-number" class="form-input" placeholder="Enter tracking number..." style="flex: 1;">
            <button type="submit" class="btn btn-primary btn-sm">
              <i class="fas fa-search"></i> Track
            </button>
          </div>
        </form>
        <div id="tracking-result" class="tracking-result" style="display: none;"></div>
      </div>
    </div>
  </div>

  <!-- daylily-tapdb -->
  <div class="card integration-card">
    <div class="card-header">
      <h3 class="card-title">
        <i class="fas fa-database"></i> daylily-tapdb
        <span class="badge {% if dependency_info.tapdb.status == 'available' %}badge-success{% else %}badge-warning{% endif %}">
          {{ dependency_info.tapdb.version }}
        </span>
      </h3>
    </div>
  <div class="card-body">
      <p class="text-muted">{{ dependency_info.tapdb.description }}</p>
      <div class="info-grid">
        <div class="info-row">
          <span class="info-key">Host:</span>
          <span class="info-val font-mono">{{ db_info.host }}:{{ db_info.port }}</span>
        </div>
        <div class="info-row">
          <span class="info-key">Database:</span>
          <span class="info-val font-mono">{{ db_info.database }}</span>
        </div>
        <div class="info-row">
          <span class="info-key">User:</span>
          <span class="info-val font-mono">{{ db_info.user }}</span>
        </div>
      </div>

      <div class="integration-actions" style="margin-top: var(--spacing-md);">
        <a href="/admin/metrics" class="btn btn-outline btn-sm">
          <i class="fas fa-chart-line"></i> DB Metrics
        </a>
        {% if tapdb_metrics_summary %}
          <span class="text-sm text-muted">
            p95 {{ "%.1f"|format(tapdb_metrics_summary.summary.p95_ms) }}ms
            ({{ tapdb_metrics_summary.summary.count }} rows)
          </span>
        {% endif %}
      </div>
  </div>
  </div>

  <!-- Cognito Auth -->
  <div class="card integration-card">
    <div class="card-header">
      <h3 class="card-title">
        <i class="fas fa-key"></i> AWS Cognito
        <span class="badge {% if cognito_info.status == 'configured' %}badge-success{% else %}badge-warning{% endif %}">
          {{ cognito_info.status }}
        </span>
      </h3>
    </div>
    <div class="card-body">
      <p class="text-muted">OAuth2 authentication via AWS Cognito</p>
      {% if cognito_info.status == 'configured' %}
      <div class="info-grid">
        <div class="info-row">
          <span class="info-key">Region:</span>
          <span class="info-val font-mono">{{ cognito_info.region }}</span>
        </div>
        <div class="info-row">
          <span class="info-key">User Pool:</span>
          <span class="info-val font-mono">{{ cognito_info.user_pool_id }}</span>
        </div>
        <div class="info-row">
          <span class="info-key">Client ID:</span>
          <span class="info-val font-mono">{{ cognito_info.client_id }}</span>
        </div>
      </div>
      {% else %}
      <p class="text-warning"><i class="fas fa-exclamation-triangle"></i> {{ cognito_info.message }}</p>
      {% endif %}
    </div>
  </div>

  <!-- Atlas Webhook Secret -->
  <div class="card integration-card">
    <div class="card-header">
      <h3 class="card-title">
        <i class="fas fa-shield-alt"></i> Atlas Webhook Signature Secret
        <span class="badge {% if atlas_webhook_secret_configured %}badge-success{% else %}badge-warning{% endif %}">
          {% if atlas_webhook_secret_configured %}configured{% else %}unset{% endif %}
        </span>
      </h3>
    </div>
    <div class="card-body">
      <p class="text-muted">Bloom value used to sign <code>X-Bloom-Signature</code> for Atlas webhook verification.</p>
      <div class="secret-row">
        <input
          type="password"
          id="atlas-webhook-secret-value"
          class="form-input font-mono secret-input"
          readonly
          value="{{ atlas_webhook_secret }}"
        >
        <button type="button" class="btn btn-outline btn-sm" id="atlas-webhook-secret-view">View</button>
        <button type="button" class="btn btn-outline btn-sm" id="atlas-webhook-secret-copy">Copy</button>
        <button type="button" class="btn btn-outline btn-sm" id="atlas-webhook-secret-hide" style="display:none;">Hide</button>
      </div>
      <div id="atlas-webhook-secret-status" class="text-sm text-muted" style="margin-top: var(--spacing-xs);"></div>
    </div>
  </div>
</div>

<!-- System Info -->
<div class="card" style="margin-top: var(--spacing-lg);">
  <div class="card-header">
    <h3 class="card-title"><i class="fas fa-info-circle"></i> System Information</h3>
  </div>
  <div class="card-body">
    <div class="grid grid-3">
      <div class="info-item">
        <div class="info-label">User</div>
        <div class="info-value">{{ udat.email | default('Unknown') }}</div>
      </div>
      <div class="info-item">
        <div class="info-label">Database</div>
        <div class="info-value font-mono text-sm">{{ db_info.host }}:{{ db_info.port }}/{{ db_info.database }}</div>
      </div>
      <div class="info-item">
        <div class="info-label">BLOOM Version</div>
        <div class="info-value">{{ bloom_version | default('0.0.0') }}</div>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block extra_css %}
<style>
.section-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--color-white);
  margin-bottom: var(--spacing-md);
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.integration-card .card-body p.text-muted {
  margin-bottom: var(--spacing-md);
  font-size: 0.875rem;
}

.integration-actions {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.info-grid {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.info-row {
  display: flex;
  gap: var(--spacing-sm);
  font-size: 0.875rem;
}

.info-key {
  color: var(--color-gray-400);
  min-width: 80px;
}

.info-val {
  color: var(--color-gray-200);
}

.info-item {
  padding: var(--spacing-md);
  background: var(--color-gray-700);
  border-radius: var(--radius-sm);
}

.info-label {
  font-size: 0.75rem;
  color: var(--color-gray-400);
  text-transform: uppercase;
  letter-spacing: 0.05em;
  margin-bottom: var(--spacing-xs);
}

.info-value {
  font-weight: 500;
}

.font-mono {
  font-family: var(--font-mono);
}

.input-group {
  display: flex;
  gap: var(--spacing-sm);
}

.tracking-form {
  margin-top: var(--spacing-sm);
}

.tracking-result {
  margin-top: var(--spacing-md);
  padding: var(--spacing-md);
  background: var(--color-gray-700);
  border-radius: var(--radius-sm);
  font-size: 0.875rem;
}

.tracking-details {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.tracking-row {
  display: flex;
  gap: var(--spacing-sm);
}

.tracking-row strong {
  min-width: 100px;
  color: var(--color-gray-400);
}

.secret-row {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  flex-wrap: wrap;
}

.secret-input {
  flex: 1 1 260px;
}

.text-warning {
  color: var(--color-warning);
}

.issued-token-box {
  margin-top: var(--spacing-sm);
  padding: var(--spacing-md);
  border: 1px solid var(--color-success);
  border-radius: var(--radius-sm);
  background: color-mix(in srgb, var(--color-success) 10%, var(--color-gray-800));
}

.issued-token-title {
  margin-bottom: var(--spacing-xs);
}

.issued-token-row {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  flex-wrap: wrap;
}

.issued-token-value {
  flex: 1 1 auto;
  min-width: 240px;
  display: inline-block;
  padding: var(--spacing-sm);
  border-radius: var(--radius-sm);
  border: 1px solid var(--color-gray-500);
  background: var(--color-gray-900);
  color: #fff;
  font-family: var(--font-mono);
  font-size: 0.95rem;
  font-weight: 600;
  letter-spacing: 0.01em;
  overflow-wrap: anywhere;
}
</style>
{% endblock %}

{% block extra_js %}
<script>
// Theme selector with localStorage persistence
document.addEventListener('DOMContentLoaded', function() {
  const themeSelector = document.getElementById('theme-selector');
  const savedTheme = localStorage.getItem('bloom_theme') || 'dark';

  // Set selector to current theme
  themeSelector.value = savedTheme;

  // Listen for theme changes
  themeSelector.addEventListener('change', function(e) {
    const theme = e.target.value;
    localStorage.setItem('bloom_theme', theme);
    applyTheme(theme);
  });
});

function applyTheme(theme) {
  if (theme === 'light') {
    document.body.classList.add('theme-light');
  } else {
    document.body.classList.remove('theme-light');
  }
}

function renderGroupMembers(bodyId, items, emptyMessage) {
  const body = document.getElementById(bodyId);
  if (!body) return;
  if (!Array.isArray(items) || items.length === 0) {
    body.innerHTML = '<tr><td colspan="2" class="text-muted">' + emptyMessage + '</td></tr>';
    return;
  }
  body.innerHTML = items.map((item) => (
    '<tr>' +
      '<td class="text-mono">' + (item.user_id || '') + '</td>' +
      '<td>' + (item.is_active ? 'yes' : 'no') + '</td>' +
    '</tr>'
  )).join('');
}

function populateTokenOwnerOptions(items) {
  const select = document.getElementById('issue-token-user-id');
  if (!select) return;
  const activeUsers = (items || []).filter((item) => item && item.is_active && item.user_id);
  const current = select.value;
  const options = ['<option value="">Select API user</option>'].concat(
    activeUsers.map((item) => (
      '<option value="' + item.user_id + '">' + item.user_id + '</option>'
    ))
  );
  select.innerHTML = options.join('');
  if (current && activeUsers.some((item) => item.user_id === current)) {
    select.value = current;
  }
}

function renderAdminTokens(items) {
  const body = document.getElementById('admin-tokens-body');
  if (!body) return;
  if (!Array.isArray(items) || items.length === 0) {
    body.innerHTML = '<tr><td colspan="6" class="text-muted">No tokens found</td></tr>';
    return;
  }
  body.innerHTML = items.map((item) => (
    '<tr>' +
      '<td>' + (item.token_name || '') + '</td>' +
      '<td class="text-mono">' + (item.user_id || '') + '</td>' +
      '<td class="text-mono">' + (item.token_prefix || '') + '</td>' +
      '<td>' + (item.status || '') + '</td>' +
      '<td class="text-mono">' + (item.expires_at || '') + '</td>' +
      '<td><button class="btn btn-sm btn-danger" data-token-id="' + item.token_id + '">Revoke</button></td>' +
    '</tr>'
  )).join('');
}

function renderManagedGroupMembers(items) {
  const body = document.getElementById('group-management-members-body');
  if (!body) return;
  if (!Array.isArray(items) || items.length === 0) {
    body.innerHTML = '<tr><td colspan="3" class="text-muted">No members found for selected group</td></tr>';
    return;
  }
  body.innerHTML = items.map((item) => (
    '<tr>' +
      '<td class="text-mono">' + (item.user_id || '') + '</td>' +
      '<td>' + (item.is_active ? 'yes' : 'no') + '</td>' +
      '<td><button class="btn btn-sm btn-danger" data-remove-group-user-id="' + (item.user_id || '') + '">Remove</button></td>' +
    '</tr>'
  )).join('');
}

async function loadGroupMembers(groupCode) {
  const resp = await fetch('/api/v1/admin/groups/' + encodeURIComponent(groupCode) + '/members');
  const payload = await resp.json();
  if (!resp.ok) {
    throw new Error(payload.detail || ('Failed loading members for ' + groupCode));
  }
  return payload.items || [];
}

async function loadGroups() {
  const resp = await fetch('/api/v1/admin/groups');
  const payload = await resp.json();
  if (!resp.ok) {
    throw new Error(payload.detail || 'Failed loading groups');
  }
  return payload.items || [];
}

async function loadAdminTokens() {
  const resp = await fetch('/api/v1/admin/user-tokens');
  const payload = await resp.json();
  if (!resp.ok) {
    throw new Error(payload.detail || 'Failed loading admin token list');
  }
  renderAdminTokens(payload.items || []);
}

async function addGroupMember(groupCode, userId) {
  const resp = await fetch('/api/v1/admin/groups/' + encodeURIComponent(groupCode) + '/members', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ user_id: userId }),
  });
  const payload = await resp.json();
  if (!resp.ok) {
    throw new Error(payload.detail || ('Failed adding membership for ' + groupCode));
  }
  return payload;
}

async function removeGroupMember(groupCode, userId) {
  const resp = await fetch(
    '/api/v1/admin/groups/' + encodeURIComponent(groupCode) + '/members/' + encodeURIComponent(userId),
    { method: 'DELETE' }
  );
  const payload = await resp.json();
  if (!resp.ok) {
    throw new Error(payload.detail || ('Failed removing membership for ' + groupCode));
  }
  return payload;
}

async function issueAdminUserToken(userId, tokenName, scope, expiresInDays) {
  const resp = await fetch('/api/v1/admin/user-tokens/issue', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      user_id: userId,
      token_name: tokenName,
      scope: scope,
      expires_in_days: expiresInDays,
    }),
  });
  const payload = await resp.json();
  if (!resp.ok) {
    throw new Error(payload.detail || 'Failed issuing token');
  }
  return payload;
}

function renderIssuedTokenResult(container, userId, plaintextToken) {
  if (!container) return;
  container.innerHTML = '';

  const box = document.createElement('div');
  box.className = 'issued-token-box';

  const title = document.createElement('div');
  title.className = 'issued-token-title';
  title.innerHTML = 'Token issued for <code>' + userId + '</code>. Store this now.';
  box.appendChild(title);

  const row = document.createElement('div');
  row.className = 'issued-token-row';

  const token = document.createElement('span');
  token.className = 'issued-token-value';
  token.textContent = plaintextToken || '';
  row.appendChild(token);

  const copyBtn = document.createElement('button');
  copyBtn.type = 'button';
  copyBtn.className = 'btn btn-outline btn-sm';
  copyBtn.textContent = 'Copy';
  copyBtn.addEventListener('click', async () => {
    try {
      await navigator.clipboard.writeText(token.textContent || '');
      copyBtn.textContent = 'Copied';
      setTimeout(() => { copyBtn.textContent = 'Copy'; }, 1500);
    } catch (err) {
      const selection = window.getSelection();
      const range = document.createRange();
      range.selectNodeContents(token);
      selection.removeAllRanges();
      selection.addRange(range);
      try {
        document.execCommand('copy');
        copyBtn.textContent = 'Copied';
        setTimeout(() => { copyBtn.textContent = 'Copy'; }, 1500);
      } catch (_copyErr) {
        copyBtn.textContent = 'Copy failed';
        setTimeout(() => { copyBtn.textContent = 'Copy'; }, 2000);
      } finally {
        selection.removeAllRanges();
      }
    }
  });
  row.appendChild(copyBtn);

  box.appendChild(row);
  container.appendChild(box);
}

async function revokeAdminToken(tokenId) {
  const resp = await fetch('/api/v1/admin/user-tokens/' + encodeURIComponent(tokenId), {
    method: 'DELETE',
  });
  const payload = await resp.json();
  if (!resp.ok) {
    throw new Error(payload.detail || 'Failed revoking token');
  }
  return payload;
}

document.addEventListener('DOMContentLoaded', function() {
  const userForm = document.getElementById('api-access-user-form');
  const apiStatus = document.getElementById('api-access-user-status');
  const atlasForm = document.getElementById('atlas-api-user-form');
  const atlasStatus = document.getElementById('atlas-api-user-status');
  const ursaForm = document.getElementById('ursa-api-user-form');
  const ursaStatus = document.getElementById('ursa-api-user-status');
  const tokenForm = document.getElementById('issue-token-form');
  const tokenResult = document.getElementById('issue-token-result');
  const tokenTable = document.getElementById('admin-tokens-body');
  const groupSelect = document.getElementById('group-management-select');
  const groupStatus = document.getElementById('group-management-status');
  const groupAddForm = document.getElementById('group-management-add-form');
  const groupMembersBody = document.getElementById('group-management-members-body');
  const atlasWebhookSecretValue = document.getElementById('atlas-webhook-secret-value');
  const atlasWebhookSecretView = document.getElementById('atlas-webhook-secret-view');
  const atlasWebhookSecretCopy = document.getElementById('atlas-webhook-secret-copy');
  const atlasWebhookSecretHide = document.getElementById('atlas-webhook-secret-hide');
  const atlasWebhookSecretStatus = document.getElementById('atlas-webhook-secret-status');

  function setAtlasWebhookSecretVisible(visible) {
    if (!atlasWebhookSecretValue || !atlasWebhookSecretView || !atlasWebhookSecretHide) return;
    atlasWebhookSecretValue.type = visible ? 'text' : 'password';
    atlasWebhookSecretView.style.display = visible ? 'none' : 'inline-flex';
    atlasWebhookSecretHide.style.display = visible ? 'inline-flex' : 'none';
  }

  if (atlasWebhookSecretValue && atlasWebhookSecretView && atlasWebhookSecretCopy && atlasWebhookSecretHide) {
    if (!atlasWebhookSecretValue.value) {
      atlasWebhookSecretView.disabled = true;
      atlasWebhookSecretCopy.disabled = true;
      atlasWebhookSecretHide.disabled = true;
      if (atlasWebhookSecretStatus) {
        atlasWebhookSecretStatus.textContent = 'No atlas.webhook_secret value is configured.';
      }
    }

    atlasWebhookSecretView.addEventListener('click', function() {
      setAtlasWebhookSecretVisible(true);
      if (atlasWebhookSecretStatus) {
        atlasWebhookSecretStatus.textContent = 'Secret is visible.';
      }
    });

    atlasWebhookSecretHide.addEventListener('click', function() {
      setAtlasWebhookSecretVisible(false);
      if (atlasWebhookSecretStatus) {
        atlasWebhookSecretStatus.textContent = 'Secret hidden.';
      }
    });

    atlasWebhookSecretCopy.addEventListener('click', async function() {
      if (!atlasWebhookSecretValue.value) return;
      try {
        await navigator.clipboard.writeText(atlasWebhookSecretValue.value);
        if (atlasWebhookSecretStatus) {
          atlasWebhookSecretStatus.textContent = 'Secret copied to clipboard.';
        }
      } catch (_err) {
        if (atlasWebhookSecretStatus) {
          atlasWebhookSecretStatus.textContent = 'Clipboard copy failed.';
        }
      }
    });
  }

  loadGroupMembers('API_ACCESS')
    .then((items) => {
      renderGroupMembers('api-access-users-body', items, 'No API_ACCESS users found');
      populateTokenOwnerOptions(items);
    })
    .catch((err) => {
      if (apiStatus) apiStatus.textContent = err.message;
    });

  loadGroupMembers('ENABLE_ATLAS_API')
    .then((items) => {
      renderGroupMembers('atlas-api-users-body', items, 'No Atlas API users found');
    })
    .catch((err) => {
      if (atlasStatus) atlasStatus.textContent = err.message;
    });

  loadGroupMembers('ENABLE_URSA_API')
    .then((items) => {
      renderGroupMembers('ursa-api-users-body', items, 'No Ursa API users found');
    })
    .catch((err) => {
      if (ursaStatus) ursaStatus.textContent = err.message;
    });

  loadAdminTokens().catch((err) => {
    if (tokenResult) tokenResult.textContent = err.message;
  });

  loadGroups()
    .then((groups) => {
      if (!groupSelect) return;
      const activeGroups = (groups || []).filter((group) => group && group.is_active && group.group_code);
      if (activeGroups.length === 0) {
        groupSelect.innerHTML = '<option value="">No groups found</option>';
        return;
      }
      groupSelect.innerHTML = activeGroups.map((group) => (
        '<option value="' + group.group_code + '">' + group.group_code + '</option>'
      )).join('');
      return loadGroupMembers(groupSelect.value);
    })
    .then((items) => {
      if (items) {
        renderManagedGroupMembers(items);
      }
    })
    .catch((err) => {
      if (groupStatus) groupStatus.textContent = err.message;
    });

  if (userForm) {
    userForm.addEventListener('submit', function(event) {
      event.preventDefault();
      const input = document.getElementById('api-access-user-id');
      const userId = input ? input.value.trim() : '';
      if (!userId) {
        apiStatus.textContent = 'User ID is required';
        return;
      }
      addGroupMember('API_ACCESS', userId)
        .then((payload) => {
          apiStatus.textContent = payload.message || 'API_ACCESS membership updated';
          if (input) input.value = '';
          return loadGroupMembers('API_ACCESS');
        })
        .then((items) => {
          renderGroupMembers('api-access-users-body', items, 'No API_ACCESS users found');
          populateTokenOwnerOptions(items);
        })
        .catch((err) => {
          apiStatus.textContent = err.message;
        });
    });
  }

  if (atlasForm) {
    atlasForm.addEventListener('submit', function(event) {
      event.preventDefault();
      const input = document.getElementById('atlas-api-user-id');
      const userId = input ? input.value.trim() : '';
      if (!userId) {
        atlasStatus.textContent = 'User ID is required';
        return;
      }
      addGroupMember('ENABLE_ATLAS_API', userId)
        .then((payload) => {
          atlasStatus.textContent = payload.message || 'ENABLE_ATLAS_API membership updated';
          if (input) input.value = '';
          return loadGroupMembers('ENABLE_ATLAS_API');
        })
        .then((items) => {
          renderGroupMembers('atlas-api-users-body', items, 'No Atlas API users found');
        })
        .catch((err) => {
          atlasStatus.textContent = err.message;
        });
    });
  }

  if (ursaForm) {
    ursaForm.addEventListener('submit', function(event) {
      event.preventDefault();
      const input = document.getElementById('ursa-api-user-id');
      const userId = input ? input.value.trim() : '';
      if (!userId) {
        ursaStatus.textContent = 'User ID is required';
        return;
      }
      addGroupMember('ENABLE_URSA_API', userId)
        .then((payload) => {
          ursaStatus.textContent = payload.message || 'ENABLE_URSA_API membership updated';
          if (input) input.value = '';
          return loadGroupMembers('ENABLE_URSA_API');
        })
        .then((items) => {
          renderGroupMembers('ursa-api-users-body', items, 'No Ursa API users found');
        })
        .catch((err) => {
          ursaStatus.textContent = err.message;
        });
    });
  }

  if (tokenForm) {
    tokenForm.addEventListener('submit', function(event) {
      event.preventDefault();
      const userId = document.getElementById('issue-token-user-id').value.trim();
      const tokenName = document.getElementById('issue-token-name').value.trim();
      const scope = document.getElementById('issue-token-scope').value;
      const days = Number(document.getElementById('issue-token-days').value || '30');
      if (!userId) {
        tokenResult.textContent = 'Token owner is required';
        return;
      }
      if (!tokenName) {
        tokenResult.textContent = 'Token name is required';
        return;
      }
      issueAdminUserToken(userId, tokenName, scope, days)
        .then((payload) => {
          renderIssuedTokenResult(tokenResult, userId, payload.plaintext_token);
          tokenForm.reset();
          document.getElementById('issue-token-days').value = '30';
          return loadAdminTokens();
        })
        .catch((err) => {
          tokenResult.textContent = err.message;
        });
    });
  }

  if (tokenTable) {
    tokenTable.addEventListener('click', function(event) {
      const target = event.target;
      if (!target || !target.dataset || !target.dataset.tokenId) {
        return;
      }
      revokeAdminToken(target.dataset.tokenId)
        .then(() => loadAdminTokens())
        .catch((err) => {
          tokenResult.textContent = err.message;
        });
    });
  }

  if (groupSelect) {
    groupSelect.addEventListener('change', function() {
      const groupCode = groupSelect.value;
      if (!groupCode) {
        renderManagedGroupMembers([]);
        return;
      }
      loadGroupMembers(groupCode)
        .then((items) => {
          renderManagedGroupMembers(items);
          if (groupStatus) groupStatus.textContent = '';
        })
        .catch((err) => {
          if (groupStatus) groupStatus.textContent = err.message;
        });
    });
  }

  if (groupAddForm) {
    groupAddForm.addEventListener('submit', function(event) {
      event.preventDefault();
      const groupCode = groupSelect ? groupSelect.value : '';
      const input = document.getElementById('group-management-user-id');
      const userId = input ? input.value.trim() : '';
      if (!groupCode) {
        if (groupStatus) groupStatus.textContent = 'Select a group';
        return;
      }
      if (!userId) {
        if (groupStatus) groupStatus.textContent = 'User ID is required';
        return;
      }
      addGroupMember(groupCode, userId)
        .then((payload) => {
          if (groupStatus) groupStatus.textContent = payload.message || 'Membership updated';
          if (input) input.value = '';
          return loadGroupMembers(groupCode);
        })
        .then((items) => {
          renderManagedGroupMembers(items);
        })
        .catch((err) => {
          if (groupStatus) groupStatus.textContent = err.message;
        });
    });
  }

  if (groupMembersBody) {
    groupMembersBody.addEventListener('click', function(event) {
      const target = event.target;
      const groupCode = groupSelect ? groupSelect.value : '';
      if (!target || !target.dataset || !target.dataset.removeGroupUserId) {
        return;
      }
      if (!groupCode) {
        if (groupStatus) groupStatus.textContent = 'Select a group';
        return;
      }
      removeGroupMember(groupCode, target.dataset.removeGroupUserId)
        .then(() => loadGroupMembers(groupCode))
        .then((items) => {
          renderManagedGroupMembers(items);
          if (groupStatus) groupStatus.textContent = 'Membership removed';
        })
        .catch((err) => {
          if (groupStatus) groupStatus.textContent = err.message;
        });
    });
  }
});

function trackPackage(event) {
  event.preventDefault();
  const trackingNumber = document.getElementById('tracking-number').value.trim();
  const carrier = document.getElementById('tracking-carrier').value;
  const resultDiv = document.getElementById('tracking-result');

  if (!trackingNumber) {
    resultDiv.innerHTML = '<span class="text-warning">Please enter a tracking number</span>';
    resultDiv.style.display = 'block';
    return;
  }

  resultDiv.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Looking up ' + carrier + ' tracking info...';
  resultDiv.style.display = 'block';

  // Call the tracking API
  fetch('/api/v1/tracking/track/' + encodeURIComponent(trackingNumber) + '?carrier=' + encodeURIComponent(carrier))
    .then(response => {
      if (!response.ok) {
        throw new Error('Tracking API not available');
      }
      return response.json();
    })
    .then(data => {
      if (data.error) {
        resultDiv.innerHTML = '<span class="text-warning"><i class="fas fa-exclamation-triangle"></i> ' + data.error + '</span>';
      } else {
        let html = '<div class="tracking-details">';
        html += '<div class="tracking-row"><strong>Status:</strong> ' + (data.status || 'Unknown') + '</div>';
        if (data.transit_time_hours) {
          html += '<div class="tracking-row"><strong>Transit Time:</strong> ' + data.transit_time_hours + ' hours</div>';
        }
        if (data.origin_city) {
          html += '<div class="tracking-row"><strong>Origin City:</strong> ' + data.origin_city + '</div>';
        }
        if (data.origin_state) {
          html += '<div class="tracking-row"><strong>Origin State:</strong> ' + data.origin_state + '</div>';
        }
        if (data.ship_date) {
          html += '<div class="tracking-row"><strong>Shipped:</strong> ' + data.ship_date + '</div>';
        }
        if (data.delivery_date) {
          html += '<div class="tracking-row"><strong>Delivered:</strong> ' + data.delivery_date + '</div>';
        }
        html += '</div>';
        html += '<details style="margin-top: var(--spacing-sm);"><summary class="text-muted">Raw Data</summary><pre style="font-size: 0.75rem; max-height: 200px; overflow: auto;">' + JSON.stringify(data.raw_data, null, 2) + '</pre></details>';
        resultDiv.innerHTML = html;
      }
    })
    .catch(error => {
      resultDiv.innerHTML = '<span class="text-muted">Tracking lookup failed. ' + error.message + '</span>';
    });
}
</script>
{% endblock %}
