<script lang="ts">
  import {
    state as _state,
    createAuth,
    deleteAuth,
    renameAuth,
    updateAuthParams,
  } from "$lib/state.svelte";

  import { Button } from "$lib/components/ui/button";
  import { Trash, Plus } from "@lucide/svelte";
  import { Input } from "./ui/input";
  import Editable from "./Editable.svelte";
  import AuthParams from "./AuthParams.svelte";
</script>

<div class="space-y-6">
  <div>
    <h1 class="p-2 text-lg">Authentication</h1>
    <p class="p-2 text-sm">
      Create workspace-wide authentication schemes. Use the schemes created here
      in request/collection tabs.
    </p>
  </div>

  <!-- Create auth -->
  <div class="space-y-2">
    <div class="flex gap-2">
      <Button variant="outline" onclick={() => createAuth("Token")}>
        <Plus class="h-4 w-4 mr-2" /> Token
      </Button>
      <Button variant="outline" onclick={() => createAuth("Basic")}>
        <Plus class="h-4 w-4 mr-2" /> Basic
      </Button>
      <Button variant="outline" onclick={() => createAuth("OAuth")}>
        <Plus class="h-4 w-4 mr-2" /> OAuth
      </Button>
    </div>
  </div>

  {#each _state.auth as auth}
    <div class="p-2 border rounded-xl">
      <div class="mx-2 flex items-center border-b space-y-2">
        <div class="w-full">
          <Editable
            bind:value={auth.name}
            onSave={(value) => {
              renameAuth(auth.id, value);
            }}
          >
            {#snippet display({ value, startEdit })}
              <h2 ondblclick={startEdit}>
                {auth.name}
              </h2>
            {/snippet}
          </Editable>
        </div>
        <Trash
          class="mb-2 h-4 w-4 cursor-pointer text-muted-foreground hover:text-destructive"
          size={16}
          onclick={() => deleteAuth(auth.id)}
        />
      </div>
      <div class="p-2">
        <AuthParams bind:auth readonly={false} />
      </div>
    </div>
  {/each}
</div>
