<script lang="ts">
  interface QueueEntry {
    id: string;
    sender: string;
    recipients: string[];
    size: number;
    time: string;
    reason: string;
  }

  let queue = $state<QueueEntry[]>([]);
  let loading = $state(true);
  let error = $state('');

  async function loadQueue() {
    loading = true;
    error = '';
    try {
      const token = localStorage.getItem('token');
      const res = await fetch('/api/queue', {
        headers: { Authorization: `Bearer ${token}` }
      });
      if (res.ok) {
        const data = await res.json();
        queue = data.data || [];
      } else {
        error = 'Failed to load queue';
      }
    } catch (e) {
      error = 'Connection error';
      console.error('Failed to load queue:', e);
    } finally {
      loading = false;
    }
  }

  async function requeue(id: string) {
    try {
      const token = localStorage.getItem('token');
      await fetch(`/api/queue/${id}/requeue`, {
        method: 'POST',
        headers: { Authorization: `Bearer ${token}` }
      });
      await loadQueue();
    } catch (e) {
      console.error('Failed to requeue:', e);
    }
  }

  async function deleteFromQueue(id: string) {
    if (!confirm('Delete this message from queue?')) return;
    try {
      const token = localStorage.getItem('token');
      await fetch(`/api/queue/${id}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${token}` }
      });
      await loadQueue();
    } catch (e) {
      console.error('Failed to delete from queue:', e);
    }
  }

  function formatSize(bytes: number): string {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
    return (bytes / 1024 / 1024).toFixed(1) + ' MB';
  }

  $effect(() => { loadQueue(); });
</script>

<div class="header">
  <h2>Mail Queue</h2>
  <button onclick={loadQueue}>Refresh</button>
</div>

{#if loading}
  <p>Loading...</p>
{:else if error}
  <p class="error">{error}</p>
{:else if queue.length === 0}
  <p>Queue is empty.</p>
{:else}
  <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>Sender</th>
        <th>Recipients</th>
        <th>Size</th>
        <th>Time</th>
        <th>Reason</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      {#each queue as entry}
        <tr>
          <td class="id">{entry.id}</td>
          <td>{entry.sender}</td>
          <td>{entry.recipients.join(', ')}</td>
          <td>{formatSize(entry.size)}</td>
          <td>{entry.time}</td>
          <td class="reason">{entry.reason}</td>
          <td>
            <button onclick={() => requeue(entry.id)}>Requeue</button>
            <button class="danger" onclick={() => deleteFromQueue(entry.id)}>Delete</button>
          </td>
        </tr>
      {/each}
    </tbody>
  </table>
{/if}

<style>
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
  }

  table {
    width: 100%;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }

  th, td {
    padding: 0.75rem;
    text-align: left;
    border-bottom: 1px solid #eee;
    font-size: 0.9rem;
  }

  th {
    background: #f8f9fa;
    font-weight: 600;
  }

  .id {
    font-family: monospace;
    font-size: 0.8rem;
  }

  .reason {
    color: #e74c3c;
  }

  button {
    padding: 0.25rem 0.5rem;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    background: #3498db;
    color: white;
    font-size: 0.8rem;
    margin-right: 0.25rem;
  }

  button.danger {
    background: #e74c3c;
  }

  .error {
    color: #e74c3c;
  }
</style>
