<script lang="ts">
  import stuffLogClient from "../clients/stufflog";
  import Checkbox from "../components/Checkbox.svelte";
  import DeadlineSelect from "../components/DeadlineSelect.svelte";
  import IconSelect from "../components/IconSelect.svelte";
  import Modal from "../components/Modal.svelte";
  import StatusTagSelect from "../components/StatusTagSelect.svelte";
  import { DEFAULT_ICON } from "../external/icons";
  import type { ProjectResult } from "../models/project";
  import markStale from "../stores/markStale";
  import modalStore from "../stores/modal";
  import { formatFormTime } from "../utils/time";

  export let deletion = false;
  export let creation = false;

  const md = $modalStore;
  let project: ProjectResult = {
    id: "",
    name: "",
    description: "",
    icon: DEFAULT_ICON,
    active: false,
    statusTag: "to do",
    createdTime: "",
    tasks: [],
    favorite: false,
  }
  let verb = "Add";
  if (md.name === "project.edit" || md.name === "project.delete") {
    project = md.project;
    verb = (md.name === "project.edit") ? "Edit" : "Delete";
  } else if (md.name !== "project.add") {
    throw new Error("Wrong form")
  }

  let endTime = formatFormTime(project.endTime);
  let name = project.name;
  let description = project.description;
  let statusTag = project.statusTag || "";
  let icon = project.icon;
  let favorite = project.favorite;
  let error = null;
  let loading = false;

  function onSubmit() {
    loading = true;
    error = null;

    const iconChanged = icon !== project.icon;

    if (creation) {
      stuffLogClient.createProject({
        active: statusTag === "",
        endTime: ( endTime == "" ) ? null : new Date(endTime),
        statusTag: statusTag !== "" ? statusTag : null,

        name, description, icon, favorite,
      }).then(() => {
        markStale("project", "task");
        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
      })
    } else if (deletion) {
      stuffLogClient.deleteProject(project.id).then(() => {
        markStale("project", "task");
        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
      })
    } else {
      stuffLogClient.updateProject(project.id, {
        endTime: ( endTime == "" ) ? null : new Date(endTime),
        clearEndTime: ( endTime == "" ),
        active: statusTag === "",
        statusTag: statusTag || null,
        clearStatusTag: statusTag === "",

        name, description, icon, favorite,
      }).then(() => {
        markStale("project", "task");
        if (iconChanged) {
          markStale("log");
        }
        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
      })
    }
  }

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

<Modal show title="{verb} Project" error={error} closable on:close={onClose}>
  <form on:submit|preventDefault={onSubmit}>
    <label for="name">Name</label>
    <input disabled={deletion} name="name" type="text" bind:value={name} />
    <label for="description">Description</label>
    <textarea disabled={deletion} name="description" bind:value={description} />
    <label for="itemId">Icon</label>
    <IconSelect disabled={deletion} bind:value={icon} />
    <label for="endTime">Deadline (Optional)</label>
    <DeadlineSelect disabled={deletion} bind:value={endTime} />
    <label for="statusTag">Status</label>
    <StatusTagSelect disabled={deletion} bind:value={statusTag} />

    <Checkbox disabled={deletion} bind:checked={favorite} label="Mark as favorite." />

    <hr />

    <button disabled={loading} type="submit">{verb} Project</button>
  </form>
</Modal>