<script lang="ts">
  import stuffLogClient from "../clients/stufflog";
  import IconSelect from "../components/IconSelect.svelte";
  import Modal from "../components/Modal.svelte";
  import { iconNames } from "../external/icons";
  import modalStore from "../stores/modal";
  import projectStore, { fpProjectStore } from "../stores/project";

  let endTime = "";
  let name = "";
  let description = "";
  let icon = iconNames[0];
  let error = null;

  function onSubmit() {
    stuffLogClient.createProject({
      active: true,
      endTime: ( endTime == "" ) ? null : new Date(endTime),

      name, description, icon,
    }).then(() => {
      projectStore.markStale();
      if (endTime !== "") {
        fpProjectStore.markStale();
      }
      modalStore.close();
    }).catch(err => {
      error = err.message ? err.message : err.toString();
    })

    error = null;
  }

  function onClose() {
    modalStore.close();
  }
</script>

<Modal show title="Add Project" error={error} closable on:close={onClose}>
  <form on:submit|preventDefault={onSubmit}>
    <label for="name">Name</label>
    <input name="name" type="text" bind:value={name} />
    <label for="description">Description</label>
    <textarea name="description" bind:value={description} />
    <label for="itemId">Icon</label>
    <IconSelect bind:value={icon} />
    <label for="endTime">Deadline (Optional)</label>
    <input name="endTime" type="datetime-local" bind:value={endTime} />

    <hr />

    <button type="submit">Add Project</button>
  </form>
</Modal>