<script lang="ts">
  import { onMount } from "svelte";
  import {
    GetThings,
    DeleteThing,
    NewThing,
  } from "../../wailsjs/go/things/Service";
  import { things } from "../../wailsjs/go/models";
  import {
    Label,
    Input,
    Button,
    Table,
    TableHead,
    TableHeadCell,
    TableBody,
    TableBodyRow,
    TableBodyCell,
  } from "flowbite-svelte";

  let name: string;
  let thingsList: things.Thing[] = [];

  function update() {
    GetThings().then((ts) => {
      thingsList = ts;
    });
  }

  function submit(e: Event) {
    e.preventDefault();
    NewThing(name).then(update);
    name = "";
  }

  function deleteEvent(id: number) {
    DeleteThing(id).then(update);
  }

  onMount(update);
</script>

<form class="max-w-96 m-5 grid-cols-1 gap-10" on:submit={submit}>
  <div class="m-5">
    <Label for="first_name" class="mb-2">First name</Label>
    <Input type="text" placeholder="John" bind:value={name} required />
  </div>
  <div class="m-5">
    <Button type="submit">Submit</Button>
  </div>
</form>
<Table>
  <TableHead>
    <TableHeadCell>ID</TableHeadCell>
    <TableHeadCell>Name</TableHeadCell>

    <TableHeadCell>Delete</TableHeadCell>
  </TableHead>
  <TableBody>
    {#each thingsList as t}
      <TableBodyRow>
        <TableBodyCell>
          {t.ID}
        </TableBodyCell>

        <TableBodyCell>
          {t.Name}
        </TableBodyCell>
        <TableBodyCell>
          <Button on:click={(_) => deleteEvent(t.ID)}>Delete</Button>
        </TableBodyCell>
      </TableBodyRow>
    {/each}
  </TableBody>
</Table>
