<script lang="ts">
  import {
    Badge,
    Button,
    Modal,
    Spinner,
    Table,
    TableBody,
    TableBodyCell,
    TableBodyRow,
    TableHead,
    TableHeadCell,
  } from "flowbite-svelte";
  import BookEditor from "../components/BookEditor.svelte";
  import { onMount } from "svelte";
  import {
    GetBooks,
    SaveBook,
    BookLended,
    SaveLending,
  } from "../../wailsjs/go/main/App";
  import { model } from "../../wailsjs/go/models";
  import LendingEditor from "../components/LendingEditor.svelte";

  let books: model.Book[] = $state();

  let book: model.Book | null = $state(null);
  let lending: model.Lending | null = $state(null);
  let modal: boolean = $state(false);

  function update() {
    GetBooks().then((bs) => (books = bs));
  }
  onMount(update);
</script>

{#if book}
  <Modal bind:open={modal} title="Book">
    <BookEditor
      bind:book
      onsubmit={(b) => {
        SaveBook(b).then(update);
        modal = false;
        book = null;
      }}
    />
  </Modal>
{:else if lending}
  <Modal bind:open={modal} title="New Lending">
    <LendingEditor
      bind:lending
      onsubmit={(l) => {
        SaveLending(l).then(update);
        modal = false;
        lending = null;
      }}
    />
  </Modal>
{/if}

<Table>
  <TableHead>
    <TableHeadCell>Title</TableHeadCell>
    <TableHeadCell>Author</TableHeadCell>
    <TableHeadCell>ISBN</TableHeadCell>
    <TableHeadCell>Status</TableHeadCell>

    <TableHeadCell>
      <Button
        onclick={() => {
          book = new model.Book();
          modal = true;
        }}>New</Button
      ></TableHeadCell
    >
  </TableHead>
  <TableBody>
    {#each books as b}
      <TableBodyRow>
        <TableBodyCell>{b.Title}</TableBodyCell>
        <TableBodyCell>{b.Author.Name}</TableBodyCell>
        <TableBodyCell>{b.ISBN}</TableBodyCell>
        <TableBodyCell
          >{#await BookLended(b.ID)}
            <Spinner />
          {:then lended}
            {#if lended}
              <Badge color="red">Lended</Badge>
            {:else}
              <Badge class="text-sm" color="green">Available</Badge>
            {/if}
          {/await}</TableBodyCell
        >

        <TableBodyCell>
          {#await BookLended(b.ID) then lended}
            {#if !lended}
              <Button
                onclick={() => {
                  lending = new model.Lending();
                  lending.BookID = b.ID;
                  lending.DueDate = new Date();
                  modal = true;
                }}>Lend</Button
              >
            {/if}
          {/await}
          <Button
            onclick={() => {
              book = b;
              modal = true;
            }}>Edit</Button
          >
        </TableBodyCell>
      </TableBodyRow>
    {/each}
  </TableBody>
</Table>
