<template>
  <div class="pui-datepicker"
    :class="[
      size,
      state,
      {
        'has-icon': icon,
        'has-label': label,
        'has-hint': hint,
        'has-action': (clearable && computedValue && !disabled),
        'filled': isFilled,
        'focused': isFocused,
        'is-required': required
      }
    ]"
    :disabled="disabled"
  >
    <p-icon v-if="icon" :size="size" :icon="icon" />
    <span class="label" v-if="label">{{ label }}</span>
    <date-picker
      :placeholder="computedPlaceholder"
      :disabled="disabled"
      :config="newOptions"
      v-model="computedValue"
      v-bind="$attrs"
      @dp-show="onOpen"
      @dp-hide="onClose"
      @dp-change="onInput"
    />
    <p-tooltip 
      class="hint" 
      v-if="hint"
      :label="hint"
      position="is-top"
      :width="tooltipWidth"
      :is-multiline="hint.length > 80"
      trigger="hover"
    >
      <i class="mdi mdi-information-outline"></i>
    </p-tooltip>
    <div class="action-trigger" v-if="clearable && isFilled && !disabled" @click="clear">
      <i class="mdi mdi-close"></i>
    </div>
  </div>
</template>

<script>
import datePicker from 'vue-bootstrap-datetimepicker';
import icons from './icons';

const isValueEmpty = (value) => {
  return typeof value !== "undefined" && value !== null
}

export default {
  name: 'PDatepicker',
  props: {
    size: String,
    state: String,
    icon: String,
    label: String,
    clearable: Boolean,
    required: Boolean,
    disabled: Boolean,
    value: null,
    hint: String,
    options: Object,
    placeholder: String
  },
  components: {datePicker},
  data() {
    return {
      isFocused: false,
      isFilled: false,
      newValue: this.value,
      newOptions: { ...this.options, icons }
    }
  },
  methods: {
    onOpen() {
      this.isFocused = true
      this.$emit('open')
    },
    onClose(e) {
      this.isFocused = false
      this.$emit('close', e)
    },
    onInput(e) {
      if (isValueEmpty(this.computedValue)) {
        this.isFilled = true
      } else {
        this.isFilled = false
      }

      this.$emit('close', e)
    },
    clear() {
      this.computedValue = null
      this.$emit('clear')
    }
  },
  mounted() {
    if (isValueEmpty(this.value)) {
      this.isFilled = true
    } else {
      this.isFilled = false
    }
  },
  computed: {
    computedPlaceholder() {
      return (this.isFocused || !this.label) ? this.placeholder : null
    },
    computedValue: {
      get() {
        return this.newValue;
      },
      set(value) {
        this.newValue = value;
        this.$emit("input", value);
      },
    },
    tooltipWidth() {
      return (typeof this.hint === 'string' && this.hint.length > 80) ? 200 : 'auto'
    }
  },
  watch: {
    value(value) {
      this.newValue = value;
    },
    options(value) {
      this.newOptions = { ...value, icons }
    }
  },
}
</script>