<script lang="ts">
  // "New note" dialog — the create half of the wiki. A plain toggle group for
  // kind (document/investigation/runbook) rather than the Select primitive:
  // three fixed, always-visible options don't need a popover, and this
  // mirrors the same toggle-group pattern WikiTree already uses for its
  // group-by switch.
  import { createKnowledge, KnowledgeApiError } from '$lib/api'
  import * as Dialog from '$lib/components/ui/dialog'
  import { Button } from '$lib/components/ui/button'
  import { Input } from '$lib/components/ui/input'
  import { Textarea } from '$lib/components/ui/textarea'

  let {
    open = $bindable(false),
    onCreated
  }: {
    open: boolean
    onCreated: (slug: string) => void
  } = $props()

  const KINDS = ['document', 'investigation', 'runbook'] as const
  type Kind = (typeof KINDS)[number]

  let title = $state('')
  let kind = $state<Kind>('document')
  let folder = $state('')
  let tags = $state('')
  let content = $state('')
  let saving = $state(false)
  let error = $state('')

  function reset(): void {
    title = ''
    kind = 'document'
    folder = ''
    tags = ''
    content = ''
    error = ''
  }

  async function submit(): Promise<void> {
    if (!title.trim() || !content.trim()) {
      error = 'Title and content are required.'
      return
    }
    saving = true
    error = ''
    try {
      const result = await createKnowledge({
        title: title.trim(),
        content: content.trim(),
        kind,
        folder: folder.trim() || undefined,
        tags: tags
          .split(',')
          .map((t) => t.trim())
          .filter(Boolean)
      })
      onCreated(result.slug)
      open = false
      reset()
    } catch (e) {
      error =
        e instanceof KnowledgeApiError
          ? `${e.message}${e.detail ? ` — ${e.detail}` : ''}`
          : 'Create failed.'
    } finally {
      saving = false
    }
  }
</script>

<Dialog.Root bind:open>
  <Dialog.Content class="sm:max-w-lg">
    <Dialog.Header>
      <Dialog.Title>New knowledge note</Dialog.Title>
    </Dialog.Header>

    <div class="flex flex-col gap-3">
      {#if error}
        <p
          class="rounded border border-destructive/30 bg-destructive/5 px-2 py-1 text-xs text-destructive"
        >
          {error}
        </p>
      {/if}

      <label class="flex flex-col gap-1 text-xs text-muted-foreground" for="new-note-title">
        Title
        <Input id="new-note-title" bind:value={title} placeholder="Short, specific, searchable" />
      </label>

      <div class="flex items-center gap-2">
        <span class="text-xs text-muted-foreground">Type</span>
        <div class="inline-flex overflow-hidden rounded-md border">
          {#each KINDS as k (k)}
            <button
              type="button"
              class="px-2 py-1 text-xs {kind === k
                ? 'bg-secondary text-secondary-foreground'
                : 'hover:bg-muted/50'}"
              onclick={() => (kind = k)}
            >
              {k}
            </button>
          {/each}
        </div>
      </div>

      <label class="flex flex-col gap-1 text-xs text-muted-foreground" for="new-note-folder">
        Folder <span class="text-muted-foreground/70">(optional — defaults to "operator")</span>
        <Input
          id="new-note-folder"
          bind:value={folder}
          placeholder="e.g. containers, infrastructure"
        />
      </label>

      <label class="flex flex-col gap-1 text-xs text-muted-foreground" for="new-note-tags">
        Tags <span class="text-muted-foreground/70">(comma-separated, optional)</span>
        <Input id="new-note-tags" bind:value={tags} placeholder="oom, rclone, gotcha" />
      </label>

      <label class="flex flex-col gap-1 text-xs text-muted-foreground" for="new-note-content">
        Content (markdown)
        <Textarea
          id="new-note-content"
          bind:value={content}
          class="min-h-[160px] font-mono text-xs"
        />
      </label>
    </div>

    <Dialog.Footer>
      <Button variant="ghost" onclick={() => (open = false)} disabled={saving}>Cancel</Button>
      <Button onclick={submit} disabled={saving}>{saving ? 'Creating…' : 'Create'}</Button>
    </Dialog.Footer>
  </Dialog.Content>
</Dialog.Root>
