<template>
  <div class="flex w-full flex-col space-y-2">
    <template v-if="isWrapper">
      <div class="flex flex-row relative">
        <input
          type="file"
          style="
            opacity: 0;
            width: 100%;
            height: 100%;
            left: 0;
            overflow: hidden;
            position: absolute;
            z-index: 10;
          "
          :accept="accept"
          :multiple="isMultiple"
          @change="uploadHandler"
        />
        <slot name="content" />
      </div>
    </template>
    <template v-else>
      <ts-normal-text>
        <slot name="title" />
      </ts-normal-text>
      <div
        class="rounded flex flex-row items-center justify-center relative space-x-2 py-3 border-[1px] border-gray-400 border-dashed"
      >
        <input
          type="file"
          style="
            opacity: 0;
            width: 100%;
            height: 100%;
            left: 0;
            overflow: hidden;
            position: absolute;
            z-index: 10;
          "
          :accept="accept"
          :multiple="isMultiple"
          @change="uploadHandler"
        />
        <ts-icon :name="`${iconName}`" :customClass="'h-[13px]'" />
        <ts-normal-text color="text-paragraphTextLight">
          {{ placeholder }}
        </ts-normal-text>
      </div>
    </template>
  </div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import TsNormalText from "../TsTypography/normalText.vue";
import TsIcon from "../TsIcon/index.vue";

export default defineComponent({
  components: {
    TsNormalText,
    TsIcon,
  },
  props: {
    placeholder: {
      type: String,
      default: "Upload File",
    },
    iconName: {
      type: String,
      default: "upload",
    },
    accept: {
      type: String,
      default: "*",
    },
    isWrapper: {
      type: Boolean,
      default: false,
    },
    isMultiple: {
      type: Boolean,
      default: false,
    },
  },
  emits: ["update:modelValue", "update:localFileUrl"],
  name: "TsFileAttachment",
  setup(props: any, context: any) {
    const uploadHandler = (e: any) => {
      const input = e.target;

      if (props.isMultiple) {
        const files = input.files;

        context.emit("update:modelValue", files);
      } else {
        const file = input.files[0];

        context.emit("update:modelValue", file);

        // create readable url
        const fr = new FileReader();
        fr.readAsDataURL(file);
        fr.addEventListener("load", () => {
          context.emit(
            "update:localFileUrl",
            fr.result?.toString() ? fr.result?.toString() : ""
          );
        });
      }

      input.value = "";
    };

    return {
      uploadHandler,
    };
  },
});
</script>
