<script lang="ts">
  import { onMount } from "svelte";
  import { fetchAgents, updateAgent, createAgentToken, deleteAgent, type Agent } from "$lib/api";
  import { getToken } from "$lib/auth";

  let agents = $state<Agent[]>([]);
  let loadError = $state<string | null>(null);
  let saving = $state<string | null>(null);
  let toast = $state<{ msg: string; ok: boolean } | null>(null);
  let editing = $state<Record<string, string>>({});

  onMount(async () => {
    try {
      agents = await fetchAgents();
      for (const a of agents) editing[a.id] = a.alias;
    } catch (e: any) {
      loadError = e.message;
    }
  });

  async function saveAlias(agent: Agent) {
    saving = agent.id;
    try {
      const updated = await updateAgent(agent.id, editing[agent.id] ?? "");
      agents = agents.map(a => a.id === updated.id ? { ...a, alias: updated.alias } : a);
      showToast("Alias sauvegardé", true);
    } catch (e: any) {
      showToast(e.message, false);
    } finally {
      saving = null;
    }
  }

  function showToast(msg: string, ok: boolean) {
    toast = { msg, ok };
    setTimeout(() => (toast = null), 3000);
  }

  // ── Agent token creation ─────────────────────────────────────────────────
  let tokenHostname = $state("");
  let tokenResult = $state<{ agent_id: string; token: string } | null>(null);
  let tokenCreating = $state(false);
  let tokenError = $state<string | null>(null);
  let tokenCopied = $state(false);

  async function generateToken(e: SubmitEvent) {
    e.preventDefault();
    tokenError = null;
    tokenResult = null;
    tokenCreating = true;
    try {
      tokenResult = await createAgentToken(tokenHostname.trim());
      tokenHostname = "";
    } catch (err: any) {
      tokenError = err.message;
    } finally {
      tokenCreating = false;
    }
  }

  async function copyToken() {
    if (!tokenResult) return;
    await navigator.clipboard.writeText(tokenResult.token);
    tokenCopied = true;
    setTimeout(() => (tokenCopied = false), 2000);
  }

  // ── Agent deletion ────────────────────────────────────────────────────────
  let deleting = $state<string | null>(null);

  async function removeAgent(agent: Agent) {
    if (!confirm(`Supprimer l'agent "${agent.alias || agent.hostname}" ? Cette action est irréversible.`)) return;
    deleting = agent.id;
    try {
      await deleteAgent(agent.id);
      agents = agents.filter(a => a.id !== agent.id);
      showToast("Agent supprimé", true);
    } catch (err: any) {
      showToast(err.message, false);
    } finally {
      deleting = null;
    }
  }

  // ── Password change ──────────────────────────────────────────────────────
  let pwCurrent = $state("");
  let pwNew = $state("");
  let pwConfirm = $state("");
  let pwSaving = $state(false);
  let pwError = $state<string | null>(null);

  async function changePassword(e: SubmitEvent) {
    e.preventDefault();
    pwError = null;
    if (pwNew !== pwConfirm) { pwError = "Les mots de passe ne correspondent pas."; return; }
    if (pwNew.length < 8) { pwError = "Minimum 8 caractères requis."; return; }
    pwSaving = true;
    try {
      const r = await fetch("/api/v1/auth/change-password", {
        method: "POST",
        headers: { "Content-Type": "application/json", Authorization: `Bearer ${getToken()}` },
        body: JSON.stringify({ current_password: pwCurrent, new_password: pwNew }),
      });
      if (!r.ok) throw new Error((await r.text()).trim() || `Erreur ${r.status}`);
      pwCurrent = pwNew = pwConfirm = "";
      showToast("Mot de passe modifié", true);
    } catch (err: any) {
      pwError = err.message;
    } finally {
      pwSaving = false;
    }
  }
</script>

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

