<script>
  import pluralize from "pluralize";
  import ModalFrame from "../components/ModalFrame";

  import modal from "../stores/modal";
  import stufflog from "../stores/stufflog";

  export let activity = {};
  export let subActivity = {};

  let error = null;
  let id = subActivity.id;
  let name = subActivity.name;
  let unitName = subActivity.unitName;
  let value = subActivity.value;

  function editSubActivity() {
    value = parseFloat(value)
    if (Number.isNaN(value)) {
      error = "Value should be a number."
      value = subActivity.value;
      return
    }

    stufflog.updateActivity(activity.id, {editSub: {id, name, unitName, value}}).then(() => {
      modal.close();
    }).catch(err => {
      error = err.message || err;
      console.warn(err);
    });
  }
</script>

<ModalFrame title={`Edit ${activity.name} Sub-Activity`} error={error} closable on:close={() => modal.close()}>
  <form on:submit|preventDefault={() => editSubActivity()}>
    <label>Name</label>
    <input type="text" bind:value={name} />
    <label>Unit</label>
    <select bind:value={unitName}>
      <option value="minute">minute</option>
      <option value="word">word</option>
      <option value="hour">hour</option>
      <option value="item">item</option>
    </select>
    <label>Value per {pluralize(unitName, 1)}</label>
    <input type="string" bind:value={value} />

    <p>
      1000 points should be equivalent to about an hour of baseline activity. Beyond that, it's
      about incentivitzing the right thing.
    </p>

    <hr />

    <button type="submit">Edit Sub-Activity</button>
  </form>
</ModalFrame>