<script lang="ts">
  import { allOffsets, pastOffsets, CustomDateRange } from "../utils/date-range";
  import type { DateRange } from "../utils/date-range";
  import { formatFormTime } from "../utils/time";

  export let noFuture: boolean = false;
  export let value: DateRange;
  export let styled: boolean = false;
  export let label: string = "Time";
  export let disabled: boolean = false;

  let rangeOptions: DateRange[];
  let selected = value.name;
  let [customMin, customMax] = (value || pastOffsets[0]).calculate(new Date()).map(d => formatFormTime(d));

  $: rangeOptions = noFuture ? pastOffsets : allOffsets;
  $: {
    if (selected === "Specific Dates") {
      value = new CustomDateRange(new Date(customMin), new Date(customMax))
    } else {
      value = rangeOptions.find(v => v.name === selected);
      if (value != null) {
        let [from, to] = value.calculate(new Date()).map(d => formatFormTime(d));
        customMin = from;
        customMax = to;
      } else {
        selected = rangeOptions[0].name;
        value = rangeOptions[0];
      }
    }
  }
</script>

<div class:styled>
  <div>
    <label for="timeRange">{label}</label>
    <select name="timeRange" disabled={disabled} bind:value={selected}>
      {#each rangeOptions as option (option.name)}
        <option value={option.name}>{option.name}</option>
      {/each}
      <option value="Specific Dates">Specific Dates</option>
    </select>
  </div>
  {#if value.name === "Specific Dates"}
    <div>
      <label for="startTime">Start Time</label>
      <input disabled={disabled} name="startTime" type="datetime-local" bind:value={customMin} />
    </div>
    <div>
      <label for="endTime">End Time</label>
      <input disabled={disabled} name="endTime" type="datetime-local" bind:value={customMax} />
    </div>
  {/if}
</div>

<style>
div.styled {
  display: flex;
  flex-direction: row;
  width: 100%;
}

div.styled > div:first {
  width: 20%;
}

div.styled > div {
  padding: 0 0.5em;
  margin: 0 auto;
  width: 35%;
}

div.styled label {
  line-height: 1.5em;
}

div.styled select, div.styled input {
  width: 100%;
  margin-bottom: 0.5em;
  padding: 0.35em;

  background: #222;
  color: #777;
  border: none;
  outline: none;
  resize: vertical;
}
div.styled select {
  padding: 0.46em 0.5ch;
}

div.styled input:focus, div.styled select:focus {
  background: #191919;
  color: #CCC;
  border: none;
  outline: none;
}

@media screen and (max-width: 900px) {
  div.styled {
    flex-direction: column;
    margin-bottom: 1em;
  }

  div.styled > div {
    width: 90%;
  }
}

</style>