<script lang="ts">
  import { page } from '$app/stores';

  interface Alias {
    id: number;
    source: string;
    destination: string;
  }

  let aliases = $state<Alias[]>([]);
  let loading = $state(true);
  let showModal = $state(false);
  let newAlias = $state({ source: '', destination: '' });
  let domainName = $state('');

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

  async function createAlias() {
    try {
      const token = localStorage.getItem('token');
      const res = await fetch(`/api/domains/${encodeURIComponent(domainName)}/aliases`, {
        method: 'POST',
        headers: { 
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`
        },
        body: JSON.stringify(newAlias)
      });
      if (res.ok) {
        showModal = false;
        newAlias = { source: '', destination: '' };
        await loadAliases(domainName);
      } else {
        const error = await res.json();
        alert(error.error || 'Failed to create alias');
      }
    } catch (e) {
      console.error('Failed to create alias:', e);
    }
  }

  async function deleteAlias(id: number) {
    if (!confirm('Delete this alias?')) return;
    try {
      const token = localStorage.getItem('token');
      await fetch(`/api/domains/${encodeURIComponent(domainName)}/aliases/${id}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${token}` }
      });
      await loadAliases(domainName);
    } catch (e) {
      console.error('Failed to delete alias:', e);
    }
  }

  $effect(() => {
    const name = $page.params.name;
    if (name) {
      domainName = name;
      loadAliases(name);
    }
  });
</script>

<div class="header">
  <a href="/domains/{domainName}" class="back">← Back to {domainName}</a>
  <h2>Aliases</h2>
  <button onclick={() => showModal = true}>Add Alias</button>
</div>

{#if loading}
  <p>Loading...</p>
{:else if aliases.length === 0}
  <p>No aliases configured yet.</p>
{:else}
  <table>
    <thead>
      <tr>
        <th>Source</th>
        <th>Destination</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      {#each aliases as alias}
        <tr>
          <td>{alias.source}</td>
          <td>{alias.destination}</td>
          <td>
            <button class="danger" onclick={() => deleteAlias(alias.id)}>Delete</button>
          </td>
        </tr>
      {/each}
    </tbody>
  </table>
{/if}

{#if showModal}
  <button class="modal-backdrop" onclick={() => showModal = false} aria-label="Close modal"></button>
  <div class="modal">
    <h3>Add Alias</h3>
    <form onsubmit={(e) => { e.preventDefault(); createAlias(); }}>
      <label>
        Source (alias address):
        <input type="text" bind:value={newAlias.source} placeholder="info@{domainName}" required />
      </label>
      <label>
        Destination (forward to):
        <input type="text" bind:value={newAlias.destination} placeholder="user@example.org" required />
      </label>
      <div class="actions">
        <button type="button" onclick={() => showModal = false}>Cancel</button>
        <button type="submit">Create</button>
      </div>
    </form>
  </div>
{/if}

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

  .back {
    color: #3498db;
    text-decoration: none;
    font-size: 0.9rem;
  }

  .back:hover {
    text-decoration: underline;
  }

  .header h2 {
    flex: 1;
    margin: 0;
  }

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

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

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

  button {
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    background: #3498db;
    color: white;
  }

  button.danger {
    background: #e74c3c;
  }

  .modal-backdrop {
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.5);
    border: none;
    cursor: pointer;
    z-index: 100;
  }

  .modal {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    padding: 2rem;
    border-radius: 8px;
    min-width: 400px;
    z-index: 101;
  }

  .modal h3 {
    margin-top: 0;
  }

  .modal form {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }

  .modal label {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }

  .modal input {
    padding: 0.5rem;
    border: 1px solid #ddd;
    border-radius: 4px;
  }

  .actions {
    display: flex;
    gap: 1rem;
    justify-content: flex-end;
  }
</style>
