<template>
  <label
    v-if="label"
    class="block text-sm font-medium text-gray-700"
    :for="id"
    v-text="label"
  />
  <button
    class="px-3 py-1 mr-2 text-sm font-medium text-gray-900 bg-white border border-gray-200 hover:bg-gray-100 hover:text-blue-700 focus:z-10 focus:ring-2 focus:ring-blue-700 focus:text-blue-700 dark:bg-gray-700 dark:border-gray-600 dark:text-white dark:hover:text-white dark:hover:bg-gray-600 dark:focus:ring-blue-500 dark:focus:text-white rounded-md"
    v-on:click="reset"
  >X</button>
  <input
    :id="id"
    class="mt-2 w-50 rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
    type="file"
    :class="$attrs.class"
    @change="convertFileToBase64($event.target.files)"
  >
</template>

<script>
import { toBase64 } from '../util/file'

export default {
  props: {
    modelValue: {
      type: String,
      default: null,
    },
    label: {
      type: String,
      default: null,
      required: false,
    },
    id: {
      type: String,
      required: true,
    },
  },
  emits: ['update:modelValue'],
  methods: {
    reset() {
      this.$emit('update:modelValue', '')
    },
    async convertFileToBase64(files) {
      if (files.length) {
        const value = await toBase64(files[0])

        this.$emit('update:modelValue', value)
      }
    },
  }
}
</script>
