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

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

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

      if (this.cache[searchTerm]) {
        this.searchItems = this.cache[searchTerm];
        return;
      }

      if (this.isLoading) return;

      this.isLoading = true;
      this.hasError = false;

      try {
        const baseUrl = drupalSettings.path.baseUrl
        const endpoint_autocomplete = `${baseUrl}${this.urlAutocomplete}?q=${encodeURIComponent(this.fieldModel.value)}`;
        const response = await fetch(endpoint_autocomplete, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        if (!response.ok) {
          throw new Error('Error fetching content suggestions');
        }

        const result = await response.json();
        this.cache[searchTerm] = result;
        this.searchItems = result;
      } catch (error) {
        this.hasError = true;
        this.searchItems = {};
      } finally {
        this.isLoading = false;
      }
    },
    setValue(event, string) {
      this.fieldModel.value = string;
      this.fieldModel.webform_id = this.getId(string);
      this.searchItems = {};
      event.target.closest('.claro-autocomplete').querySelector('input').focus();
    },
    suggestionsHandler(event) {
      if (event.type === 'blur' && !this.isFocused) {
        this.searchItems = {};
        this.isFocused = false;
      }
      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');
      }
    },
    getId(string) {
      return string.substring(string.lastIndexOf('(') + 1, string.lastIndexOf(')'));
    },
  },
  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 in searchItems" class="ui-menu-item">
              <a
                @click="setValue($event, item.value)"
                @mouseenter="suggestionsHandler"
                @mouseleave="suggestionsHandler"
                class="ui-menu-item-wrapper">{{ item.label }}
              </a>
            </li>
          </ul>
        </div>
        <div class="form-item__description" v-html="componentFieldSettings.description"></div>
      </div>
    </div>
  `
};
