<template>
  <div class="upload-slot">
    <div class="wrapper">
      <div class="image-container">
        <div class="icon-container remove" @click="remove">
          <div class="icon small">
            <SpIcon name="sp-close" />
          </div>
        </div>

        <div v-if="imageType && image" class="image">
          <img :src="image" />
        </div>
        <iframe
          v-else-if="!imageType && iframe"
          :src="iframe"
          frameborder="0"
          scrolling="no"
        ></iframe>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, watch } from "vue";

export default defineComponent({
  props: {
    file: {
      type: File,
      required: true,
    },
  },
  emits: ["remove"],
  setup(props, { emit }) {
    const state: {
      imageType: boolean;
      image: string;
      iframe: string;
    } = reactive({
      imageType: false,
      image: "",
      iframe: "",
    });

    const remove = (): void => {
      emit("remove");
    };

    const RenderFile = (file: File): void => {
      const reader = new FileReader();
      if (props.file.type === "image/jpeg" || file.type === "image/png") {
        reader.onload = (e) => {
          state.image = e.target.result as string;
          state.imageType = true;
        };
      } else {
        reader.onload = (e) => {
          state.iframe = e.target.result as string;
          state.imageType = false;
        };
      }

      reader.readAsDataURL(file);
    };

    onMounted(() => {
      RenderFile(props.file);
    });

    watch(
      () => props.file,
      (newValue) => {
        if (newValue) {
          RenderFile(newValue);
        }
      }
    );

    return {
      ...toRefs(state),
      remove,
    };
  },
});
</script>

<style scoped lang="scss">
.upload-slot {
  --image-size: 88px;
  --flex-direction: row;

  .wrapper {
    position: relative;
    display: flex;
    align-items: center;
    flex-direction: var(--flex-direction);

    .icon-container {
      position: absolute;
      right: 0;
      top: 0;
      transform: translate(25%, -25%);
      border-radius: 50%;
      overflow: hidden;
      padding: 4px;
      background-color: var(--background-primary);
      box-shadow: 0px 0px 7px rgba(0, 0, 0, 0.2);
      cursor: pointer;
    }

    .image-container {
      width: var(--image-size);
      height: var(--image-size);
      background-color: var(--grey-4);
      position: relative;
      border-radius: 16px;

      .image {
        overflow: hidden;
        border-radius: 16px;
        border: 1px solid var(--grey-4);
        width: 100%;
        height: 100%;
      }

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        object-position: center;
      }

      iframe {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
