<template>
  <div class="mt-20 flex flex-col items-center gap-5">
    <FloatLabel variant="in">
      <InputText id="collection" v-model="collectionName" variant="filled" />
      <label for="collection">Collection Name</label>
    </FloatLabel>
    <FileUpload
      name="files[]"
      :auto="false"
      :multiple="true"
      accept="image/*"
      custom-upload
      @uploader="onUpload"
    >
      <template #empty>
        <p>Drag and drop files here to upload.</p>
      </template>
    </FileUpload>
  </div>
</template>

<script setup lang="ts">
import type { FileUploadUploaderEvent } from "primevue";

const toast = useToast();
const collectionName = ref("");

const onUpload = async (event: FileUploadUploaderEvent) => {
  const files = Array.isArray(event.files) ? event.files : [event.files];
  if (collectionName.value.trim().length === 0) {
    toast.error({
      title: "Collection name missing",
      message: "Please enter a valid collection name.",
    });
    return;
  }
  for (const file of files) {
    const formData = new FormData();
    formData.append("image", file);
    formData.append("name", toTitleCaseWithSpaces(parseImageName(file.name)));
    formData.append("collection_name", collectionName.value);

    try {
      await $fetch("/api/cards/", {
        method: "POST",
        body: formData,
        baseURL: useApiBase(),
      });
      toast.success({
        title: "Success!",
        message: "Files uploaded successfully",
      });
    } catch (e) {
      console.error(e);
      toast.error({
        title: "Upload failed!",
        message: "Something went wrong.",
      });
    }
  }
};
</script>
