<script lang="ts">
  import { decodeJWT } from '$lib/auth';

  interface Domain {
    id: number;
    name: string;
    userCount: number;
    aliasCount: number;
  }

  let domains = $state<Domain[]>([]);
  let isAdmin = $state(false);
  let loading = $state(true);
  let dialogEl = $state<HTMLDialogElement | null>(null);
  let newDomain = $state({ name: '' });
  let createError = $state('');

  async function fetchWithAuth(url: string) {
    const token = localStorage.getItem('token');
    const res = await fetch(url, {
      headers: { Authorization: `Bearer ${token}` }
    });
    return res.json();
  }

  async function loadData() {
    const token = localStorage.getItem('token');
    const payload = decodeJWT(token || '');
    isAdmin = payload?.role === 'admin';

    try {
      const domainsRes = await fetchWithAuth('/api/domains');
      if (domainsRes.data) {
        domains = domainsRes.data || [];
      }
    } catch (e) {
      console.error('Failed to load data:', e);
    } finally {
      loading = false;
    }
  }

  function openModal() {
    createError = '';
    newDomain = { name: '' };
    dialogEl?.showModal();
  }

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

  async function createDomain() {
    createError = '';
    try {
      const res = await fetch('/api/domains', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${localStorage.getItem('token')}` },
        body: JSON.stringify(newDomain)
      });
      const data = await res.json();
      if (res.ok) {
        closeModal();
        await loadData();
      } else {
        createError = data.error || 'Failed to create domain';
      }
    } catch (e) {
      createError = 'Failed to create domain';
      console.error('Failed to create domain:', e);
    }
  }

  async function deleteDomain(name: string) {
    if (!confirm(`Delete domain ${name}? Users and aliases will be deleted.`)) return;
    try {
      await fetch(`/api/domains/${name}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      });
      await loadData();
    } catch (e) {
      console.error('Failed to delete domain:', e);
    }
  }

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

<div class="space-y-4">
  <div class="flex justify-between items-center">
    <h2 class="text-2xl font-bold">Domains</h2>
    {#if isAdmin}
      <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 Domain
      </button>
    {/if}
  </div>

  {#if loading}
    <div class="flex justify-center py-12">
      <span class="loading loading-spinner loading-lg"></span>
    </div>
  {:else if domains.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 domains configured yet.</p>
      </div>
    </div>
  {:else}
    <div class="card bg-base-100 shadow overflow-hidden">
      <table class="table">
        <thead>
          <tr>
            <th>Domain</th>
            <th>Users</th>
            <th>Aliases</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {#each domains as domain}
            <tr class="hover">
              <td>
                <a href="/domains/{domain.name}/users" class="font-medium text-primary hover:underline">
                  {domain.name}
                </a>
              </td>
              <td>{domain.userCount}</td>
              <td>{domain.aliasCount}</td>
              <td>
                {#if isAdmin}
                  <button class="btn btn-error btn-sm" onclick={() => deleteDomain(domain.name)}>
                    Delete
                  </button>
                {/if}
              </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 Domain</h3>
    <form onsubmit={(e) => { e.preventDefault(); createDomain(); }}>
      <fieldset class="fieldset">
        <legend class="fieldset-legend">Domain name</legend>
        <input 
          type="text" 
          class="input input-bordered w-full" 
          bind:value={newDomain.name} 
          placeholder="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>
