<template>
  <div class="form-group">
    <label v-if="label" class="form-label" :for="id">
      {{ label }}
      <span v-if="$attrs.required !== undefined" class="form-required">*</span>
    </label>
    <div :class="{'input-group': withButtons}">
      <flat-pickr
        v-bind="$attrs"
        v-on="$listeners"
        :config="config"
        class="form-control"
        placeholder="Select date"
        name="date"
        :class="{ 'is-invalid': hasError }"
      ></flat-pickr>
      <div class="input-group-btn" v-if="withButtons">
        <eb-button kind="secondary" icon="calendar" title="Toggle" data-toggle>
          <span aria-hidden="true" class="sr-only">Toggle</span>
        </eb-button>

        <eb-button kind="secondary" icon="x" title="Clear" data-clear>
          <span aria-hidden="true" class="sr-only">Clear</span>
        </eb-button>
      </div>
    </div>
    <div v-if="hasError" class="invalid-feedback d-block">
      <slot name="invalid-feedback">{{ getError }}</slot>
    </div>
  </div>
</template>

<script>
import flatPickr from 'vue-flatpickr-component';
import 'flatpickr/dist/flatpickr.css';
import EbButton from '../eb-button/eb-button';
import ErrorMixin from '../../../mixins/error-mixin';

export default {
  name: 'EbDatePicker',

  inheritAttrs: false,

  mixins: [ErrorMixin],

  components: {
    flatPickr,
    EbButton
  },

  props: {
    withButtons: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default() {
        return `date-picker-${this._uid}`;
      }
    },
    config: {
      type: Object,
      default: function() {
        return {
          enableTime: true,
          wrap: true, // set wrap to true only when using 'input-group'
          altFormat: 'F j, Y h:i K',
          altInput: true,
          dateFormat: 'Y-m-d H:i:S'
        };
      }
    },
    label: String
  },
  mounted() {
    this.config.wrap = this.withButtons;
  }
};
</script>

<style>
.flatpickr-current-month .flatpickr-monthDropdown-months {
  appearance: menulist;
  background: transparent !important;
  border: none;
  border-radius: 0;
  box-sizing: border-box;
  color: inherit;
  cursor: pointer;
  font-size: inherit;
  font-family: inherit;
  font-weight: 300;
  height: 22px;
  line-height: inherit;
  margin: -1px 0 0 0;
  outline: none;
  padding: 0 0 0 0.5ch;
  position: relative;
  vertical-align: initial;
  -webkit-box-sizing: border-box;
  -webkit-appearance: menulist;
  -moz-appearance: menulist;
  width: auto;
}
</style>
