<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="space-y-4">
  <div class="flex justify-between items-center">
    <h2 class="text-2xl font-bold">Mail Queue</h2>
    <button class="btn btn-primary" onclick={loadQueue}>
      <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
        <path fill-rule="evenodd" d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z" clip-rule="evenodd" />
      </svg>
      Refresh
    </button>
  </div>

  {#if loading}
    <div class="flex justify-center py-12">
      <span class="loading loading-spinner loading-lg"></span>
    </div>
  {:else if error}
    <div class="alert alert-error">
      <span>{error}</span>
    </div>
  {:else if queue.length === 0}
    <div class="card bg-base-100 shadow">
      <div class="card-body items-center text-center py-12">
        <p class="text-base-content/60">Queue is empty.</p>
      </div>
    </div>
  {:else}
    <div class="card bg-base-100 shadow overflow-hidden">
      <table class="table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Sender</th>
            <th>Recipients</th>
            <th>Size</th>
            <th>Reason</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {#each queue as entry}
            <tr class="hover">
              <td class="font-mono text-sm">{entry.id}</td>
              <td class="text-sm">{entry.sender}</td>
              <td class="text-sm">{entry.recipients.join(', ')}</td>
              <td>{formatSize(entry.size)}</td>
              <td class="text-error text-sm">{entry.reason}</td>
              <td>
                <div class="flex gap-2">
                  <button class="btn btn-sm btn-warning" onclick={() => requeue(entry.id)}>Requeue</button>
                  <button class="btn btn-sm btn-error" onclick={() => deleteFromQueue(entry.id)}>Delete</button>
                </div>
              </td>
            </tr>
          {/each}
        </tbody>
      </table>
    </div>
  {/if}
</div>
