export default {
  props: ['fieldModel', 'componentFieldSettings', 'fieldName'],
  data() {
    const { allowed_formats: allowedFormatsFromSettings, default_translations: defaultTranslations } = drupalSettings;
    const { allowed_formats: allowedFieldFormats } = this.componentFieldSettings.settings;
    const fieldFormats = Object.keys(allowedFormatsFromSettings)
      .filter(key => key in allowedFieldFormats && allowedFieldFormats[key] !== 0)
      .reduce((acc, key) => {
        acc[key] = allowedFormatsFromSettings[key];
        return acc;
      }, {});
    const allowedFormats = Object.keys(fieldFormats).length ? fieldFormats : allowedFormatsFromSettings;
    const currentFormat = fieldFormats.hasOwnProperty(this.fieldModel.format) ? this.fieldModel.format : Object.keys(allowedFormats)[0];
    let hasPermissions = true;
    this.fieldModel.format = currentFormat;

    if (Object.values(fieldFormats).some(value => value !== 0) && !Object.keys(fieldFormats).length) {
      this.fieldModel.value = defaultTranslations.text_format_disabled;
      hasPermissions = false;
    }

    return {
      allowedFormats,
      hasPermissions,
      currentFormat,
      allowedFormatsFromSettings,
      defaultTranslations,
      isFormat: drupalSettings.is_format,
      htmlId: `${this.fieldName}`,
      isRequired: this.componentFieldSettings.required
    };
  },
  mounted() {
    if (this.isFormat && this.hasPermissions) {
      this.toggleEditor(this.currentFormat);
      this.initializeEditor();
    }
  },
  methods: {
    toggleEditor(format, action = 'attach') {
      const field = this.$refs[this.htmlId];
      const formatSettings = drupalSettings.editor.formats[format];

      if (formatSettings) {
        action === 'attach'
          ? Drupal.editorAttach(field, formatSettings)
          : Drupal.editorDetach(field, formatSettings);
      } else if (action === 'detach') {
        jQuery(field).off('.editor');
      }
    },
    handleSelectChange(event) {
      const newFormat = event.target.value;
      this.toggleEditor(this.currentFormat, 'detach');
      this.toggleEditor(newFormat);
      this.currentFormat = newFormat;
      this.initializeEditor();
    },
    initializeEditor() {
      const editorInterval = setInterval(() => {
        const editorElement = document.getElementById(this.htmlId);

        if (editorElement) {
          const editorId = editorElement.getAttribute('data-ckeditor5-id');
          const editorInstance = Drupal.CKEditor5Instances.get(editorId);

          if (editorInstance) {
            editorInstance.model.document.on('change:data', () => {
              this.fieldModel.value = editorInstance.getData();
            });
            clearInterval(editorInterval);
          }
        }
      }, 100);
    }
  },
  computed: {
    hasMultipleFormats() {
      return Object.keys(this.allowedFormats).length > 1;
    }
  },
  template: `
    <div class="field--widget-text-textarea">
      <div class="text-full form-item">
        <div class="form-item form-type--textarea">
          <label v-if="!componentFieldSettings.hide_label" :for="htmlId" class="form-item__label" :class="{ 'form-required': isRequired }">{{ componentFieldSettings.label }}</label>
          <div class="form-textarea-wrapper">
            <textarea
              class="text-full form-textarea resize-vertical form-element form-element--type-textarea form-element--api-textarea"
              :data-drupal-selector="htmlId"
              :id="htmlId"
              :name="htmlId"
              :ref="htmlId"
              rows="5"
              cols="60"
              placeholder=""
              :data-editor-active-text-format="currentFormat"
              v-model="fieldModel.value"
              :disabled="!hasPermissions"
              :required="isRequired"
            >
            </textarea>
          </div>
        </div>
        <div v-if="hasPermissions && hasMultipleFormats" class="form-item--editor-format form-item form-type--select">
          <label :for="htmlId + '_format'" class="form-item__label">{{ defaultTranslations.text_format }}</label>
          <select
            class="editor form-element--extrasmall form-element--editor-format form-select form-element form-element--type-select"
            :data-drupal-selector="htmlId + '_format'"
            :data-editor-for="htmlId + '_format'"
            :id="htmlId + '_format'"
            :name="htmlId + '_format'"
            @change="handleSelectChange"
            data-once="editor"
            v-model="fieldModel.format">
            <option v-for="(option, index) in allowedFormats" :key="index" :value="index">{{ allowedFormatsFromSettings[index] }}</option>
          </select>
        </div>
        <div class="form-item__description">{{ componentFieldSettings.description }}</div>
      </div>
    </div>
  `
};
