<template>

  <div class="itf-label" :class="{'has-validation': hasState, 'no-details': hideDetails, 'row': left}">
    <slot name="label" v-bind="{ required, label, left }">
      <div :class="{'col-md-4': left}">
        <label class="itf-label__label form-label d-flex" v-if="label">
          {{label}}
          <span class="star" v-if="required">*</span>
          <itf-tooltip v-if="helpTooltip" class="align-items-center">
            <template #activator><itf-icon name="help-alt" new class="itf-label__tooltip ms-1 mb-1" /></template>
            {{helpTooltip}}
            <div><a href="" @click.prevent.stop="onDetailsClick" v-if="helpDetails" v-text="helpDetails"></a></div>
          </itf-tooltip>
          <slot name="after-label"></slot>
        </label>
        <div v-if="left && helpText">
          <small class="text-muted" v-html="helpText"></small>
        </div>
      </div>
    </slot>

    <div :class="{'is-invalid': hasState && hasError, 'is-valid': hasState && hasSuccess, 'col-md-8': left}">
      <slot :validate="doValidation"></slot>
    </div>

    <div v-if="!hideDetails" class="itf-label__errors mb-1" :class="{'invalid-feedback': hasState && hasError, 'valid-feedback': hasState && hasSuccess}">
      <slot v-if="validations.length" name="errors" :errors="validations">
        <div v-for="(error, n) in validations" :key="n">
          <slot name="error-text"><span v-html="error"></span></slot>
        </div>
      </slot>
      <div v-else-if="helpText && !left" v-html="helpText"></div>
    </div>
  </div>

</template>
<script>
import { Component, Prop, Inject, Mixins } from 'vue-property-decorator';
import ValidatableMixin from '../../mixins/ValidatableMixin';
import itfIcon from '../icon/Icon.vue';
import itfTooltip from '../tooltip/Tooltip.vue';

export default
@Component({
  name: 'itfLabel',
  components: {
    itfIcon,
    itfTooltip
  },
  provide() {
    return { itemLabel: this }; // do not use Provide from vue-property-decorator
  }
})
class itfLabel extends Mixins(ValidatableMixin) {
  @Inject({ default: null }) form;

  @Prop() value;

  @Prop(String) label;
  @Prop(String) helpText;
  @Prop(String) helpTooltip;
  @Prop(String) helpDetails;
  @Prop(Boolean) required;
  @Prop(Boolean) hideDetails;
  @Prop(Boolean) left;

  isHasError() {
    return this.hasState && this.hasError;
  }

  isHasSuccess() {
    return this.hasState && this.hasSuccess;
  }

  get hasTooltip () {
    return !!this.$slots.tooltip;
  }

  onDetailsClick() {
    this.$emit('details');
  }
}
</script>
