{% 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 successfully.</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_start</code> on this host.
      {% elif zebra_error == "launch_failed" %}
      Failed to launch zebra_day service.
      {% 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="/bloom_schema_report" class="list-item">
          <span><i class="fas fa-database"></i> Schema Report</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 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="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>
</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);
}

.text-warning {
  color: var(--color-warning);
}
</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 renderApiAccessUsers(items) {
  const body = document.getElementById('api-access-users-body');
  if (!body) return;
  if (!Array.isArray(items) || items.length === 0) {
    body.innerHTML = '<tr><td colspan="2" class="text-muted">No API_ACCESS users found</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 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('');
}

async function loadApiAccessUsers() {
  const resp = await fetch('/api/v1/admin/groups/API_ACCESS/members');
  const payload = await resp.json();
  if (!resp.ok) {
    throw new Error(payload.detail || 'Failed loading API_ACCESS members');
  }
  renderApiAccessUsers(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 addApiAccessUser(userId) {
  const resp = await fetch('/api/v1/admin/groups/API_ACCESS/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 API_ACCESS membership');
  }
  return payload;
}

async function issueUserToken(tokenName, scope, expiresInDays) {
  const resp = await fetch('/api/v1/user-tokens', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      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;
}

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 status = document.getElementById('api-access-user-status');
  const tokenForm = document.getElementById('issue-token-form');
  const tokenResult = document.getElementById('issue-token-result');
  const tokenTable = document.getElementById('admin-tokens-body');

  loadApiAccessUsers().catch((err) => {
    if (status) status.textContent = err.message;
  });
  loadAdminTokens().catch((err) => {
    if (tokenResult) tokenResult.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) {
        status.textContent = 'User ID is required';
        return;
      }
      addApiAccessUser(userId)
        .then(() => {
          status.textContent = 'API_ACCESS membership added';
          if (input) input.value = '';
          return loadApiAccessUsers();
        })
        .catch((err) => {
          status.textContent = err.message;
        });
    });
  }

  if (tokenForm) {
    tokenForm.addEventListener('submit', function(event) {
      event.preventDefault();
      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 (!tokenName) {
        tokenResult.textContent = 'Token name is required';
        return;
      }
      issueUserToken(tokenName, scope, days)
        .then((payload) => {
          tokenResult.innerHTML =
            'Token issued for current admin user. Plaintext token: <code>' +
            payload.plaintext_token +
            '</code>';
          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;
        });
    });
  }
});

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 %}
