<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="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">Users - {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 User
    </button>
  </div>

  {#if loading}
    <div class="flex justify-center py-12">
      <span class="loading loading-spinner loading-lg"></span>
    </div>
  {:else if users.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 users configured yet.</p>
      </div>
    </div>
  {:else}
    <div class="card bg-base-100 shadow overflow-hidden">
      <table class="table">
        <thead>
          <tr>
            <th>Email</th>
            <th>Quota</th>
            <th>Used</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {#each users as user}
            <tr class="hover">
              <td class="font-medium">{user.email}</td>
              <td>{formatQuota(user.quota)}</td>
              <td>{formatUsed(user.usedQuota, user.quota)}</td>
              <td>
                <button class="btn btn-error btn-sm" onclick={() => deleteUser(user.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 User</h3>
    <form onsubmit={(e) => { e.preventDefault(); createUser(); }}>
      <fieldset class="fieldset">
        <legend class="fieldset-legend">Username</legend>
        <div class="join w-full">
          <input 
            type="text" 
            class="input input-bordered join-item flex-1" 
            bind:value={localPart} 
            placeholder="username" 
            required 
          />
          <span class="btn btn-disabled join-item">@{domainName}</span>
        </div>
      </fieldset>
      <fieldset class="fieldset mt-4">
        <legend class="fieldset-legend">Password</legend>
        <input 
          type="password" 
          class="input input-bordered w-full" 
          bind:value={newUser.password} 
          required 
        />
      </fieldset>
      <fieldset class="fieldset mt-4">
        <legend class="fieldset-legend">Quota (bytes, 0 = default)</legend>
        <input 
          type="number" 
          class="input input-bordered w-full" 
          bind:value={newUser.quota} 
          min="0" 
        />
      </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>
