<template>
  <div>
    <label v-if="label" class="text-gray-light text-lg mb-2">{{ label }}:</label>
    <div :class="{ error: error }">
      <input ref="file" type="file" :accept="accept" class="hidden" @change="change">
      <div v-if="!modelValue" class="py-2">
        <button type="button" class="px-6 py-2 bg-indigo-300 focus:ring-4 focus:ring-offset-1 focus:ring-orange focus:ring-opacity-20 focus:ring-offset-orange focus:outline-none focus:border-transparent rounded-sm text-sm text-white" @click="browse">
          Выбрать файл
        </button>
      </div>
       <div v-else class="flex justify-center items-start max-w-lg mt-3 p-2 border rounded-md">
        <div class="flex-1 pr-1 text-gray">{{ modelValue.name }} <span class="text-xs text-gray-light">({{ filesize(modelValue.size) }})</span></div>
        <button type="button" class="px-4 py-1 bg-indigo-300 hover:bg-indigo-100 rounded-sm text-xs font-medium text-white" @click="remove">
          Удалить
        </button>
      </div>
    </div>
    <div v-if="error" class="text-red text-sm">{{ error }}</div>
  </div>
</template>

<script>
export default {
  props: {
    modelValue: File,
    label: String,
    accept: String,
    error: String,
  },
  watch: {
    modelValue(value) {
      if (!value) {
        this.$refs.file.value = ''
      }
    },
  },
  methods: {
    filesize(size) {
      var i = Math.floor(Math.log(size) / Math.log(1024))
      return (size / Math.pow(1024, i) ).toFixed(2) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i]
    },
    browse() {
      this.$refs.file.click()
    },
    change(e) {
      this.$emit('update:modelValue', e.target.files[0])
    },
    remove() {
      this.$emit('update:modelValue', null)
    },
  },
}
</script>
