export default {
  props: ['fieldModel', 'componentFieldSettings', 'fieldName'],
  data() {
    const {
      options,
      width,
      height,
      vimeo_options: vimeoOptions,
      youtube_options: youtubeOptions
    } = this.componentFieldSettings.settings;

    return {
      options,
      vimeoOptions,
      youtubeOptions,
      width,
      height,
      hasErrors: false,
      isRequired: this.componentFieldSettings.required,
      defaultTranslations: drupalSettings.default_translations
    };
  },
  created() {
    this.setDefaultOption();
  },
  updated() {
    this.setDefaultOption();
  },
  methods: {
    validateUrl(event) {
      this.hasErrors = false;
      const url = this.fieldModel.url;
      let embedUrl = '';

      const regexPatterns = {
        vimeo: /^https?:\/\/(www\.)?vimeo.com\/(channels\/[a-zA-Z0-9]*\/)?(?<id>[0-9]*)(\/[a-zA-Z0-9]+)?(\#t=(\d+)s)?$/,
        youtube: /^https?:\/\/(www\.)?((?!.*list=)youtube\.com\/watch\?.*v=|youtu\.be\/)(?<id>[0-9A-Za-z_-]*)/
      };

      const match = url.match(regexPatterns[this.fieldModel.option]);

      if (match) {
        const videoId = match.groups.id;

        if (this.fieldModel.option === 'vimeo') {
          const { width, height } = this.vimeoOptions;
          embedUrl = `https://player.vimeo.com/video/${videoId}`;
          this.fieldModel.value = `<iframe src="${embedUrl}" width="${width}" height="${height}" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" target_type="vimeo" target_id="${videoId}" allowfullscreen></iframe>`;
        }
        else if (this.fieldModel.option === 'youtube') {
          const { width, height, autoplay, mute, loop, rel, controls } = this.youtubeOptions;
          embedUrl = `https://www.youtube.com/embed/${videoId}?autoplay=${autoplay ? 1 : 0}&mute=${mute ? 1 : 0}&loop=${loop ? 1 : 0}&rel=${rel ? 0 : 1}&controls=${controls ? 0 : 1}&playlist=${videoId}`;
          this.fieldModel.value = `<iframe width="${width}" height="${height}" src="${embedUrl}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" target_type="youtube" target_id="${videoId}" allowfullscreen></iframe>`;
        }
      }
      else {
        this.hasErrors = true;
        this.fieldModel.url = '';
      }
    },
    capitalizeOption(option) {
      return option.charAt(0).toUpperCase() + option.slice(1).toLowerCase();
    },
    setDefaultOption() {
      if (!this.fieldModel.option) {
        this.fieldModel.option = Object.keys(this.options)[0];
      }
    }
  },
  computed: {
    hasMultipleOptions() {
      return Object.keys(this.options).length > 1;
    }
  },
  template: `
    <fieldset class="fieldset form-item">
      <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="castorcito-container">
        <div v-if="hasMultipleOptions" class="form-item form-type--select">
          <label :for="fieldName + '_option_select'" class="form-item__label">{{ defaultTranslations.options }}</label>
          <select
            class="form-select form-element form-element--type-select"
            v-model="fieldModel.option"
            :id="fieldName + '_option_select'"
            :name="fieldName + '_option_select'">
            <option v-for="(option, i) in options" :key="i" :value="i">{{ capitalizeOption(option) }}</option>
          </select>
        </div>
        <div v-if="fieldModel.option !== 'iframe'" class="form-item form-type--textfield">
          <div v-if="hasErrors" role="contentinfo" class="messages-list__item messages messages--error">
            <div role="alert">
              <div class="messages__header">
                <h2 :id="fieldName + 'message-error-url'" class="messages__title">{{ defaultTranslations.error_message }}</h2>
              </div>
              <div class="messages__content">
                <ul class="messages__list">
                  <li class="messages__item">{{ defaultTranslations.video_error_message }}</li>
                </ul>
              </div>
            </div>
          </div>
          <label :for="fieldName + '_option_input'" class="form-item__label" :class="{'form-required': isRequired, 'has-error': hasErrors }">{{ defaultTranslations.video_insert_label.replace('@type', fieldModel.option) }}</label>
          <input :id="fieldName + '_option_input'" :name="fieldName + '_option_input'" v-model="fieldModel.url" @blur="validateUrl" type="text" size="60" maxlength="255" class="form-text form-element" :class="hasErrors ? 'error' : ''" :required="isRequired"/>
          <div class="form-item__description has-error" v-html="fieldModel.option == 'vimeo' ? vimeoOptions.vimeo_details : youtubeOptions.youtube_details"></div>
        </div>
        <div v-if="fieldModel.option === 'iframe'" class="form-textarea-wrapper">
          <label :for="fieldName" class="form-item__label" :class="{ 'form-required': isRequired }">Iframe</label>
          <textarea
            class="text-full form-textarea resize-vertical form-element form-element--type-textarea form-element--api-textarea"
            :data-drupal-selector="fieldName"
            :id="fieldName"
            :name="fieldName"
            :ref="fieldName"
            rows="5"
            cols="60"
            placeholder=""
            v-model="fieldModel.value"
            :required="isRequired"
          >
          </textarea>
          <div class="form-item__description" v-html="componentFieldSettings.description"></div>
        </div>
      </div>
    </fieldset>
  `
};
