export default {
  props: ['fieldModel', 'componentFieldSettings', 'fieldName'],
  emits: ['reset_conditional_fields'],
  data () {
    const { options, condition: isConditional,  conditions: fieldConditions} = this.componentFieldSettings.settings;
    if (this.fieldModel.value === '') {
      this.fieldModel.value = options[0].key;
      if (this.componentFieldSettings.settings.set_default_value) {
        this.fieldModel.value = this.componentFieldSettings.settings.default_value;
      }
    }

    return {
      options,
      isConditional,
      fieldConditions,
      isRequired: this.componentFieldSettings.required
    };
  },
  mounted() {
    if (this.isConditional) {
      const selectElement = document.getElementById(this.fieldName);
      const formContainer = selectElement.closest('.castorcito-form--fields');
      const searchKey = Object.entries(this.options).find(([_, val]) => val.key === this.fieldModel.value);
      const updateFieldVisibility = setInterval(() => {
        this.updateFieldVisibility(formContainer, this.fieldConditions[searchKey[0]]);
        clearInterval(updateFieldVisibility);
      }, 100);
    }
  },
  methods: {
    handleSelectChange(event) {
      const selectedKey = event.target.options[event.target.selectedIndex].getAttribute('data-key');
      const formContainer = event.target.closest('.castorcito-form--fields');
      this.updateFieldVisibility(formContainer, this.fieldConditions[selectedKey], true);
    },
    updateFieldVisibility(formContainer, fieldConditions, shouldResetFields = false) {
      const baseName = this.fieldName.substring(0, this.fieldName.lastIndexOf(this.componentFieldSettings.name));
      const fields = formContainer.querySelectorAll(':scope > div[data-field-name]');
      let resetFields = [];

      fields.forEach(field => {
        const fieldName = field.getAttribute('data-field-name');

        if (fieldName !== this.componentFieldSettings.name) {
          const elements = field.querySelectorAll(`[name^="${baseName + fieldName}"]`);
          elements.forEach(element => { this.toggleRequired(element, fieldConditions, fieldName) });
          field.style.display = 'block';

          if (
            (fieldConditions.state === 'visible' && !fieldConditions.fields[fieldName]) ||
            (fieldConditions.state === 'invisible' && fieldConditions.fields[fieldName])) {
            field.style.display = 'none';
            resetFields.push(fieldName);
          }
        }
      });

      if (shouldResetFields && resetFields.length) {
        this.$emit('reset_conditional_fields', resetFields);
      }
    },
    toggleRequired(element, fieldConditions, fieldName) {
      if (
        (fieldConditions.state === 'visible' && !fieldConditions.fields[fieldName]) ||
        (fieldConditions.state === 'invisible' && fieldConditions.fields[fieldName])
      ) {
        if (element.hasAttribute('required')) {
          element.dataset.wasRequired = 'true';
          element.removeAttribute('required');
        }
      } else {
        if (element.dataset.wasRequired === 'true') {
          element.setAttribute('required', 'true');
          delete element.dataset.wasRequired;
        }
      }
    }
  },
  template: `
    <div class="form-item form-type--textfield">
      <div class="form-item form-type--select">
        <label v-if="!componentFieldSettings.hide_label" :for="fieldName" class="form-item__label" :class="{'form-required': isRequired }">{{ componentFieldSettings.label }}</label>
        <select
          v-if="isConditional"
          class="form-select form-element form-element--type-select"
          v-model="fieldModel.value"
          @change="handleSelectChange"
          :id="fieldName"
          :name="fieldName"
          :required="isRequired"
        >
          <option v-for="(option, key) in options" :key="key" :value="option.key" :data-key="key">{{ option.label }}</option>
        </select>
        <select
          v-else
          class="form-select form-element form-element--type-select"
          v-model="fieldModel.value"
          :id="fieldName"
          :name="fieldName"
          :required="isRequired"
        >
          <option v-for="(option, key) in options" :key="key" :value="option.key">{{ option.label }}</option>
        </select>
        <div class="form-item__description">{{ componentFieldSettings.description }}</div>
      </div>
    </div>
  `
};
