import castorcito_fields from '../castorcito_fields.js';

export default {
  components: {
    'castorcito-fields': castorcito_fields
  },
  props: ['fieldModel', 'componentFieldSettings', 'overriddenCFieldSettings', 'fieldBaseName', 'fieldName'],
  data() {
    const { components: allComponents, components_fields_settings: componentsFieldsSettings,  default_translations: defaultTranslations } = drupalSettings;
    const {
      min,
      max,
      add_button_label: addButtonLabel,
      delete_button_label: deleteButtonLabel,
      allowed_children: allowedChildren,
      head_component: headComponent,
      item_container_label: itemContainerLabel,
      collapse_container: collapseContainer
    } = this.componentFieldSettings.settings;

    return {
      allComponents,
      componentsFieldsSettings,
      allowedChildren,
      headComponent,
      min,
      max,
      addButtonLabel,
      deleteButtonLabel,
      collapseContainer,
      itemContainerLabel,
      defaultTranslations,
      selectedComponent: '',
      draggedItemIndex: null,
      showDragMessage: false,
      loadedCFieldComponents: {}
    };
  },
  created() {
    if (!this.hasMultipleComponents && this.fieldModel.items.length === 0) {
      this.addItem();
    }
  },
  computed: {
    hasMultipleComponents() {
      return Object.keys(this.allowedChildren).length > 1;
    }
  },
  methods: {
    addItem() {
      if (this.hasMultipleComponents && !this.selectedComponent) return;

      const component = this.hasMultipleComponents ? this.selectedComponent : Object.keys(this.allowedChildren)[0];
      const newItem = {
        'head': JSON.parse(JSON.stringify(this.allComponents[this.headComponent])),
        'body': JSON.parse(JSON.stringify(this.allComponents[component]))
      };

      this.fieldModel.items.push(newItem);
    },
    deleteItem: function(event, items, key) {
      items.splice(parseInt(key), 1);
      this.loadedCFieldComponents = {};
    },
    formData(field, type) {
      let componentOverriddenSettings = this.overriddenCFieldSettings?.settings?.allowed_components?.[field.type];
      if (type === 'head') {
        componentOverriddenSettings = this.overriddenCFieldSettings?.settings?.allowed_head_component?.[field.type];
      }

      return {
        componentModel: field,
        fieldsSettings: this.componentsFieldsSettings[field.type],
        componentOverriddenSettings: componentOverriddenSettings
      };
    },
    duplicateComponent(event, delta, item = {}) {
      const duplicateComponent = JSON.parse(JSON.stringify(item));
      const label = duplicateComponent.head.fields[this.itemContainerLabel].value ? duplicateComponent.head.fields[this.itemContainerLabel].value : `${this.componentFieldSettings.label} ${delta + 1}`;
      duplicateComponent.head.fields[this.itemContainerLabel].value = label  + ' - ' + this.defaultTranslations.duplicate;
      this.fieldModel.items.splice(delta + 1, 0, duplicateComponent);

      this.actionMessages(event, this.defaultTranslations.duplicate_component);
      this.duplicateFocus(event, delta);
    },
    startDrag(event, item) {
      event.dataTransfer.dropEffect = 'move';
      event.dataTransfer.effectAllowed = 'move';
      this.draggedItemIndex = item;
    },
    onDrop(event, i, items) {
      const itemKey = parseInt(this.draggedItemIndex, 10);
      if (isNaN(itemKey)) {
        console.error('Invalid item_key:', itemKey);
        return;
      }

      if (itemKey === i) return;

      const element = items.splice(itemKey, 1)[0];
      items.splice(i, 0, element);
      this.addDragStyle(event);
      this.showDragMessage = true;
      this.loadedCFieldComponents = {};
    },
    containerLabel(i, item) {
      return item.head.fields[this.itemContainerLabel].value || `${this.componentFieldSettings.label} ${i + 1}`;
    },
    hasCollapseComponent(comp, type) {
      const key = type === 'head' ? 'allowed_head_component' : 'allowed_components';
      const overridden = this.overriddenCFieldSettings?.settings?.[key]?.[comp.type]?.settings?.collapse_component;
      const defaultValue = this.componentsFieldsSettings[comp.type].settings.collapse_component;

      return overridden ?? defaultValue;
    },
    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;
    },
  },
  template: `
    <fieldset class="fieldset js-form-item form-item js-form-wrapper form-wrapper castorcito-field-container">
      <legend class="fieldset__legend fieldset__legend--visible">
        <span v-if="!componentFieldSettings.hide_label" class="fieldset__label">{{ componentFieldSettings.label }}</span>
      </legend>
      <div 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="form-item__description">{{ componentFieldSettings.description }}</div>
        <div
          class="castorcito--drag"
          v-for="(item, i) in fieldModel.items"
        >
          <a
            v-if="fieldModel.items.length > 1"
            title="Drag to re-order"
            class="tabledrag-handle js-tabledrag-handle tabledrag-handle-y"
            @drop="onDrop($event, i, fieldModel.items)"
            @dragover.prevent
            @dragenter.prevent
            draggable="true"
            @dragstart="startDrag($event, i)"
          ></a>
          <details v-bind="collapseContainer ? {} : { open: true }" class="claro-details" data-once="details" :data-castorcito-container-delta="i">
            <summary tabindex="-1" class="claro-details__summary">
              <span v-text="containerLabel(i, item)"></span>
              <span class="castorcito--drag-changed"></span>
              <span class="claro-details__summary-summary"></span>
              <div :class="['castorcito--more-operations', {'visually-hidden': fieldModel.items.length >= max}]">
                <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, item)" type="button" aria-label="{{ defaultTranslations.duplicate }}">
                      <span>{{ defaultTranslations.duplicate }}</span>
                    </button>
                  </div>
                </div>
              </div>
            </summary>
            <div :class="['castorcito-container castorcito-drag--content']">
              <details v-bind="hasCollapseComponent(item.head, 'head') ? {} : { open: true }" class="claro-details" data-once="details">
                <summary role="button" aria-expanded="true" class="claro-details__summary">
                  <span class="form-item__label form-required">{{ item.head.label }}</span>
                  <span class="claro-details__summary-summary"></span>
                </summary>
                <div class="claro-details__wrapper details-wrapper">
                  <castorcito-fields
                    :formData="formData(item.head, 'head')"
                    :cFieldComponents="cFieldComponents(item.head)"
                    :fieldBaseName="fieldBaseName"
                    :containerDelta="i + '_head_' + componentFieldSettings.name"
                  />
                </div>
              </details>
              <details v-bind="hasCollapseComponent(item.body, 'body') ? {} : { open: true }" class="claro-details" data-once="details">
                <summary role="button" aria-expanded="true" class="claro-details__summary">
                  <span class="form-item__label">{{ item.body.label }}</span>
                  <span class="claro-details__summary-summary"></span>
                </summary>
                <div class="claro-details__wrapper details-wrapper">
                  <castorcito-fields
                    :formData="formData(item.body, 'body')"
                    :cFieldComponents="cFieldComponents(item.body)"
                    :fieldBaseName="fieldBaseName"
                    :containerDelta="i + '_body_' + componentFieldSettings.name"
                  />
                </div>
              </details>
              <button v-show="max > 1 || hasMultipleComponents" type="button" class="button--small button--danger button" @click="deleteItem($event, fieldModel.items, i)">{{ deleteButtonLabel }}</button>
            </div>
          </details>
        </div>
        <div v-if="fieldModel.items.length < max" class="form-item castorcito-container--add-item">
          <div class="form-item--editor-format form-item form-type--select">
            <label v-if="hasMultipleComponents" :for="fieldName + '_add_item_select'" class="form-item__label visually-hidden">items</label>
            <select
              v-if="hasMultipleComponents"
              class="form-select form-element form-element--type-select"
              v-model="selectedComponent"
              :id="fieldName + '_add_item_select'">
              <option value="" disabled selected>{{ defaultTranslations.select_component }}</option>
              <option v-for="(child, key) in allowedChildren" :key="key" :value="key">{{ allComponents[child].label }}</option>
            </select>
            <button type="button" class="button button--action button--primary" @click="addItem">{{ addButtonLabel }}</button>
          </div>
        </div>
      </div>
    </fieldset>
  `
};
