<script lang="ts">
  import { navigate } from "svelte-routing";

  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 ProjectGroupSelect from "../components/ProjectGroupSelect.svelte";
  import StartTimeSelect from "../components/StartTimeSelect.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: "",
    groupId: null,
    name: "",
    description: "",
    icon: DEFAULT_ICON,
    active: false,
    statusTag: "to do",
    createdTime: "",
    tasks: [],
    favorite: false,
    subtractAmount: 0,
    tags: [],
    taskSortFields: ["status"],
    subtractions: [],
  }
  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") {
    project.groupId = md.groupId;
  } else {
    throw new Error("Wrong form")
  }

  let startTime = formatFormTime(project.startTime);
  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 subtractAmount = project.subtractAmount;
  let groupId = project.groupId || "";
  let error = null;
  let loading = false;
  let tags = project.tags.join(", ");
  let taskSortFields = project.taskSortFields.join(", ");

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

    const iconChanged = icon !== project.icon;

    if (creation) {
      stuffLogClient.createProject({
        active: statusTag === "",
        groupId: groupId || void(0),
        startTime: ( startTime == "" ) ? null : new Date(startTime),
        endTime: ( endTime == "" ) ? null : new Date(endTime),
        statusTag: statusTag !== "" ? statusTag : null,
        subtractAmount: Math.min(subtractAmount, 0),
        tags: tags.length > 0 ? tags.split(",").map(t => t.trim()) : [],
        taskSortFields: taskSortFields.length > 0 ? taskSortFields.split(",").map(t => t.trim()) : [],

        name, description, icon, favorite,
      }).then(newProject => {
        markStale("project", "task");
        modalStore.close();

        navigate(`/questlog/${newProject.groupId || "META_UNGROUPED"}/${newProject.id}`);
      }).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, {
        groupId: groupId || "",
        endTime: ( endTime == "" ) ? null : new Date(endTime),
        clearEndTime: ( endTime == "" ),
        startTime: ( startTime == "" ) ? null : new Date(startTime),
        clearStartTime: ( startTime == "" ),
        active: statusTag === "",
        statusTag: statusTag || null,
        clearStatusTag: statusTag === "",
        subtractAmount: subtractAmount,
        setTags: tags.length > 0 ? tags.split(",").map(t => t.trim()) : [],
        taskSortFields: taskSortFields.length > 0 ? taskSortFields.split(",").map(t => t.trim()) : [],

        name, description, icon, favorite,
      }).then(() => {
        markStale("project", "task");
        if (iconChanged) {
          markStale("log");
        }
        modalStore.close();

        navigate(`/questlog/${groupId || "META_UNGROUPED"}/${project.id}`);
      }).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="group">Project Group</label>
    <ProjectGroupSelect optional name="group" disabled={deletion} bind:value={groupId} />
    <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</label>
    <DeadlineSelect disabled={deletion} bind:value={endTime} />
    {#if endTime != ""}
      <label for="endTime">Start time</label>
      <StartTimeSelect disabled={deletion} bind:value={startTime} />
      <label for="subtractAmount">Subtract progress</label>
      <input disabled={deletion} name="subtractAmount" type="number" bind:value={subtractAmount} />  
    {/if}
    <label for="statusTag">Status</label>
    <StatusTagSelect disabled={deletion} isProject bind:value={statusTag} />
    <label for="tags">Tags (Comma Separated)</label>
    <input disabled={deletion} name="tags" type="text" bind:value={tags} />
    <label for="tags">Task sorting fields (Comma Separated; time, name, status)</label>
    <input disabled={deletion} name="tags" type="text" bind:value={taskSortFields} />

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

    <hr />

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