<script lang="ts">
  interface Domain {
    id: number;
    name: string;
    userCount: number;
    aliasCount: number;
  }

  interface UserInfo {
    id: number;
    username: string;
    role: string;
    domains: string[];
  }

  let domains = $state<Domain[]>([]);
  let user = $state<UserInfo | null>(null);
  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() {
    try {
      const [domainsRes, userRes] = await Promise.all([
        fetchWithAuth('/api/domains'),
        fetchWithAuth('/api/auth/me')
      ]);

      if (domainsRes.data) {
        domains = domainsRes.data || [];
      }
      if (userRes.data) {
        user = userRes.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);
    }
  }

  function isAdmin() {
    return user?.role === 'admin';
  }

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

<div class="header">
  <h2>Domains</h2>
  {#if isAdmin()}
    <button onclick={openModal}>Add Domain</button>
  {/if}
</div>

{#if user && !isAdmin() && user.domains.length > 0}
  <h3>Your Domains</h3>
  <div class="domains-grid">
    {#each user.domains as domainName}
      <a href="/domains/{domainName}/users" class="domain-card">
        <span class="domain-name">{domainName}</span>
        <span class="domain-links">Manage →</span>
      </a>
    {/each}
  </div>
{/if}

{#if loading}
  <p>Loading...</p>
{:else if isAdmin() && domains.length === 0}
  <p>No domains configured yet.</p>
{:else if isAdmin()}
  <h3>All Domains</h3>
  <table>
    <thead>
      <tr>
        <th>Domain</th>
        <th>Users</th>
        <th>Aliases</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      {#each domains as domain}
        <tr>
          <td><a href="/domains/{domain.name}/users">{domain.name}</a></td>
          <td>{domain.userCount}</td>
          <td>{domain.aliasCount}</td>
          <td>
            <button class="danger" onclick={() => deleteDomain(domain.name)}>Delete</button>
          </td>
        </tr>
      {/each}
    </tbody>
  </table>
{/if}

<dialog bind:this={dialogEl}>
  <h3>Add Domain</h3>
  <form onsubmit={(e) => { e.preventDefault(); createDomain(); }}>
    <label>
      Domain name:
      <input type="text" bind:value={newDomain.name} placeholder="example.org" required />
    </label>
    {#if createError}
      <p class="error">{createError}</p>
    {/if}
    <div class="actions">
      <button type="button" class="secondary" onclick={closeModal}>Cancel</button>
      <button type="submit">Create</button>
    </div>
  </form>
</dialog>

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

  h3 {
    color: #2c3e50;
    margin-top: 1.5rem;
  }

  .domains-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 1rem;
    margin-top: 1rem;
  }

  .domain-card {
    background: white;
    padding: 1rem 1.5rem;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    text-decoration: none;
    color: inherit;
    transition: transform 0.2s, box-shadow 0.2s;
  }

  .domain-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
  }

  .domain-name {
    font-weight: 600;
    color: #2c3e50;
  }

  .domain-links {
    color: #3498db;
    font-size: 0.9rem;
  }

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

  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.secondary {
    background: #95a5a6;
  }

  button.danger {
    background: #e74c3c;
  }

  dialog {
    padding: 2rem;
    border-radius: 8px;
    border: none;
    box-shadow: 0 4px 20px rgba(0,0,0,0.2);
  }

  dialog::backdrop {
    background: rgba(0,0,0,0.5);
  }

  dialog h3 {
    margin: 0 0 1rem 0;
  }

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

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

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

  dialog .error {
    color: #e74c3c;
    background: #fdecea;
    padding: 0.5rem;
    border-radius: 4px;
    margin: 0;
  }

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