<script setup lang="ts">
  import FileUpload, {type FileUploadUploadEvent} from 'primevue/fileupload';
  import Button from 'primevue/button';
  import Badge from 'primevue/badge';
  import Message from 'primevue/message';
  import Dialog from 'primevue/dialog';
  import {ref} from "vue";
  import {useToast} from "primevue/usetoast";
  import ProgressBar from 'primevue/progressbar';
  import type {FileCreationResultDto} from "@/dto/file-creation-result-dto.ts";
  import type {FileCreationErrorDto} from "@/dto/file-creation-error-dto.ts";
  
  const emit = defineEmits(["uploaded"]);
  
  const totalSize = ref(0);
  const totalSizePercent = ref(0);
  const files = ref([]);
  
  const visible = ref(false);
  
  const toast = useToast();
  const filename = ref<string>("");
  
  const onRemoveTemplatingFile = (file, removeFileCallback, index) => {
    removeFileCallback(index);
    totalSize.value -= parseInt(formatSize(file.size));
    totalSizePercent.value = totalSize.value / 10;
  };
  
  const onClearTemplatingUpload = (clear) => {
    clear();
    totalSize.value = 0;
    totalSizePercent.value = 0;
  };
  
  const onSelectedFiles = (event) => {
    files.value = event.files;
    files.value.forEach((file) => {
      totalSize.value += parseInt(formatSize(file.size));
    });
  };
  
  const uploadEvent = (callback) => {
    totalSizePercent.value = totalSize.value / 10;
    callback();
  };
  
  const onTemplatedUpload = (ev : FileUploadUploadEvent) => {
    const resp = JSON.parse(ev.xhr.responseText) as FileCreationResultDto | FileCreationErrorDto;
    if ('filename' in resp) {
      filename.value = resp.filename;
      visible.value = true;
      emit("uploaded");
    } else if ('reason' in resp) {
      toast.add({
        severity: "error",
        detail: `There was an error uploading your file: ${resp.reason}`,
      })
    }
  };
  
  const formatSize = (bytes) => {
    const k = 1024;
    const dm = 3;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  
    if (bytes === 0) {
      return `0 ${sizes[0]}`;
    }
  
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    const formattedSize = parseFloat((bytes / Math.pow(k, i)).toFixed(dm));
  
    return `${formattedSize} ${sizes[i]}`;
  };
</script>

<template>
  <FileUpload name="formFile" url="/api/file/upload" @upload="onTemplatedUpload($event)" :multiple="false" :maxFileSize="52428800">
    <template #header="{ chooseCallback, uploadCallback, clearCallback, files }">
      <div class="flex flex-wrap justify-between items-center flex-1 gap-4">
        <div class="flex gap-2">
          <Button @click="chooseCallback()" icon="pi pi-images" rounded outlined severity="secondary"></Button>
          <Button @click="uploadEvent(uploadCallback)" icon="pi pi-cloud-upload" rounded outlined severity="success" :disabled="!files || files.length === 0"></Button>
          <Button @click="clearCallback()" icon="pi pi-times" rounded outlined severity="danger" :disabled="!files || files.length === 0"></Button>
        </div>
        <ProgressBar :value="totalSizePercent" :showValue="false" class="md:w-20rem h-1 w-full md:ml-auto">
          <span class="whitespace-nowrap">{{ totalSize }}B / 1Mb</span>
        </ProgressBar>
      </div>
    </template>
    <template #content="{ files, uploadedFiles, removeUploadedFileCallback, removeFileCallback, messages }">
      <div class="flex flex-col gap-8 pt-4">
        <Message v-for="message of messages" :key="message" :class="{ 'mb-8': !files.length && !uploadedFiles.length}" severity="error">
          {{ message }}
        </Message>

        <div v-if="files.length > 0">
          <h5>Pending</h5>
          <div class="flex flex-wrap gap-4">
            <div v-for="(file, index) of files" :key="file.name + file.type + file.size" class="p-8 rounded-border flex flex-col border border-surface items-center gap-4">
              <span class="font-semibold text-ellipsis max-w-60 whitespace-nowrap overflow-hidden">{{ file.name }}</span>
              <div>{{ formatSize(file.size) }}</div>
              <Badge value="Pending" severity="warn" />
              <Button icon="pi pi-times" @click="onRemoveTemplatingFile(file, removeFileCallback, index)" outlined rounded severity="danger" />
            </div>
          </div>
        </div>

        <div v-if="uploadedFiles.length > 0">
          <h5>Completed</h5>
          <div class="flex flex-wrap gap-4">
            <div v-for="(file, index) of uploadedFiles" :key="file.name + file.type + file.size" class="p-8 rounded-border flex flex-col border border-surface items-center gap-4">
              <span class="font-semibold text-ellipsis max-w-60 whitespace-nowrap overflow-hidden">{{ file.name }}</span>
              <div>{{ formatSize(file.size) }}</div>
              <Badge value="Completed" class="mt-4" severity="success" />
              <Button icon="pi pi-times" @click="removeUploadedFileCallback(index)" outlined rounded severity="danger" />
            </div>
          </div>
        </div>
      </div>
    </template>
    <template #empty>
      <div class="flex items-center justify-center flex-col">
        <i class="pi pi-cloud-upload !border-2 !rounded-full !p-8 !text-4xl !text-muted-color" />
        <p class="mt-6 mb-0">Drag and drop files to here to upload.</p>
      </div>
    </template>
  </FileUpload>
  <Dialog v-model:visible="visible" modal header="Success!" :style="{ width: '30rem' }">
    <div class="space-y-3">
      <p>Your file has been uploaded and is now accessible at:</p>
      <div class="p-5 bg-neutral-950 text-gray-50 rounded-2xl font-bold ">
        https://localhost:5118/f/{{ filename }}
      </div>
      <Button label="Click to copy" class="float-right"/>
    </div>
  </Dialog>
</template>

<style scoped>

</style>