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

  interface User {
    id: number;
    email: string;
    domain_id: number;
    quota: number;
    used_quota: number;
  }

  let users = $state<User[]>([]);
  let loading = $state(true);
  let showModal = $state(false);
  let newUser = $state({ email: '', password: '', quota: 0 });
  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;
    }
  }

  async function createUser() {
    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(newUser)
      });
      if (res.ok) {
        showModal = false;
        newUser = { email: '', password: '', quota: 0 };
        await loadUsers(domainName);
      } else {
        const error = await res.json();
        alert(error.error || 'Failed to create user');
      }
    } catch (e) {
      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 formatQuota(bytes: number): string {
    if (bytes === 0) return 'Default';
    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';
  }

  $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={() => showModal = true}>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>{formatQuota(user.used_quota)}</td>
          <td>
            <button class="danger" onclick={() => deleteUser(user.id)}>Delete</button>
          </td>
        </tr>
      {/each}
    </tbody>
  </table>
{/if}

{#if showModal}
  <button class="modal-backdrop" onclick={() => showModal = false} aria-label="Close modal"></button>
  <div class="modal">
    <h3>Add User</h3>
    <form onsubmit={(e) => { e.preventDefault(); createUser(); }}>
      <label>
        Email:
        <input type="email" bind:value={newUser.email} placeholder="user@{domainName}" required />
      </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>
      <div class="actions">
        <button type="button" onclick={() => showModal = false}>Cancel</button>
        <button type="submit">Create</button>
      </div>
    </form>
  </div>
{/if}

<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.danger {
    background: #e74c3c;
  }

  .modal-backdrop {
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.5);
    border: none;
    cursor: pointer;
    z-index: 100;
  }

  .modal {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    padding: 2rem;
    border-radius: 8px;
    min-width: 400px;
    z-index: 101;
  }

  .modal h3 {
    margin-top: 0;
  }

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

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

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

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