export default {
  props: ['fieldModel', 'componentFieldSettings', 'fieldBaseName', 'fieldName'],
  data () {
    const { alt_field: altField, alt_field_required: isAltRequired, title_field: titleField, title_field_required: isTitleRequired, uri_scheme: uriScheme } = this.componentFieldSettings.settings;
    const file = this.fieldModel.fid !== '' ? this.fieldModel : {};
    const defaultTranslations = drupalSettings.default_translations;

    return {
      uploadFile: {},
      file: file,
      errors: {},
      mstatus: {},
      isRequired: this.componentFieldSettings.required,
      isAltRequired,
      isTitleRequired,
      altField,
      titleField,
      uriScheme,
      countFile: defaultTranslations.count_file,
      allowedTypes: defaultTranslations.allowed_types.replace('@extensions', this.componentFieldSettings.settings.extensions),
      maxSize: defaultTranslations.limit.replace('@size', this.componentFieldSettings.settings.max_size),
      imageLarger: defaultTranslations.image_larger
        .replace('@max', this.componentFieldSettings.settings.max_dimensions.width)
        .replace('@min', this.componentFieldSettings.settings.max_dimensions.height),
      defaultTranslations
    };
  },
  methods: {
    onFileChange(event) {
      this.uploadFile = event.target.files[0];
      if (this.$refs.uploadButton) {
        this.$refs.uploadButton.click();
      }
    },
    onFileRemove() {
      this.uploadFile = '';
      document.getElementById(this.fieldName).value = '';
      Object.assign(this.fieldModel, {
        fid: '',
        name: '',
        size: '',
        width: '',
        value: '',
        thumbnail: '',
        height: '',
        alt: '',
        title: ''
      });
      this.file = {};
    },
    generateSrc(uri) {
      if (typeof uri === 'undefined') return '';

      const { url_private, url_public } = drupalSettings;

      if (this.uriScheme === 'private') {
        return uri.replace('private://', url_private);
      }

      return uri.replace('public://', url_public);
    },
    async uploadImage() {
      if (!this.uploadFile) {
        console.log('Please select an image file.');
        return;
      }

      try {
        const csrfTokenResponse = await fetch(drupalSettings.url_token);
        if (!csrfTokenResponse.ok) throw new Error('Failed to get CSRF token.');
        const token = await csrfTokenResponse.text();

        const base64Image = await new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.onloadend = () => resolve(reader.result.split(',')[1]);
          reader.onerror = reject;
          reader.readAsDataURL(this.uploadFile);
        });

        const response = await fetch(drupalSettings.url_upload_image, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': token
          },
          body: JSON.stringify({
            image: base64Image,
            name: this.uploadFile.name,
            size: this.uploadFile.size,
            settings_image: this.componentFieldSettings.settings
          })
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();

        if (data.errors.length === 0) {
          this.file = data.data;
          Object.assign(this.fieldModel, {
            fid: data.data.fid,
            name: data.data.name,
            size: data.data.size,
            width: data.data.width,
            value: data.data.value,
            thumbnail: data.data.thumbnail,
            height: data.data.height
          });
          this.mstatus = data.status;
          this.errors = [];

          this.$nextTick(() => {
            const altField = this.$refs.altField;
            if (altField) {
              altField.focus();
            }
          });
        } else {
          this.errors = data.errors;
        }
      } catch (error) {
        console.error('Error uploading image:', error);
        this.errors = [this.defaultTranslations.error_uploading_image];
      }
    }
  },
  computed: {
    isFileEmpty() {
      return Object.keys(this.file).length === 0;
    },
    hasErrors() {
      return Object.keys(this.errors).length === 0;
    },
    hasStatus() {
      return Object.keys(this.mstatus).length === 0;
    },
    messageNotUploaded() {
      return this.defaultTranslations.image_not_uploaded.replace(
        '%name',
        `<em class="placeholder">${this.uploadFile.name}</em>`
      );
    }
  },
  template: `
    <div class="field--type-image field--widget-image-image js-form-wrapper form-wrapper">
      <details open="" class="claro-details" data-once="details">
        <summary role="button" aria-expanded="true" class="claro-details__summary">
          <span v-if="!componentFieldSettings.hide_label">
            {{ componentFieldSettings.label }}
            <span v-show="isRequired" class="required-mark"></span>
          </span>
          <span class="claro-details__summary-summary"></span>
        </summary>
        <div class="claro-details__wrapper details-wrapper">
          <div class="js-form-item form-item js-form-type-managed-file form-type--managed-file">
            <div :class="['castorcito-container messages-list__wrapper', {'hidden': hasStatus}]">
              <div role="contentinfo" class="messages-list__item messages messages--status">
                <div class="messages__header">
                  <h2 :id="fieldName + '-message-status-title'" class="messages__title">Mensaje de estado</h2>
                </div>
                <div class="messages__content" v-if="!hasStatus" v-for="(status, i) in mstatus" :key="i" v-html="status"></div>
              </div>
            </div>
            <div :class="['castorcito-container messages-list__wrapper', {'hidden': hasErrors}]">
              <div role="contentinfo" class="messages-list__item messages messages--error">
                <div role="alert">
                  <div class="messages__header">
                    <h2 :id="fieldName + '-message-error-title'" class="messages__title">{{ defaultTranslations.error_message }}</h2>
                  </div>
                  <div class="messages__content">
                    <span v-if="uploadFile" v-html="messageNotUploaded"></span>
                    <div class="item-list">
                      <ul>
                        <li v-if="!hasErrors" v-for="(error, i) in errors" :key="i" v-html="error"></li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="js-form-item form-item js-form-type-managed-file form-type--managed-file form-item--no-label">
              <label :for="fieldName" :class="['form-item__label', {'has-error': !hasErrors, 'js-form-required': false, 'form-required': false, 'form-required': isRequired }]">{{ componentFieldSettings.label }}</label>
              <div class="image-widget js-form-managed-file form-managed-file form-managed-file--image is-single has-upload no-value has-meta">
                <div class="form-managed-file__main">
                  <span :class="['file', {'js-hide': isFileEmpty}]">
                    <a :href="generateSrc(file.value)" type="image/png">{{ file.name }}</a>
                    <span class="file__size">({{ file.size }})</span>
                  </span>
                  <input @change="onFileChange($event)" accept="image/*" type="file" :id="fieldName" :name="fieldName" size="22" :class="['form-file form-element form-element--type-file', {'js-hide': !isFileEmpty, 'error': !hasErrors}]">
                  <input @click.prevent="uploadImage" ref="uploadButton" class="js-hide upload-button button js-form-submit form-submit" type="submit" :id="fieldName + '_upload_button'" :name="fieldName + '_upload_button'" :value="defaultTranslations.upload">
                  <input @click.prevent="onFileRemove" :class="['button--extrasmall button', {'js-hide': isFileEmpty}]" type="submit" :id="fieldName + '_remove_button'" :name="fieldName + '_remove_button'" :value="defaultTranslations.remove">
                </div>
                <div :class="[{'hidden': isFileEmpty}]">
                  <div class="form-managed-file__meta">
                    <div class="form-managed-file__image-preview image-preview">
                      <div class="image-preview__img-wrapper">
                        <img :src="generateSrc(file.thumbnail)" width="100" height="38" alt="" class="image-style-thumbnail">
                      </div>
                    </div>
                    <div class="form-managed-file__meta-items">
                      <div v-if="altField" class="js-form-item form-item js-form-type-textfield form-type--textfield">
                        <label :class="['form-item__label', {'hidden': isFileEmpty, 'has-error': false, 'form-required': isAltRequired && !isFileEmpty}]" :for="fieldName + '_alt'">{{ defaultTranslations.alternative_text }}</label>
                        <input
                          :aria-describedby="fieldName + '_alt_description'"
                          type="text" :id="fieldName + '_alt'"
                          :name="fieldName + '_alt'"
                          v-model="fieldModel.alt"
                          ref="altField"
                          size="60"
                          maxlength="512"
                          :required="isAltRequired && !isFileEmpty"
                          :class="['form-text form-element form-element--type-text form-element--api-textfield', {'hidden': file.fid == 0, 'error': false}]">
                        <div :id="fieldName + '_alt_description'" class="form-item__description">
                          {{ defaultTranslations.alternative_text_help }}
                        </div>
                      </div>
                      <div v-if="titleField" class="js-form-item form-item js-form-type-textfield form-type--textfield">
                        <label :class="['form-item__label', {'hidden': isFileEmpty, 'has-error': false, 'form-required': isTitleRequired && !isFileEmpty}]" :for="fieldName + '_title'">{{ defaultTranslations.title }}</label>
                        <input
                          :aria-describedby="fieldName + '_title_description'"
                          type="text" :id="fieldName + '_title'"
                          :name="fieldName + '_title'"
                          v-model="fieldModel.title"
                          size="60"
                          maxlength="1024"
                          :required="isTitleRequired && !isFileEmpty"
                          :class="['form-text form-element form-element--type-text form-element--api-textfield', {'hidden': file.fid == 0, 'error': false}]">
                        <div id="fieldName + '_title_description'" class="form-item__description">
                          {{ defaultTranslations.image_title_help }}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="form-item__description">
                {{ componentFieldSettings.description }}<br>
                {{ countFile }}<br>
                {{ maxSize }}<br>
                {{ allowedTypes }}<br>
                <span v-show="componentFieldSettings.settings.max_dimensions.width && componentFieldSettings.settings.max_dimensions.height" v-html="imageLarger"></span>
              </div>
            </div>
          </div>
        </div>
      </details>
    </div>
  `
};
