<template>
  <div class="block">
    <div class="grid">
      <div v-if="!previews.length" class="col-12">
        <div class="w-full border-2 border-round border-gray-200 h-6rem">
          <label
            for="image_url"
            class="flex align-item-center justify-content-center cursor-pointer"
          >
            <div class="pt-4">
              <i class="pi pi-cloud-upload" style="font-size: 2.5rem"></i>
              Upload Your Gallery
            </div>
          </label>
        </div>
      </div>
      <div
        v-else
        v-for="(preview, key) of previews"
        :key="'image' + key"
        class="md:col-4 lg:col-3 xl:col-2"
      >
        <div class="relative">
          <span
            @click="removeFile(key)"
            class="right absolute mt-1 mr-1 top-0 right-0 cursor-pointer text-red-500 px-1 border-round py-1 text-sm"
            ><i class="pi pi-times" style="font-size: 1rem"></i
          ></span>
          <img
            v-if="preview"
            :src="preview"
            :alt="preview"
            class="block border-round cursor-pointer border-solid border-2 surface-border w-full block border-cyan-700 mt-2"
          />
        </div>
      </div>
    </div>
    <div class="block">
      <div
        class="flex block border-solid border-2 block surface-border border-round text-blue-500"
      >
        <label
          class="flex-grow-1 px-3 py-2 text-overflow-ellipsis cursor-pointer"
          for="image_url"
          >{{
            totalFile > 0
              ? totalFile +
                (totalFile > 1 ? " files selected" : " file selected")
              : "Select File ..."
          }}
        </label>
        <Button
          v-if="totalFile"
          text
          icon="pi pi-times"
          severity="danger"
          class="w-5rem right-0 flex-shrink-0"
          @click="clearFile"
        ></Button>
      </div>
      <input
        type="file"
        multiple
        ref="fileRef"
        id="image_url"
        class="hidden"
        accept="image/*"
        @change="changeImg"
      />
    </div>
  </div>
</template>
<script setup>
import { ref, computed, onMounted, watch } from "vue";

const files = ref([]);
const fileRef = ref([]);
const totalFile = computed(() => {
  return files.value?.length;
});
const emits = defineEmits(["update:modelValue"]);
const props = defineProps({
  initialize: {
    type: Array,
    default: [],
  },
  value: {
    type: Array,
    default: [],
  },
});
const previews = ref([]);

const toBase64 = async (file) => {
  const reader = new FileReader();
  await new Promise((resolve, reject) => {
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
  });
  return reader.result;
};
const changeImg = (event) => {
  const images = [...event.target.files];
  const existing = [...files.value];
  images.forEach((image) => {
    if (!imageExist(image, existing)) {
      existing.push(image);
    }
  });
  files.value = [...existing];
  initPreview(files.value)
  emits("update:modelValue", files.value);
};
watch(
  () => props.initialize,
  (newValue) => {
    files.value = newValue
    initPreview(newValue);
  }
);
const initPreview = async (filePrev) => {
  const images = [];
  for (const image of filePrev) {
    const newFile = await toBase64(image);
    images.push(newFile);
  }
  previews.value = [...images];
};
const imageExist = (file, files) => {
  files.forEach((item) => {
    if (_.isEqual(file, item)) {
      return true;
    }
  });
  return false;
};

const removeFile = (index) => {
  const newFileList = [...files.value];
  newFileList.splice(index, 1);
  files.value = [...newFileList];
  fileRef.value = newFileList;
  initPreview(files.value)
  emits("update:modelValue", files.value);
};
const clearFile = () => {
  files.value = [];
  initPreview(files.value)
  emits("update:modelValue", files.value);
};
onMounted(() => {});
</script>