<template>
  <label class="upload">
    <input type="file" ref="input" class="upload__input" :accept="accepts" @change.stop.prevent="upload" />
    <span class="upload__label" :class="{ 'upload__label--filled': hasUploads }" v-text="indicator"></span>
    <button v-if="hasUploads" class="upload__remove" @click.stop.prevent="removeUpload"><cross-icon></cross-icon></button>
    <main-button type="sharp" :text="label" :disabled="!hasUploads" @callback="emitUpload"></main-button>
  </label>
</template>

<script>
export default {
  name: 'upload-input',
  components: {
    CrossIcon: () => import('@/components/icons/CrossIcon.vue'),
    MainButton: () => import('@/components/buttons/MainButton.vue'),
  },
  props: {
    title: {
      type: String,
      required: true,
    },
    placeholder: {
      type: String,
      required: false
    },
    accepts: {
      type: String,
      default: 'image/*',
      required: false,
    },
  },
  data () {
    return {
      uploads: [],
      loading: false,
      formData: new FormData(),
    }
  },
  computed: {
    hasUploads() {
      return this.uploads.length > 0;
    },
    label() {
      return this.loading ? 'loading' : this.title
    },
    indicator() {
      return (this.uploads.length > 0) ? this.uploads[0].name : this.placeholder;
    }
  },
  methods: {
    emitUpload() {
      this.$emit('upload', this.formData);
      this.removeUpload();
    },
    removeUpload() {
      this.formData.delete('attachment[]');
      this.uploads = [];
    },
    upload() {
      const { input } = this.$refs;
      const file = input.files ? input.files[0] : '';
      this.formData.append('attachment[]', file);
      this.uploads = this.formData.getAll('attachment[]');
      input.value = '';
    },
  }
}
</script>

<style lang="scss" scoped>
.upload {
  position: relative;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0;
  &__input {
    display: none;
    visibility: hidden;
  }
  &__label {
    height: 50px;
    height: 5rem;
    width: 100%;
    background-color: $white;
    border-radius: border-radius(primary);
    box-shadow: box-shadow(secondary);
    @include body-small;
    color: rgba($color-black-primary, .5);
    cursor: pointer;
    line-height: 50px;
    line-height: 5rem;
    padding-left: 10px;
    padding-left: 1rem;
    padding-right: 115px;
    padding-right: 11.5rem;
    transition: color transition(fast);
    &--filled {
      color: rgba($color-black-primary, 1);
    }
  }
  &__remove {
    position: absolute;
    top: 50%;
    right: 130px;
    transform: translateY(-50%);
  }
  /deep/
  .sharp {
    height: 50px;
    height: 5rem;
    min-width: 115px;
    min-width: 11.5rem;
    width: 115px;
    width: 11.5rem;
    position: absolute;
    top: 50%;
    right: 0;
    transform: translateY(-50%);
  }
}
</style>

