export default {
  props: ['fieldModel', 'componentFieldSettings', 'fieldName'],
  data() {
    const { allowed_provider: allowedProvider } = this.componentFieldSettings.settings;
    const defaultTranslations = drupalSettings.default_translations;

    // The block_label key has been changed to value. The following code ensures compatibility with existing code that still uses block_label, preventing errors.
    if ('block_label' in this.fieldModel) {
      this.fieldModel.value = this.fieldModel.block_label;
    }

    return {
      allowedProvider,
      searchItems: {},
      searchStore: null,
      isLoading: false,
      hasError: false,
      isFocused: false,
      isRequired: this.componentFieldSettings.required,
      defaultTranslations
    };
  },
  methods: {
    async fetchContentSuggestions() {
      const searchTerm = this.fieldModel.value.trim();

      if (!searchTerm) {
        this.fieldModel.value = '';
        this.fieldModel.block_id = '';
        this.isLoading = false;
        this.searchItems = {};
        return;
      }

      if (!this.searchStore) {
        this.isLoading = true;
        this.hasError = false;
        const params = new URLSearchParams({ provider: JSON.stringify(this.allowedProvider)});

        try {
          const response = await fetch(`${drupalSettings.url_list_block}?${params.toString()}`, {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
          });

          if (!response.ok) {
            const errorMessage = `Error ${response.status}: ${response.statusText}`;
            console.error(errorMessage);
            throw new Error(errorMessage);
          }

          this.searchStore = await response.json();
        } catch (error) {
          console.error('Fetch content suggestions failed:', error);
          this.hasError = true;
          this.searchItems = {};
        } finally {
          this.isLoading = false;
        }
      }

      this.getData();
    },
    getData() {
      this.searchItems = Object.entries(this.searchStore)
      .filter(([key, value]) => value && value.toLowerCase().includes(this.fieldModel.value.toLowerCase()))
      .slice(0, 5)
      .reduce((acc, [key, value]) => {
        acc[key] = value;
        return acc;
      }, {});
    },
    setValue(event, i, label) {
      this.fieldModel.value = label;
      this.fieldModel.block_id = i;
      this.searchItems = {};
      event.target.closest('.claro-autocomplete').querySelector('input').focus();
    },
    suggestionsHandler(event) {
      if (event.type === 'blur' && !this.isFocused) {
        this.searchItems = {};
        this.isFocused = false;
        this.searchStore = null;
      }
      if (event.type === 'mouseenter') {
        this.isFocused = true;
        event.target.classList.add('ui-state-active');
      }
      if (event.type === 'mouseleave') {
        this.isFocused = false;
        event.target.classList.remove('ui-state-active');
      }
    }
  },
  template: `
    <div class="field--type-entity-reference field--name-field-referencia field--widget-entity-reference-autocomplete form-wrapper" data-drupal-selector="edit-field-referencia-wrapper" id="edit-field-referencia-wrapper">
      <div class="form-item form-type--entity-autocomplete">
        <label v-if="!componentFieldSettings.hide_label" :for="fieldName" class="form-item__label" :class="{ 'form-required': isRequired }">{{ componentFieldSettings.label }}</label>
        <div class="claro-autocomplete">
          <input
            :data-drupal-selector="fieldName"
            class="form-autocomplete form-text form-element form-element--type-text form-element--api-entity-autocomplete ui-autocomplete-input"
            type="text"
            :id="fieldName"
            :name="fieldName"
            value=""
            size="60"
            maxlength="1024"
            placeholder=""
            v-model="fieldModel.value"
            @keyup="fetchContentSuggestions"
            autocomplete="off"
            @blur="suggestionsHandler"
            :required="isRequired"
          >
          <div v-if="isLoading" class="claro-autocomplete__message" data-drupal-selector="autocomplete-message">{{ defaultTranslations.loading }}</div>
          <ul
            v-if="!isLoading && !hasError && Object.keys(searchItems).length"
            class="ui-menu ui-widget ui-widget-content ui-autocomplete ui-front"
            unselectable="on"
            @mouseenter="suggestionsHandler"
            @mouseleave="suggestionsHandler"
            style="top: 48px; width: -webkit-fill-available;">
            <li v-for="(item, i) in searchItems" class="ui-menu-item">
              <a
                @click="setValue($event, i, item)"
                @mouseenter="suggestionsHandler"
                @mouseleave="suggestionsHandler"
                class="ui-menu-item-wrapper">{{ item }}
              </a>
            </li>
          </ul>
        </div>
        <div class="form-item__description" v-html="componentFieldSettings.description"></div>
      </div>
    </div>
  `
};
