<template>
  <div
    class="document-form"
    ref="documentform"
  >
    <div
      v-if="!value.url"
      ref="uploadcare-panel"
    />
    <div
      class="document-form__spinner"
      v-if="loading"
    >
      <loading-icon class="document-form__loading-icon" />
    </div>
    <div
      class="document-form__uploaded"
      v-if="value.url"
    >
      <document-icon class="document-form__icon" />
      <a
        :href="previewUrl"
        class="document-form__link"
        target="_blank"
        >{{ previewLink }}</a
      >
    </div>
  </div>
</template>

<script>
import { uploadcare } from '@/helpers/uploadcare';
import LoadingIcon from '@/components/icons/LoadingIcon.vue';
import { defineAsyncComponent } from 'vue';

const DocumentIcon = defineAsyncComponent(() =>
  import('@/components/icons/DocumentIcon.vue')
);

export default {
  props: ['value', 'index'],

  components: {
    LoadingIcon,
    DocumentIcon,
  },

  data() {
    return {
      loading: false,
    };
  },

  computed: {
    previewUrl() {
      if (this.value && this.value.url) {
        return this.value.url;
      }
      return null;
    },
    previewLink() {
      if (this.value && this.value.url) {
        const parts = this.value.url.split('/');
        return parts[parts.length - 1];
      }
      return '';
    },
  },

  mounted() {
    uploadcare(
      this,
      (url) => {
        this.$emit('change-url', url, this.index);
        this.loading = false;
      },
      () => {
        this.loading = true;
      }
    );
  },
};
</script>

<style scoped lang="scss">
@import 'styles/helpers';

.document-form {
  &__uploaded {
    display: flex;
    align-items: center;
  }

  &__link {
    text-decoration: underline;
  }

  &__spinner {
    width: 100%;
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  &__loading-icon {
    @include spin;
    fill: $color-silver-dark;
  }

  &__icon {
    width: 30px;
    height: 30px;
    margin-right: $small-spacing;
  }

  &__file-input {
    width: 0.1px;
    height: 0.1px;
    overflow: hidden;
    opacity: 0;
    position: absolute;
    z-index: -1;

    & + label {
      cursor: pointer;
      background-color: $color-silver-light;
      height: 150px;
      display: flex;
      width: 100%;
      justify-content: center;
      align-items: center;
      font-family: $sans-serif-font-family;
      font-weight: $font-weight-regular;
      text-decoration: underline;
    }
  }
}
</style>
