<script>
  import { onMount } from 'svelte'
  import dj from 'dayjs'

  import DateInput from './DateInput.svelte'

  export let start = new Date()
  export let end = new Date()

  function set(interval, amount = 1) {
    return () => {
      start = dj().subtract(amount, interval).startOf('day').toDate()
      end = dj().endOf('day').toDate()
    }
  }

  function all() {
    start = new Date(0)
    end = new Date()
  }

  const intervals = [
    { label: 'Year', set: set('year', 1) },
    { label: 'Month', set: set('month', 1) },
    { label: 'Week', set: set('week', 1) },
    { label: '3 Days', set: set('day', 3) },
    { label: 'Today', set: set('day', 0) },
  ]

  // Init
  onMount(() => set('day', 0)())
</script>

<div class="flex items-center">
  <div class="btn-group">
    {#each intervals as interval (interval.label)}
      <button class="btn btn-sm" on:click={interval.set}>{interval.label}</button>
    {/each}
  </div>
  <div class="spacer" />
  <div class="input-group">
    <DateInput bind:date={start} />
    <DateInput bind:date={end} />
  </div>
</div>

<style>
  .spacer {
    width: 0.5em;
  }
</style>
