<script lang="ts">
  import stuffLogClient from "../clients/stufflog";
  import Modal from "../components/Modal.svelte";
  import goalStore, { fpGoalStore } from "../stores/goal";
  import modalStore from "../stores/modal";
  import projectStore, { fpProjectStore } from "../stores/project";
  import { formatFormTime } from "../utils/time";

  const md = $modalStore;
  if (md.name !== "task.edit") {
    throw new Error("Wrong form");
  }

  let task = md.task
  let name = task.name;
  let description = task.description;
  let itemAmount = task.itemAmount;
  let active = task.active;
  let endTime = task.endTime ? formatFormTime(task.endTime) : "";
  let error = null;

  function onSubmit() {
    stuffLogClient.updateTask(task.id, {
      endTime: (endTime == "") ? null : new Date(endTime),
      clearEndTime: endTime == "",

      name, description, itemAmount, active,
    }).then(() => {
      projectStore.markStale();
      fpProjectStore.markStale();
      goalStore.markStale();
      fpGoalStore.markStale();
      modalStore.close();
    })

    error = null;
  }

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

<Modal show title="Add Task" 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="name">Item</label>
    <input disabled name="name" type="text" value={task.item.name} />
    <label for="itemAmount">Amount</label>
    <input name="itemAmount" type="number" bind:value={itemAmount} />
    <label for="endTime">Deadline (Optional)</label>
    <input name="endTime" type="datetime-local" bind:value={endTime} />
    <input id="active" type="checkbox" bind:checked={active} />
    <label for="active">Task is active/incomplete</label>

    <hr />

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