<template>
  <div>
    <v-row class="mb-4" align="center" no-gutters>
      <v-col
        cols="10"
        class="pr-2"
        v-if="
          props.createdFrom === 'feedback' && props.attachments.length > 0
            ? false
            : true
        "
      >
        <div
          class="d-flex align-center justify-center pa-4 rounded-lg border-dashed border border-grey"
          @dragover.prevent
          @drop="handleDrop"
          style="position: relative; z-index: 1"
        >
          <v-file-input
            ref="dropInput"
            v-model="files"
            multiple
            hide-details
            :max-files="maxFiles"
            style="
              opacity: 0;
              position: absolute;
              inset: 0;
              z-index: 2;
              cursor: pointer;
            "
            @change="onFileChange"
          />
          <div
            class="d-flex align-center"
            style="z-index: 1; pointer-events: none"
          >
            <v-icon size="28" class="mr-2" color="primary"
              >mdi-cloud-upload-outline</v-icon
            >
            <span class="text-body-1 font-weight-medium"
              >Drag and drop files here</span
            >
          </div>
        </div>
      </v-col>

      <v-col
        cols="2"
        class="d-flex justify-center"
        v-if="
          props.createdFrom === 'feedback' && props.attachments.length > 0
            ? false
            : true
        "
      >
        <v-btn
          color="primary-button"
          min-width="55"
          width="55"
          height="55"
          elevation="0"
          @click="selectAttachment"
        >
          <v-icon size="20">mdi-camera-outline</v-icon>
        </v-btn>
      </v-col>
    </v-row>

    <v-sheet v-if="attachments.length > 0" elevation="0" class="py-3" rounded>
      <v-row no-gutters>
        <v-col
          v-for="(file, index) in attachments"
          :key="index"
          cols="12"
          class="d-flex align-center pa-2 mr-2 mb-2 rounded bg-white border-sm"
        >
          <div class="mr-3">
            <!-- <v-img
              v-if="!localErroredImages.includes(file)"
              :src="file"
              width="40"
              height="40"
              class="rounded"
              cover
              @error="onImageError(file)"
            />
            <v-img
              v-else
              :src="getThumbnail(file)"
              width="40"
              height="40"
              class="rounded"
              cover
            /> -->
            <v-img
              :src="getThumbnail(file)"
              width="40"
              height="40"
              class="rounded"
              cover
            />
          </div>

          <div class="flex-grow-1 text-truncate">
            {{ getDisplayName(file) }}
          </div>

          <v-icon
            size="small"
            @click.stop="$emit('delete', file)"
            v-if="
              props.createdFrom === 'feedback' && props.attachments.length > 0
                ? false
                : true
            "
          >
            mdi-trash-can-outline
          </v-icon>
        </v-col>
      </v-row>
    </v-sheet>
  </div>
</template>

<script setup lang="ts">
const props = defineProps<{
  attachments: string[];
  erroredImages?: string[];
  maxFiles?: number;
  createdFrom?: string;
}>();

const emit = defineEmits<{
  (e: "add", file: File): void;
  (e: "delete", url: string): void;
  (e: "errored", url: string): void;
}>();

const dropInput = ref<any>(null);
const files = ref<File[]>([]);
const localErroredImages = ref<string[]>(props.erroredImages || []);
// Store file names for display
const fileNamesMap = ref<Record<string, string>>({});

watch(
  () => props.erroredImages,
  (val) => {
    if (val) {
      localErroredImages.value = val;
    }
  }
);

function handleDrop(event: DragEvent) {
  const droppedFiles = event.dataTransfer?.files;
  if (droppedFiles?.length) {
    files.value = Array.from(droppedFiles);
    onFileChange();
  }
}

function selectAttachment() {
  const input = dropInput.value?.$el?.querySelector(
    "input[type='file']"
  ) as HTMLInputElement | null;
  input?.click();
}

function onFileChange() {
  if (files.value.length) {
    console.log(
      "onFileChange triggered with files:",
      files.value.map((f) => f.name)
    );

    const maxFiles = props.maxFiles || 5;
    if (files.value.length > maxFiles) {
      console.warn(`Too many files selected. Maximum allowed: ${maxFiles}`);
      files.value = [];
      return;
    }

    files.value.forEach((file) => {
      console.log(`Emitting 'add' event for file: ${file.name}`);
      // For each file, we'll also need to store its original name
      // This will be associated with the file URL in the parent component
      emit("add", file);
    });

    files.value = [];
  }
}

function onImageError(file: string) {
  console.log(`Image error for file: ${file}`);
  emit("errored", file);
}

function getThumbnail(fileUrl: string): string {
  // if (fileUrl.endsWith(".pdf")) return "mdi-file-pdf-outline";
  // if (fileUrl.match(/\.(doc|docx)$/i))
  //   return "/images/file-thumbnails/word.png";
  // if (fileUrl.match(/\.(xls|xlsx)$/i))
  //   return "/images/file-thumbnails/excel.png";
  // return "/images/file-thumbnails/file.png";
  return `/api/public/${fileUrl}`;
}

// Modified to try to display the friendly name
function getFileName(fileUrl: string): string {
  try {
    const url = new URL(fileUrl);
    return decodeURIComponent(url.pathname.split("/").pop() || "");
  } catch (e) {
    return fileUrl.split("/").pop() || "";
  }
}

// This will use our stored file names when available
function getDisplayName(fileUrl: string): string {
  // If we have a friendly name stored, use it
  if (fileNamesMap.value[fileUrl]) {
    return fileNamesMap.value[fileUrl];
  }
  // Otherwise fall back to the ID/URL-based name
  return getFileName(fileUrl);
}

// Method to update file names map - will be called from parent
defineExpose({
  updateFileName: (url: string, name: string) => {
    fileNamesMap.value[url] = name;
  },
});
</script>