{#if toast}
  <div class="fixed top-4 right-4 z-50 flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm
              font-medium shadow-2xl border
              {toast.ok
                ? 'bg-abyss-800 border-signal-green/30 text-signal-green'
                : 'bg-abyss-800 border-signal-red/30 text-signal-red'}">
    <span class="w-1.5 h-1.5 rounded-full {toast.ok ? 'bg-signal-green' : 'bg-signal-red'}"></span>
    {toast.msg}
  </div>
{/if}

<div class="min-h-screen bg-abyss-900 bg-grid-faint bg-grid text-slate-200">

  <!-- Page title bar -->
  <div class="border-b border-white/[0.06] bg-abyss-900/80 px-4 md:px-6 py-3 shrink-0">
    <div class="max-w-4xl mx-auto flex items-center gap-2">
      <svg class="w-4 h-4 text-cyan-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75"
          d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
      </svg>
      <span class="text-sm font-medium text-slate-300">Administration</span>
    </div>
  </div>

  <main class="p-4 md:p-6 max-w-4xl mx-auto space-y-10">

    <!-- Password section -->
    <section>
      <h2 class="text-xs font-semibold text-slate-500 uppercase tracking-widest mb-4">Sécurité</h2>
      <div class="card p-5 max-w-sm">
        <h3 class="text-sm font-semibold text-slate-200 mb-4">Changer le mot de passe</h3>
        <form onsubmit={changePassword} class="space-y-3">
          {#if pwError}
            <p class="text-xs text-signal-red bg-signal-red/10 border border-signal-red/20
                       rounded-lg px-3 py-2">{pwError}</p>
          {/if}
          {#each [
            { id: "pw-c", label: "Mot de passe actuel", bind: "pwCurrent", val: pwCurrent, ac: "current-password" },
            { id: "pw-n", label: "Nouveau mot de passe", bind: "pwNew", val: pwNew, ac: "new-password" },
            { id: "pw-cf", label: "Confirmer", bind: "pwConfirm", val: pwConfirm, ac: "new-password" },
          ] as field}
            <div>
              <label class="block text-xs text-slate-500 mb-1" for={field.id}>{field.label}</label>
              <input id={field.id} type="password" required
                value={field.id === "pw-c" ? pwCurrent : field.id === "pw-n" ? pwNew : pwConfirm}
                oninput={(e) => {
                  const v = (e.target as HTMLInputElement).value;
                  if (field.id === "pw-c") pwCurrent = v;
                  else if (field.id === "pw-n") pwNew = v;
                  else pwConfirm = v;
                }}
                class="w-full bg-abyss-700 border border-white/[0.08] rounded-lg px-3 py-2 text-sm
                       text-slate-100 outline-none focus:border-emerald/60 focus:ring-1 focus:ring-emerald/30
                       transition-all" />
            </div>
          {/each}
          <button type="submit" disabled={pwSaving}
            class="w-full mt-1 bg-emerald hover:bg-emerald-bright disabled:opacity-50 text-white
                   text-sm font-medium py-2 rounded-lg transition-colors">
            {pwSaving ? "Sauvegarde…" : "Mettre à jour"}
          </button>
        </form>
      </div>
    </section>

    <!-- Agents section -->
    <section>
      <h2 class="text-xs font-semibold text-slate-500 uppercase tracking-widest mb-4">Agents</h2>

      <!-- Créer un token d'agent -->
      <div class="card p-5 max-w-sm mb-6">
        <h3 class="text-sm font-semibold text-slate-200 mb-1">Créer un token d'agent</h3>
        <p class="text-xs text-slate-500 mb-4">
          Génère un token d'authentification pour enregistrer un nouvel agent.
        </p>
        <form onsubmit={generateToken} class="space-y-3">
          {#if tokenError}
            <p class="text-xs text-signal-red bg-signal-red/10 border border-signal-red/20
                       rounded-lg px-3 py-2">{tokenError}</p>
          {/if}
          <div>
            <label class="block text-xs text-slate-500 mb-1" for="token-hostname">Hostname de l'agent</label>
            <input
              id="token-hostname"
              type="text"
              required
              bind:value={tokenHostname}
              placeholder="ex: server-01"
              class="w-full bg-abyss-700 border border-white/[0.08] rounded-lg px-3 py-2 text-sm
                     text-slate-100 placeholder-slate-600 outline-none focus:border-emerald/60
                     focus:ring-1 focus:ring-emerald/30 transition-all"
            />
          </div>
          <button
            type="submit"
            disabled={tokenCreating}
            class="w-full bg-emerald hover:bg-emerald-bright disabled:opacity-50 text-white
                   text-sm font-medium py-2 rounded-lg transition-colors">
            {tokenCreating ? "Génération…" : "Générer"}
          </button>
        </form>

        {#if tokenResult}
          <div class="mt-4 p-3 rounded-lg bg-signal-green/5 border border-signal-green/20 space-y-2">
            <div class="flex items-center gap-1.5 text-xs font-semibold text-signal-green">
              <svg class="w-3.5 h-3.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
              </svg>
              Token généré — notez-le, il ne sera plus affiché !
            </div>
            <p class="text-xs text-slate-500 font-mono break-all select-all bg-abyss-800 rounded px-2 py-1.5 border border-white/[0.06]">
              {tokenResult.token}
            </p>
            <button
              onclick={copyToken}
              class="w-full flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-lg text-xs
                     font-medium transition-all
                     {tokenCopied
                       ? 'bg-signal-green/20 text-signal-green border border-signal-green/30'
                       : 'bg-abyss-700 hover:bg-abyss-600 text-slate-300 border border-white/[0.08]'}">
              {#if tokenCopied}
                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                </svg>
                Copié !
              {:else}
                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                </svg>
                Copier le token
              {/if}
            </button>
          </div>
        {/if}
      </div>

      <!-- Liste des agents -->
      <h3 class="text-xs font-semibold text-slate-600 uppercase tracking-wider mb-3">Agents enregistrés</h3>
      {#if loadError}
        <p class="text-signal-red text-sm">{loadError}</p>
      {:else if agents.length === 0}
        <p class="text-slate-600 text-sm">Aucun agent enregistré.</p>
      {:else}
        <div class="card overflow-hidden">
          <table class="w-full text-sm">
            <thead>
              <tr class="border-b border-white/[0.06] text-xs uppercase tracking-wider text-slate-600">
                <th class="px-4 py-3 text-left font-medium">Statut</th>
                <th class="px-4 py-3 text-left font-medium">Hostname</th>
                <th class="px-4 py-3 text-left font-medium">IP</th>
                <th class="px-4 py-3 text-left font-medium">Arch / OS</th>
                <th class="px-4 py-3 text-left font-medium">Alias</th>
                <th class="px-4 py-3 text-right font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {#each agents as agent (agent.id)}
                <tr class="border-b border-white/[0.04] last:border-0 hover:bg-white/[0.025] transition-colors">
                  <td class="px-4 py-3">
                    <div class="flex items-center gap-2">
                      <span class={agent.online ? "dot-online" : "dot-offline"}></span>
                      <span class="text-xs {agent.online ? 'text-signal-green' : 'text-slate-600'}">
                        {agent.online ? "En ligne" : "Hors ligne"}
                      </span>
                    </div>
                  </td>
                  <td class="px-4 py-3 font-mono text-xs text-slate-400">{agent.hostname}</td>
                  <td class="px-4 py-3 font-mono text-xs text-slate-500">{agent.ip_address || "—"}</td>
                  <td class="px-4 py-3 text-xs text-slate-600 font-mono">{agent.arch || "—"} / {agent.os || "—"}</td>
                  <td class="px-4 py-3">
                    <input
                      type="text"
                      bind:value={editing[agent.id]}
                      placeholder={agent.hostname}
                      class="bg-abyss-700 border border-white/[0.08] rounded-lg px-2.5 py-1.5
                             text-xs text-slate-100 placeholder-slate-700 outline-none w-36
                             focus:border-emerald/60 focus:ring-1 focus:ring-emerald/30 transition-all"
                    />
                  </td>
                  <td class="px-4 py-3 text-right">
                    <div class="flex items-center justify-end gap-2">
                      <button
                        onclick={() => saveAlias(agent)}
                        disabled={saving === agent.id || editing[agent.id] === agent.alias}
                        class="px-3 py-1.5 rounded-lg text-xs font-medium transition-all disabled:opacity-30
                               bg-emerald/10 hover:bg-emerald/20 text-emerald border border-emerald/20">
                        {saving === agent.id ? "…" : "Sauvegarder"}
                      </button>
                      <button
                        onclick={() => removeAgent(agent)}
                        disabled={deleting === agent.id}
                        class="px-3 py-1.5 rounded-lg text-xs font-medium transition-all disabled:opacity-30
                               bg-signal-red/10 hover:bg-signal-red/20 text-signal-red border border-signal-red/20">
                        {deleting === agent.id ? "…" : "Supprimer"}
                      </button>
                    </div>
                  </td>
                </tr>
              {/each}
            </tbody>
          </table>
        </div>
      {/if}
    </section>

  </main>
</div>
