import castorcito_fields from './castorcito_fields.js';

export default {
  components: {
    'castorcito-fields': castorcito_fields
  },
  data() {
    return {
      defaultTranslations: drupalSettings.default_translations,
      showDragMessage: false,
      loadedCFieldComponents: {},
    };
  },
  props: ['formData', 'isUnique'],
  emits: ['toggle-show-button'],
  template: `
    <div v-if="!isUnique" class="fieldset__wrapper">
      <div v-if="showDragMessage" class="messages messages--warning" role="alert">
        <abbr class="warning tabledrag-changed" title="Changed">*</abbr> {{ defaultTranslations.reorder_changes }}
      </div>
      <div class="castorcito--drag" v-for="(data, i) in formData" :key="i">
        <a 
          v-if="formData.length > 1"
          title="Drag to re-order"
          class="tabledrag-handle js-tabledrag-handle tabledrag-handle-y"
          @drop="onDrop($event, i, formData)"
          @dragover.prevent
          @dragenter.prevent
          draggable="true"
          @dragstart="startDrag($event, i)"
        ></a>
        <details v-bind="hasCollapseComponent(data) ? {} : { open: true }" class="claro-details" :data-castorcito-delta="i">
          <summary tabindex="-1" class="claro-details__summary">
            <span>{{ data.componentModel.label }}</span>
            <span class="claro-details__summary-summary"></span>
            <div class="castorcito--more-operations" v-if="hideOperations(i)">
              <div class="message"></div>
              <button class="reset-appearance tabs__trigger" type="button">
                <svg fill="none" height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg">
                  <path clip-rule="evenodd" d="m15 9h-14c-.56016 0-1-.43984-1-1s.43984-1 1-1h14c.5602 0 1 .43984 1 1s-.4398 1-1 1zm0-5h-14c-.56016 0-1-.43984-1-1s.43984-1 1-1h14c.5602 0 1 .43984 1 1s-.4398 1-1 1zm-14 8h14c.5602 0 1 .4398 1 1s-.4398 1-1 1h-14c-.56016 0-1-.4398-1-1s.43984-1 1-1z" fill="#003ECC" fill-rule="evenodd"></path>
                </svg>
              </button>
              <div class="castorcito--more-options">
                <div>
                  <button class="reset-appearance" @click="duplicateComponent($event, i)" type="button" aria-label="{{ defaultTranslations.duplicate }}">
                    <span>{{ defaultTranslations.duplicate }}</span>
                  </button>
                </div>
                <div v-if="hasPermission('use castorcito button copy')">
                  <button class="reset-appearance" @click="copyComponent($event, i)" type="button" aria-label="{{ defaultTranslations.copy }}">
                    <span>{{ defaultTranslations.copy }}</span>
                  </button>
                </div>
              </div>
            </div>
          </summary>
          <div :class="['castorcito-drag--content']">
            <div class="castorcito-form" @focusout="saveData(i)">
              <castorcito-fields
                v-if="data.fieldsSettings"
                :formData="data"
                :cFieldComponents="cFieldComponents(data.componentModel)"
                :fieldBaseName="fieldBaseName(i)"
                :containerDelta="0"
              />
              <div v-else role="contentinfo" class="messages-list__item messages messages--error">
                <div role="alert">
                  <div class="messages__header">
                    <h2 class="messages__title">{{ defaultTranslations.error_message }}</h2>
                  </div>
                  <div class="messages__content">
                    <ul class="messages__list">
                      <li class="messages__item">{{ defaultTranslations.missing_component_message.replace('@component', data.componentModel.label) }}</li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
            <div class="fieldset__wrapper">
              <button type="button" class="button--small button--danger button" @click="deleteComponent(i)">{{ defaultTranslations.remove }} {{ data.componentModel.label }}</button>
            </div>
          </div>
        </details>
      </div>
    </div>
    <div v-else v-for="(data, i) in formData" :key="i" tabindex="0" class="castorcito-form" @focusout="saveData(i)">
      <castorcito-fields
        v-if="data.fieldsSettings"
        :formData="data"
        :cFieldComponents="cFieldComponents(data.componentModel)"
        :fieldBaseName="fieldBaseName(i)"
        :containerDelta="0" />
      <div v-else role="contentinfo" class="messages-list__item messages messages--error">
        <div role="alert">
          <div class="messages__header">
            <h2 class="messages__title">{{ defaultTranslations.error_message }}</h2>
          </div>
          <div class="messages__content">
            <ul class="messages__list">
              <li class="messages__item">{{ defaultTranslations.missing_component_message.replace('@component', data.componentModel.label) }}</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  `,
  methods: {
    fieldBaseName(delta) {
      const { fieldNameDrupal, componentId } = this.formData[delta];
      return `${fieldNameDrupal}_${delta}_${componentId}`;
    },
    duplicateComponent(event, delta) {
      const field = drupalSettings.field_components[this.formData[delta].fieldNameDrupal];
      if (field.cardinality !== 1) {
        const duplicateComponent = JSON.parse(JSON.stringify(this.formData[delta]));
        duplicateComponent.componentModel.label = duplicateComponent.componentModel.label + ' - ' + this.defaultTranslations.duplicate;
        this.formData.splice(delta + 1, 0, duplicateComponent);
        this.formData.forEach((_, index) => this.saveData(index));
      }

      if (field.cardinality > 1) {
        this.setFocusComponent(field.field_name_class, delta);
      }

      if (field.cardinality === -1) {
        this.triggerAddAnotherComponent(field.field_name_class, delta);
      }

      this.actionMessages(event, this.defaultTranslations.duplicate_component);
    },
    hideOperations(delta) {
      const field = drupalSettings.field_components[this.formData[delta].fieldNameDrupal];
      if (field.cardinality === this.formData.length) {
        return false;
      }
      return true;
    },
    async copyComponent(event, delta) {
      const componentModel = JSON.stringify(this.formData[delta]);
      if (!componentModel) return;

      try {
        await navigator.clipboard.writeText(componentModel);
        this.actionMessages(event, this.defaultTranslations.copy_component);
      } catch (err) {
        this.actionMessages(event, this.defaultTranslations.copy_error);
        console.error('Copy error: ', err);
      }
    },
    startDrag(event, item) {
      event.dataTransfer.dropEffect = 'move';
      event.dataTransfer.effectAllowed = 'move';
      event.dataTransfer.setData('item_key', item);
    },
    onDrop(event, list) {
      const itemKey = event.dataTransfer.getData('item_key');
      const element = this.formData.splice(itemKey, 1)[0];
      this.formData.splice(list, 0, element);

      // Saving updated data
      this.formData.forEach((_, index) => this.saveData(index));
      this.addDragStyle(event);
      this.showDragMessage = true;
      this.loadedCFieldComponents = {};
    },
    deleteComponent(delta) {
      const { fieldNameDrupal } = this.formData[delta];

      // Clear corresponding textareas
      const textareas = document.querySelectorAll(`textarea[name^="${fieldNameDrupal}["]`);
      textareas.forEach(textarea => {
        textarea.value = '';
      });

      // Remove the component from the array
      this.formData.splice(delta, 1);

      // Saving updated data
      this.formData.forEach((_, index) => this.saveData(index));

      // Show button "Add Component".
      this.$emit('toggle-show-button', true);
      this.loadedCFieldComponents = {};
    },
    saveData(delta) {
      const { componentModel, fieldNameDrupal } = this.formData[delta];
      const textareas = document.querySelectorAll(
        `textarea[name^="${fieldNameDrupal}[${delta}]"]`
      );

      textareas.forEach(textarea => {
        textarea.value = JSON.stringify(componentModel);
      });
    },
    hasCollapseComponent(data) {
      return data.componentOverriddenSettings?.settings?.collapse_component
        ?? data.fieldsSettings.settings.collapse_component
    },
    cFieldComponents(model) {
      Object.values(model.fields).forEach(field => {
        const type = field.type;
        if (!this.loadedCFieldComponents[type]) {
          this.loadedCFieldComponents[type] = this.loadedCFieldComponent(type);
        }
      });

      return this.loadedCFieldComponents;
    },
  }
};
