<script lang="ts">
  import { endOfMonth, endOfWeek, endOfYear, formatDate, nextMonth, nextYear } from "$lib/utils/date";

  export let value: string;
  export let openDate: Date;
  export let notScheduledText = "Not Scheduled";

  let selected: "none" | "date" | "eod" | "eot" | "eow" | "eonw" | "eonnw" | "eom" | "eonm" | "eoy" | "eony" = !!value ? "date" : "none";

  $: {
    switch (selected) {
      case "eod": 
        value = formatDate(openDate);
        break;
      case "eot": 
        value = formatDate(new Date(openDate.getTime() + 86400000));
        break;
      case "eow":
        value = formatDate(endOfWeek(openDate))
        break;
      case "eonw":
        value = formatDate(endOfWeek(new Date(openDate.getTime() + (86400000 * 7))))
        break;
      case "eonnw":
        value = formatDate(endOfWeek(new Date(openDate.getTime() + (86400000 * 14))))
        break;
      case "eom":
        value = formatDate(endOfMonth(openDate))
        break;
      case "eonm":
        value = formatDate(endOfMonth(nextMonth(openDate)))
        break;
      case "eoy":
        value = formatDate(endOfYear(openDate))
        break;
      case "eony":
        value = formatDate(endOfYear(nextYear(openDate)))
        break;
      case "date":
        if (value == "") {
          value = formatDate(openDate);
        }
        break;
      case "none":
        value = "";
        break;
    }
  }
</script>

<select bind:value={selected}>
  <option value="none">{notScheduledText}</option>
  <option value="eod">Today</option>
  <option value="eot">Tomorrow</option>
  <option value="eow">Sunday</option>
  <option value="eonw">Next Sunday</option>
  <option value="eonnw">The Sunday after Next</option>
  <option value="eom">End of Month</option>
  <option value="eonm">End of Next Month</option>
  <option value="eoy">End of Year</option>
  <option value="eony">End of Next Year</option>
  <option value="date">Specific Date</option>
</select>

{#if selected !== "none"}
  <input type="date" disabled={selected !== "date"} bind:value={value} />
{/if}

<style>
  select {
    margin-bottom: 0.25em !important;
  }

  input {
    margin-top: 0 !important;
    resize: none !important;
  }
</style>