<template>
  <div class="col border mx-2 rounded px-2 py-2">
    <label v-if="label" :for="`${name}-input`" class="form-label">{{
      label
    }}</label>
    <input
      ref="fileInput"
      :id="`${name}-input`"
      :name="name"
      :label="label"
      @change="handleFileChange"
      type="file"
      style="display: none"
      :placeholder="label"
      @blur="handleBlur"
    />
    <div class="mt-2">
      <template v-if="value">
        <a :href="value" target="_blank" class="btn btn-primary btn-block btn-rounded">Lihat File</a>
      </template>
      <div class="d-flex mt-2">
        <button
          type="button"
          class="btn btn-light btn-sm btn rounded btn border btn-block"
          @click="openFilePicker"
        >
          Select File
        </button>
        <button
          v-if="canRemove"
          style="width: 100px"
          type="button"
          class="btn btn-danger btn-sm btn rounded btn border btn-block ms-2"
          @click="handleFileRemove"
        >
          <i class="fa fa-trash"></i>
        </button>
      </div>
    </div>
    <div class="text-danger">{{ errorMessage }}</div>
    <slot name="additional-field"> </slot>
  </div>
</template>
<script setup>
import { useField } from "vee-validate";
import { ref } from "vue";
const emit = defineEmits(["update:modelValue", "remove", "change"]);
const props = defineProps({
  modelValue: {
    default: null,
  },
  name: {
    type: String,
    required: false,
  },
  label: {
    type: String,
    required: false,
    default: null,
  },
  successMessage: {
    type: String,
    default: "",
  },
  placeholder: {
    type: String,
    default: "",
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  rules: {
    default: null,
  },
  canRemove: {
    default: false,
    type: Boolean,
  },
});

const existingPhoto = ref(null);

const { value, errorMessage, handleBlur } = props.name
  ? useField(() => props.name, props.rules, {
      syncVModel: true,
    })
  : { value: ref(props.modelValue), errorMessage: null, handleBlur: null };
const fileInput = ref(null);
const openFilePicker = () => {
  fileInput.value.click();
};
const handleFileChange = (event) => {
  value.value = event.target.files[0];
  emit("change", value.value);
};
const isBlob = (variable) => {
  return variable instanceof Blob;
};
const createObjectURL = (obj) => {
  return URL.createObjectURL(obj);
};

const openFile = (file) => {
  window.open(file);
};

const handleFileRemove = () => {
  emit("remove");
};
</script>
