<script setup lang="ts">
import { ref, watch } from "vue";
import type { UserDataFileInfo } from "@/types";
import { useFileUpload } from "@/composables";

const props = defineProps<{
  fileInfo: UserDataFileInfo | null;
  readOnly: boolean;
}>();
const emit = defineEmits(["fileUploaded", "fileDeleted"]);

const selectedFile = ref();
const {
  upload: uploadFile,
  loading: uploadLoading,
  error: uploadError,
  fileInfo: uploadInfo,
} = useFileUpload();

watch(
  () => props.fileInfo,
  (newVal) => {
    selectedFile.value = newVal;
  },
  { immediate: true }
);

watch(uploadInfo, (info) => {
  console.log("fileInfo changed", info);
  selectedFile.value = info;
  emit("fileUploaded", info.id);
});

function handleDelete() {
  selectedFile.value = null;
  emit("fileDeleted");
}
</script>

<template>
  <div>
    <h4 class="mb-2 text-xl">{{ $t("a.Datei hochladen") }}</h4>

    <template v-if="uploadLoading">
      {{ $t("a.Laden...") }}
    </template>

    <template v-else>
      <template v-if="!selectedFile">
        <div
          :class="[props.readOnly ? 'text-blue-600' : 'cursor-pointer text-blue-800']"
          class="relative mb-4 flex items-center"
        >
          <input
            v-if="!props.readOnly"
            id="upload"
            type="file"
            class="absolute opacity-0"
            accept=".pdf,.jpg,.jpeg,.png,.doc,.docx,.mov,.ppt,.pptx,.mp4"
            :disabled="uploadLoading"
            @change="uploadFile"
          />
          <it-icon-document class="mr-1.5 h-7 w-7 text-blue-800" />
          {{ $t("a.Datei auswählen") }}
        </div>
        <p class="text-sm text-gray-900">
          {{ $t("a.Mögliche Formate") }}: .JPG, .PNG, .PDF, .DOC, .MOV, .PPT, .MP4
        </p>
        <p class="mb-8 text-sm text-gray-900">
          {{ $t("a.Maximale Dateigrösse") }}: 50 MB
        </p>
      </template>

      <template v-else>
        <div class="flex items-center gap-x-2">
          <h4 class="mr-4 text-lg font-bold">{{ selectedFile.name }}</h4>
          <a v-if="!props.readOnly" class="flex cursor-pointer" @click="handleDelete">
            <it-icon-delete class="h-8 w-8" />
          </a>
          <a :href="selectedFile.url" class="flex">
            <it-icon-download class="h-8 w-8" />
          </a>
        </div>
      </template>

      <p v-if="uploadError" class="mt-3 text-red-700">
        {{ $t("a.Datei kann nicht gespeichert werden.") }}
      </p>
    </template>
  </div>
</template>
