<script lang="ts">
  import { enhance } from '$app/forms';
  import type { PageData, ActionData } from './$types';

  let { data, form }: { data: PageData; form: ActionData } = $props();

  let password = $state('');
  let confirm = $state('');

  const mismatch = $derived(confirm.length > 0 && password !== confirm);

  function formatDate(ts?: number): string {
    if (!ts) return '—';
    return new Date(ts).toLocaleDateString('it-IT', {
      year: 'numeric',
      month: 'short',
      day: '2-digit'
    });
  }
</script>

<svelte:head><title>Amministratori — Admin</title></svelte:head>

<header class="page-head">
  <p class="kicker">Accessi</p>
  <h1>Amministratori</h1>
  <p>Crea nuovi account amministratore o rimuovi quelli non più necessari. Gli account rimossi vengono immediatamente disconnessi.</p>
</header>

{#if form?.success}
  <div class="alert-row">
    {form.created ? `Amministratore "${form.created}" creato.` : `Amministratore "${form.deleted}" eliminato.`}
  </div>
{/if}
{#if form?.error}
  <div class="alert-row err">{form.error}</div>
{/if}

<div class="card">
  <h2>Nuovo amministratore</h2>
  <form
    method="POST"
    action="?/create"
    use:enhance={() => async ({ update, result }) => {
      await update();
      if (result.type === 'success') {
        password = '';
        confirm = '';
      }
    }}
  >
    <div class="grid-2">
      <div class="field">
        <label for="new-username">Username</label>
        <input
          id="new-username"
          name="username"
          type="text"
          required
          minlength="3"
          pattern="[a-zA-Z0-9_.\-]+"
          value={form?.username ?? ''}
          autocomplete="off"
        />
        <small>Solo lettere, numeri, . _ -</small>
      </div>
      <div class="field">
        <label for="new-password">Password</label>
        <input
          id="new-password"
          name="password"
          type="password"
          required
          minlength="8"
          bind:value={password}
          autocomplete="new-password"
        />
        <small>Minimo 8 caratteri.</small>
      </div>
    </div>
    <div class="field">
      <label for="new-confirm">Conferma password</label>
      <input
        id="new-confirm"
        name="confirm"
        type="password"
        required
        minlength="8"
        bind:value={confirm}
        autocomplete="new-password"
      />
      {#if mismatch}
        <small style="color:#d64545;">Le password non coincidono.</small>
      {/if}
    </div>
    <button type="submit" class="btn" disabled={mismatch}>
      <span class="material-symbols-outlined" aria-hidden="true">person_add</span>
      Crea amministratore
    </button>
  </form>
</div>

<div class="section-divider">
  <h2>Amministratori esistenti</h2>
  <span class="count">{data.admins.length}</span>
</div>

<div class="card">
  <table class="users-table">
    <thead>
      <tr>
        <th>Username</th>
        <th>Creato il</th>
        <th aria-label="Azioni"></th>
      </tr>
    </thead>
    <tbody>
      {#each data.admins as a (a.username)}
        <tr>
          <td>
            <strong>{a.username}</strong>
            {#if data.admins.length > 0 && a.username === data.admins[0].username}
              <span class="badge">primo admin</span>
            {/if}
          </td>
          <td>{formatDate(a.createdAt)}</td>
          <td style="text-align:right;">
            <form
              method="POST"
              action="?/delete"
              use:enhance
              onsubmit={(e) => {
                if (!window.confirm(`Eliminare l'amministratore "${a.username}"?`)) e.preventDefault();
              }}
            >
              <input type="hidden" name="username" value={a.username} />
              <button
                type="submit"
                class="btn btn-danger btn-sm"
                disabled={data.admins.length <= 1}
                title={data.admins.length <= 1 ? 'Serve almeno un amministratore' : 'Elimina'}
              >
                <span class="material-symbols-outlined" aria-hidden="true">delete</span>
              </button>
            </form>
          </td>
        </tr>
      {/each}
    </tbody>
  </table>
</div>

<style>
  .users-table {
    width: 100%;
    border-collapse: collapse;
  }
  .users-table th,
  .users-table td {
    padding: 12px 10px;
    border-bottom: 1px solid var(--border);
    text-align: left;
    font-size: 14px;
  }
  .users-table th {
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 0.1em;
    text-transform: uppercase;
    color: var(--text-muted);
  }
  .users-table tr:last-child td {
    border-bottom: none;
  }
  .badge {
    margin-left: 8px;
    background: var(--panel-muted);
    color: var(--text-muted);
    padding: 2px 8px;
    border-radius: 9999px;
    font-size: 10px;
    font-weight: 700;
    letter-spacing: 0.08em;
    text-transform: uppercase;
  }
</style>
