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

  interface User {
    id: number;
    email: string;
    quota: number;
    usedQuota?: number;
  }

  let users = $state<User[]>([]);
  let loading = $state(true);
  let dialogEl = $state<HTMLDialogElement | null>(null);
  let localPart = $state('');
  let newUser = $state({ password: '', quota: 0 });
  let createError = $state('');
  let domainName = $state('');

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

  function openModal() {
    createError = '';
    localPart = '';
    newUser = { password: '', quota: 0 };
    dialogEl?.showModal();
  }

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

  async function createUser() {
    createError = '';
    const email = `${localPart}@${domainName}`;
    try {
      const token = localStorage.getItem('token');
      const res = await fetch(`/api/domains/${encodeURIComponent(domainName)}/users`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`
        },
        body: JSON.stringify({ email, password: newUser.password, quota: newUser.quota })
      });
      if (res.ok) {
        closeModal();
        await loadUsers(domainName);
      } else {
        const error = await res.json();
        createError = error.error || 'Failed to create user';
      }
    } catch (e) {
      createError = 'Failed to create user';
      console.error('Failed to create user:', e);
    }
  }

  async function deleteUser(id: number) {
    if (!confirm('Delete this user? Mailbox will NOT be deleted.')) return;
    try {
      const token = localStorage.getItem('token');
      await fetch(`/api/domains/${encodeURIComponent(domainName)}/users/${id}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${token}` }
      });
      await loadUsers(domainName);
    } catch (e) {
      console.error('Failed to delete user:', e);
    }
  }

  function formatBytes(bytes: number | undefined | null): string {
    if (bytes === undefined || bytes === null || isNaN(bytes)) return 'Unknown';
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
    if (bytes < 1024 * 1024 * 1024) return (bytes / 1024 / 1024).toFixed(1) + ' MB';
    return (bytes / 1024 / 1024 / 1024).toFixed(2) + ' GB';
  }

  function formatQuota(limit: number): string {
    if (limit === 0) return 'Default';
    return formatBytes(limit);
  }

  function formatUsed(used: number | undefined | null, limit: number): string {
    const usedStr = formatBytes(used ?? null);
    if (limit === 0) return usedStr;
    if (used === undefined || used === null) return usedStr + ' (Unknown)';
    const pct = (used / limit * 100).toFixed(1);
    return usedStr + ' (' + pct + '%)';
  }

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

<div class="header">
  <a href="/domains/{domainName}" class="back">← Back to {domainName}</a>
  <h2>Users</h2>
  <button onclick={openModal}>Add User</button>
</div>

{#if loading}
  <p>Loading...</p>
{:else if users.length === 0}
  <p>No users configured yet.</p>
{:else}
  <table>
    <thead>
      <tr>
        <th>Email</th>
        <th>Quota</th>
        <th>Used</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      {#each users as user}
        <tr>
          <td>{user.email}</td>
          <td>{formatQuota(user.quota)}</td>
          <td>{formatUsed(user.usedQuota, user.quota)}</td>
          <td>
            <button class="danger" onclick={() => deleteUser(user.id)}>Delete</button>
          </td>
        </tr>
      {/each}
    </tbody>
  </table>
{/if}

<dialog bind:this={dialogEl}>
  <h3>Add User</h3>
  <form onsubmit={(e) => { e.preventDefault(); createUser(); }}>
    <label class="email-input">
      <span class="label-text">Email:</span>
      <div class="input-group">
        <input type="text" bind:value={localPart} placeholder="username" required />
        <span class="domain-suffix">@{domainName}</span>
      </div>
    </label>
    <label>
      Password:
      <input type="password" bind:value={newUser.password} required />
    </label>
    <label>
      Quota (bytes, 0 = default):
      <input type="number" bind:value={newUser.quota} min="0" />
    </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;
    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.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;
  }

  .email-input .label-text {
    font-weight: normal;
  }

  .input-group {
    display: flex;
    align-items: center;
  }

  .input-group input {
    flex: 1;
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
  }

  .domain-suffix {
    padding: 0.5rem 0.75rem;
    background: #f0f0f0;
    border: 1px solid #ddd;
    border-left: none;
    border-radius: 0 4px 4px 0;
    color: #666;
    white-space: nowrap;
  }

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

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