<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 dialogEl = $state<HTMLDialogElement | null>(null);
  let sourceLocalPart = $state('');
  let newAlias = $state({ destination: '' });
  let createError = $state('');
  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;
    }
  }

  function openModal() {
    createError = '';
    sourceLocalPart = '';
    newAlias = { destination: '' };
    dialogEl?.showModal();
  }

  function closeModal() {
    dialogEl?.close();
  }

  async function createAlias() {
    createError = '';
    const source = `${sourceLocalPart}@${domainName}`;
    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({ source, destination: newAlias.destination })
      });
      if (res.ok) {
        closeModal();
        await loadAliases(domainName);
      } else {
        const error = await res.json();
        createError = error.error || 'Failed to create alias';
      }
    } catch (e) {
      createError = 'Failed to create alias';
      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="space-y-4">
  <div class="flex justify-between items-center">
    <div class="flex items-center gap-4">
      <a href="/domains/{domainName}" class="btn btn-ghost btn-sm">
        <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="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" />
        </svg>
        Back
      </a>
      <h2 class="text-2xl font-bold">Aliases - {domainName}</h2>
    </div>
    <button class="btn btn-primary" onclick={openModal}>
      <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="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
      </svg>
      Add Alias
    </button>
  </div>

  {#if loading}
    <div class="flex justify-center py-12">
      <span class="loading loading-spinner loading-lg"></span>
    </div>
  {:else if aliases.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">No aliases configured yet.</p>
      </div>
    </div>
  {:else}
    <div class="card bg-base-100 shadow overflow-hidden">
      <table class="table">
        <thead>
          <tr>
            <th>Source</th>
            <th>Destination</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {#each aliases as alias}
            <tr class="hover">
              <td class="font-medium">{alias.source}</td>
              <td>{alias.destination}</td>
              <td>
                <button class="btn btn-error btn-sm" onclick={() => deleteAlias(alias.id)}>
                  Delete
                </button>
              </td>
            </tr>
          {/each}
        </tbody>
      </table>
    </div>
  {/if}
</div>

<dialog bind:this={dialogEl} class="modal">
  <div class="modal-box">
    <h3 class="font-bold text-lg mb-4">Add Alias</h3>
    <form onsubmit={(e) => { e.preventDefault(); createAlias(); }}>
      <fieldset class="fieldset">
        <legend class="fieldset-legend">Source (alias address)</legend>
        <div class="join w-full">
          <input 
            type="text" 
            class="input input-bordered join-item flex-1" 
            bind:value={sourceLocalPart} 
            placeholder="alias-name" 
            required 
          />
          <span class="btn btn-disabled join-item">@{domainName}</span>
        </div>
      </fieldset>
      <fieldset class="fieldset mt-4">
        <legend class="fieldset-legend">Destination (forward to)</legend>
        <input 
          type="text" 
          class="input input-bordered w-full" 
          bind:value={newAlias.destination} 
          placeholder="user@example.org" 
          required 
        />
      </fieldset>
      {#if createError}
        <div class="alert alert-error mt-4">
          <span>{createError}</span>
        </div>
      {/if}
      <div class="modal-action">
        <button type="button" class="btn" onclick={closeModal}>Cancel</button>
        <button type="submit" class="btn btn-primary">Create</button>
      </div>
    </form>
  </div>
  <form method="dialog" class="modal-backdrop">
    <button onclick={closeModal}>close</button>
  </form>
</dialog>
