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

    return {
      urlAutocomplete,
      allowLinkText,
      searchItems: {},
      isLoading: false,
      isFocused: false,
      cache: {},
      isRequired: this.componentFieldSettings.required,
      linkUrlHelp: this.formatLinkUrlHelp(defaultTranslations.link_url_help),
      defaultTranslations
    };
  },
  computed: {
    isExternal() {
      this.fieldModel.external = true;
      this.fieldModel.relative = '';
      const link = this.fieldModel.value;
      if (link.indexOf('http') === -1) {
        this.fieldModel.external = false;
        this.fieldModel.relative = link;
        var nid = link.substring(link.lastIndexOf('(') + 1, link.lastIndexOf(')'));
        if (nid) {
          this.fieldModel.relative = '/node/' + nid;
        }
      }
    }
  },
  methods: {
    async fetchLinksSuggestions() {
      const searchTerm = this.fieldModel.value.trim();

      if (!searchTerm) {
        this.searchItems = {};
        return;
      }

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

      if (this.isLoading) return;

      this.isLoading = true;
      const baseUrl = drupalSettings.path.baseUrl;
      const url_autocomplete = `${baseUrl}${this.urlAutocomplete}?q=${encodeURIComponent(this.fieldModel.value)}`;

      try {
        const response = await fetch(url_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.searchItems = {};
      } finally {
        this.isLoading = false;
      }
    },
    setValue(event, string) {
      this.fieldModel.value = string;
      this.searchItems = {};
      event.target.closest('.claro-autocomplete').querySelector('input').focus();
      event.target.closest('.claro-autocomplete').querySelector('input').classList.remove('is-autocompleting');
    },
    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');
      }
    },
    formatLinkUrlHelp(text) {
      const placeholders = {
        '%add-node': '<em class="placeholder">/node/add</em>',
        '%url': '<em class="placeholder">https://example.com</em>',
        '%front': '<em class="placeholder">&lt;front&gt;</em>',
        '%nolink': '<em class="placeholder">&lt;nolink&gt;</em>',
        '%button': '<em class="placeholder">&lt;button&gt;</em>'
      };

      return Object.keys(placeholders).reduce((acc, key) => {
        return acc.replace(key, placeholders[key]);
      }, text);
    }
  },
  template: `
    <div class="field--type-link field--widget-link-default form-wrapper">
      <fieldset class="fieldset form-item form-wrapper">
        <legend class="fieldset__legend fieldset__legend--visible">
          <span v-if="!componentFieldSettings.hide_label" class="fieldset__label" :class="{ 'form-required': isRequired }">{{ componentFieldSettings.label }}</span>
        </legend>
        <div class="fieldset__wrapper">
          <div class="js-form-item form-item form-type--entity-autocomplete">
            <label :for="fieldName + '_autocomplete'" class="form-item__label" :class="{ 'form-required': isRequired }">{{ defaultTranslations.url }}</label>
            <div class="claro-autocomplete">
              <input
                class="form-autocomplete form-text form-element form-element--type-text form-element--api-entity-autocomplete ui-autocomplete-input"
                type="text"
                :id="fieldName + '_autocomplete'"
                :data-type="isExternal"
                :name="fieldName + '_autocomplete'"
                v-model="fieldModel.value"
                size="60"
                maxlength="2048"
                @blur="suggestionsHandler($event)"
                @keyup="fetchLinksSuggestions"
                autocomplete="off"
                :required="isRequired"
              />
              <div v-if="isLoading" class="claro-autocomplete__message">{{ defaultTranslations.loading }}</div>
              <ul
                v-if="Object.keys(searchItems).length > 0"
                class="ui-menu ui-widget ui-widget-content ui-autocomplete ui-front"
                @mouseenter="suggestionsHandler($event)"
                @mouseleave="suggestionsHandler($event)"
                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($event)"
                    @mouseleave="suggestionsHandler($event)"
                    class="ui-menu-item-wrapper"
                  >{{ item.label }}</a>
                </li>
              </ul>
            </div>
            <div class="form-item__description" v-html="linkUrlHelp"></div>
          </div>
          <div v-if="allowLinkText !== '0'" class="js-form-item form-item form-type--textfield">
            <label :for="fieldName + '_text'" :class="['form-item__label', {'form-required': allowLinkText === '2'}]">{{ defaultTranslations.link_text }}</label>
            <input
              type="text"
              :id="fieldName + '_text'"
              :name="fieldName + '_text'"
              v-model="fieldModel.text"
              size="60"
              maxlength="255"
              :required="allowLinkText === '2'"
              class="form-text form-element form-element--type-text form-element--api-textfield"
            />
          </div>
          <details class="form-wrapper claro-details" open="">
            <summary role="button" class="claro-details__summary">
              {{ defaultTranslations.link_attributes }}
              <span class="claro-details__summary-summary"></span>
            </summary>
            <div class="claro-details__wrapper details-wrapper">
              <div class="form-item form-type--select">
                <label :for="fieldName + '_attributes_target'" class="form-item__label">{{ defaultTranslations.target }}</label>
                <select
                  v-model="fieldModel.target"
                  :id="fieldName + '_attributes_target'"
                  :name="fieldName + '_attributes_target'"
                  class="form-select form-element form-element--type-select"
                >
                  <option value="" selected="selected">{{ defaultTranslations.none }}</option>
                  <option value="_self">Same window (_self)</option>
                  <option value="_blank">New window (_blank)</option>
                </select>
              </div>
            </div>
          </details>
          <div class="form-item__description">{{ componentFieldSettings.description }}</div>
        </div>
      </fieldset>
    </div>
  `
};
