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

  export let thingID: null | number = null;
  let subThings: things.SubThing[] = [];

  function update() {
    if (thingID) {
      GetSubThings(thingID).then((ts) => {
        subThings = ts;
      });
    }
  }

  $: {
    thingID = thingID;
    update();
  }

  let name: string;

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

  function deleteSubThing(id: number) {
    DeleteSubThing(id).then(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 class="m-5">
  <TableHead>
    <TableHeadCell>ID</TableHeadCell>
    <TableHeadCell>Name</TableHeadCell>

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

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