<template>
  <label
    @dragover="dragover"
    @dragleave="dragleave"
    @drop="drop"
    :class="['file-upload', { dragging: isDragging }]"
  >
    <input
      ref="upload"
      type="file"
      multiple
      :accept="accept"
      @change="changeFile"
      class="input-file"
    />
    <i class="bi bi-cloud-upload-fill"></i>
    <span v-if="text" class="input-text">
      {{ text }}
      <span v-if="textSecondPart" class="last-word">{{ textSecondPart }}</span>
    </span>
    <span v-if="textPictureType" class="input-text-type">{{
      textPictureType
    }}</span>
  </label>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
const emit = defineEmits<{ (e: 'trigger', value: FileList): void }>()
let isDragging = ref<boolean>(false)

defineProps({
  text: { type: String, default: null },
  textPictureType: { type: String, default: null },
  textSecondPart: { type: String, default: null },
  accept: { type: String, default: '' }
})

interface HTMLInputChangeEvent extends Event {
  target: HTMLInputElement & EventTarget
}
function changeFile(event: Event): void {
  const { target } = event as HTMLInputChangeEvent
  if (target && target.files) {
    if (!checkPicturesType(target.files)) return
    emit('trigger', target.files)
  }
}

function dragover(event: DragEvent): void {
  event.preventDefault()
  isDragging.value = true
}

function dragleave(): void {
  isDragging.value = false
}
function drop(event: DragEvent): void | boolean {
  event.preventDefault()
  const { dataTransfer } = event
  if (dataTransfer && dataTransfer.files) {
    if (!checkPicturesType(dataTransfer.files))
      return (isDragging.value = false)
    emit('trigger', dataTransfer.files)
    isDragging.value = false
  }
}

function checkPicturesType(files: FileList): number {
  const picturesToUpload = [...files].filter((p) => p.type == 'image/jpeg')
  return picturesToUpload.length
}
</script>

<style scoped lang="scss">
.file-upload {
  padding: toRem(0.3) toRem(0.3) toRem(3);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.dragging {
  border-color: var(--green);
  background-color: var(--green-pale);
  .last-word,
  .bi-cloud-upload-fill {
    color: var(--green);
  }
}
.file-upload input {
  overflow: hidden;
  width: 0;
}
.bi-cloud-upload-fill {
  color: var(--blue);
  font-size: toRem(7);
}
.input-text {
  font-size: toRem(2);
  @include text(m-r-regular);
  width: toRem(21);
  text-align: center;
  margin-bottom: toRem(1);
  font-weight: 590;
}
.input-text-type {
  @include text(xs-r-regular);
}
.last-word {
  color: var(--blue);
  text-decoration: underline;
}
</style>
