export default {
  props: ['fieldModel', 'componentFieldSettings', 'fieldName'],
  data() {
    const { date_type: type } = this.componentFieldSettings.settings;
    return {
      dateValue: '',
      timeValue: '',
      isRequired: this.componentFieldSettings.required,
      isTimeRequired: false,
      type,
    };
  },
  watch: {
    dateValue() {
      this.validateTimeRequirement();
      this.updateFieldModel();
    },
    timeValue() {
      this.updateFieldModel();
    }
  },
  mounted() {
    if (this.fieldModel.value) {
      const [datePart, timePart] = this.fieldModel.value.split('T');
      if (datePart) {
        this.dateValue = datePart;
      }

      if (timePart) {
        this.timeValue = timePart;
      }
    }
  },
  methods: {
    validateTimeRequirement() {
      if (this.type === 'datetime') {
        this.isTimeRequired = !this.isRequired && this.dateValue !== '';
      }
      else {
        this.isTimeRequired = false;
      }
    },
    updateFieldModel() {
      if (this.type === 'date') {
        this.fieldModel.value = this.dateValue;
      }
      else {
        if (this.dateValue && this.timeValue) {
          this.fieldModel.value = `${this.dateValue}T${this.timeValue}`;
        }
      }
    },
  },
  template: `
    <div class="field--type-datetime field--widget-datetime-default">
      <fieldset :id="fieldName" class="fieldset form-item form-wrapper">
        <legend class="fieldset__legend fieldset__legend--visible">
          <span class="fieldset__label" :class="{ 'form-required': isRequired }">{{ componentFieldSettings.label }}</span>
        </legend>
        <div class="fieldset__wrapper">
          <div class="form-item form-datetime-wrapper">
            <div :id="fieldName" class="form-items-inline">
              <div class="form-item form-type--date form-item--no-label">
                <label :for="fieldName + '-value-date'" class="form-item__label visually-hidden">Date</label>
                <input type="date" :id="fieldName + '-value-date'" :name="fieldName + '-value-date'" v-model="dateValue" class="form-date form-element form-element--type-date form-element--api-date" :required="isRequired">
              </div>
              <div v-if="type === 'datetime'" class="form-item form-type--date form-item--no-label">
                <label :for="fieldName + '-value-time'" class="form-item__label visually-hidden">Time</label>
                <input type="time" step="1" :id="fieldName + '-value-time'" :name="fieldName + '-value-time'" v-model="timeValue" class="form-time form-element form-element--type-time form-element--api-date" :required="isRequired || isTimeRequired">
              </div>
            </div>
          </div>
        </div>
      </fieldset>
    </div>
  `
};
