<script lang="ts">
  import { Button } from "$lib/components/ui/button";
  import * as Dialog from "$lib/components/ui/dialog";
  import ItemForm from "./items/ItemForm.svelte";
  import { goto } from "$app/navigation";

  let {
    data,
  }: {
    data: { itemsForParent: { id: string; Item: string; SKU: string }[] };
  } = $props();

  let dialogOpen = $state(false);
  const itemsForParent = $derived(data?.itemsForParent ?? []);

  function onSuccess() {
    dialogOpen = false;
    goto("/items");
  }
</script>

<main class="flex min-h-screen flex-col items-center justify-center gap-6 p-8">
  <h1 class="text-2xl font-semibold">Stackq</h1>
  <p class="text-muted-foreground">Svelte 5 + shadcn-svelte + PocketBase</p>
  <div class="flex w-full max-w-xs flex-col gap-2">
    <a href="/items" class="block">
      <Button class="w-full">Items table</Button>
    </a>
    <Button class="w-full" variant="outline" onclick={() => (dialogOpen = true)}>
      New item
    </Button>
    <a href="/logout" class="block">
      <Button class="w-full" variant="outline">Log out</Button>
    </a>
  </div>
</main>

<Dialog.Root bind:open={dialogOpen}>
  <Dialog.Content class="max-h-[90vh] overflow-y-auto sm:max-w-[500px]">
    <Dialog.Header>
      <Dialog.Title>New item</Dialog.Title>
      <Dialog.Description>Add a new Stackq item.</Dialog.Description>
    </Dialog.Header>
    <ItemForm
      itemsForParent={itemsForParent}
      action="/items?/create"
      submitLabel="Create"
      onSuccess={onSuccess}
    />
  </Dialog.Content>
</Dialog.Root>
