<template>
  <div class="itf-inline-edit">
    <div ref="input" class="input" :role="editable ? 'button' : 'textbox'" tabindex="1" @keydown.space="onEnter" @keydown.enter="onEnter" @focus="$emit('focus')" @blur="$emit('blur')">
      <span v-if="value">{{ value | formatDate }}</span>
      <span v-else class="text-muted">Empty</span>
    </div>

    <div style="display: none">
      <div ref="dropdown" class="itf-datepicker__dropdown">
        <itf-date-picker-inline
          :value="value"
          start-view="days"
          display-format="MM/dd/yyyy"
          value-format="yyyy-MM-dd"
          @input="selectInlineDate"
        ></itf-date-picker-inline>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.itf-inline-edit {
  margin: -5px;
  padding: 5px;
}
.itf-inline-edit .input {
  border: 0 none;
  margin: 0;
  outline: 0;
  resize: none;
  background: transparent;
}
</style>
<script>
import {Vue, Component, Model, Watch, Prop} from 'vue-property-decorator';
import itfTextField from '../../text-field/TextField.vue';
import itfDatePickerInline from '../../datepicker/DatePickerInline.vue';
import tippy from 'tippy.js';
import { formatDate } from '../../../helpers/formatters';

export default @Component({
  name: 'itfCustomizeInlineDate',
  components: {
    itfTextField,
    itfDatePickerInline
  },
  filters: {
    formatDate
  }
})

class itfCustomizeInlineText extends Vue {
  @Model('input') value;
  @Prop({ type: String, default: 'bottom-start' }) placement;
  @Prop({ type: Boolean, default: false }) editable;

  tooltip = null;

  mounted() {
    if (!this.editable) {
      return;
    }
    const context = this.$el.closest('.itf-append-context') || document.body;
    this.tooltip = tippy(this.$refs.input, {
      interactiveBorder: 30,
      interactiveDebounce: 75,
      animation: 'scale',
      arrow: true,
      content: this.$refs.dropdown,
      allowHTML: true,
      trigger: 'click',
      interactive: true,
      placement: this.placement,
      appendTo: context
    });
  }

  selectInlineDate(date) {
    this.$emit('input', date);
    this.tooltip.hide();
    this.isFocused = false;
  }

  onEnter() {
    this.tooltip.show();
  }
}
</script>
