<script lang="ts">
  import { Button, Input, Label, Modal, Select } from "flowbite-svelte";
  import { model } from "../../wailsjs/go/models";
  import { GetAuthors, SaveAuthor } from "../../wailsjs/go/main/App";
  import AuthorEditor from "./AuthorEditor.svelte";
  import { onMount } from "svelte";

  const ISBNRegex =
    "^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[- ]){4})[- 0-9]{17}$)97[89][- ]?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9]$";

  let {
    book = $bindable(),
    onsubmit = (_) => {},
  }: { book: model.Book; onsubmit: (a: model.Book) => void } = $props();

  let authors: model.Author[] = $state([]);

  let modal: boolean = $state(false);
  let newAuthor: model.Author = $state();

  function update() {
    GetAuthors().then((as) => (authors = as));
  }

  function submit(e: Event) {
    e.preventDefault();
    onsubmit(book);
  }
  onMount(update);
</script>

<Modal bind:open={modal}>
  <AuthorEditor
    author={newAuthor}
    onsubmit={(a) => {
      SaveAuthor(a).then(update);
      modal = false;
    }}
  />
</Modal>

<form onsubmit={submit}>
  <div class="m-5">
    <Label>Name</Label>
    <Input type="text" bind:value={book.Title} />
  </div>

  <div class="m-5">
    <Label>ISBN</Label>
    <Input pattern={ISBNRegex} type="text" bind:value={book.ISBN} />
  </div>
  <div class="m-5">
    <Label>Author</Label>
    <div class="grid grid-cols-5 gap-5">
      <Select
        class="col-span-4"
        items={authors.map((a) => {
          return { value: a.ID, name: a.Name };
        })}
        bind:value={book.AuthorID}
      />
      <Button
        onclick={() => {
          newAuthor = new model.Author();
          modal = true;
        }}>New</Button
      >
    </div>
  </div>
  <div class="m-5">
    <Button type="submit">Save</Button>
  </div>
</form>
