<template>
  <div class="bg-m-secondary w-[507px] h-[367px] rounded-md mx-4 shadow-md/50 shadow-black">
    <p class="font-bold text-3xl text-m-tertiary my-1 mx-3">
      {{ title }}
    </p>

    <div v-if="loading">
      <div
        v-for="n in 6"
        :key="`backup-skeleton-${n}`"
        class="relative w-[483px] h-[39px] mx-3 mb-[10px]"
      >
        <ButtonSkeleton custom-class="h-full w-full" />
        <div class="absolute inset-0 flex items-center justify-between px-3">
          <TextSkeleton custom-class="h-5 w-[260px]" />
          <CircleSkeleton custom-class="h-6 w-6 rounded-md" />
        </div>
      </div>
    </div>

    <button
        v-else
        v-for="file in backups"
        :key="file"
        class="bg-m-tertiary w-[483px] h-[39px] rounded-md shadow-md/50 shadow-m-black mx-3 mb-[10px] flex items-center justify-between cursor-pointer"
        @click="downloadBackup(file)"
    >
      <p class="text-xl ml-3 truncate max-w-[400px]">
        {{ file }}
      </p>

      <IconifyIcon
          icon="mdi:download"
          class="text-black text-2xl mr-3"
      />
    </button>
  </div>
</template>
<script setup lang="ts">
import {Icon as IconifyIcon} from "@iconify/vue"
import ButtonSkeleton from "~/components/skeleton/ButtonSkeleton.vue"
import CircleSkeleton from "~/components/skeleton/CircleSkeleton.vue"
import TextSkeleton from "~/components/skeleton/TextSkeleton.vue"

const props = defineProps<{
  folder: string | null
}>()

const backups = ref<string[]>([])
const loading = ref(false)
const title = computed(() => {
  if (!props.folder) return "Backup"
  return `Liste des backup de ${props.folder.toUpperCase()}`
})

const downloadBackup = (file: string) => {
  if (!props.folder) return
  const url = `/api/download?folder=${encodeURIComponent(props.folder)}&file=${encodeURIComponent(file)}`
  window.location.href = url
}

watch(() => props.folder, async (folder) => {
  if (!folder) {
    loading.value = false
    backups.value = []
    return
  }

  loading.value = true
  try {
    const data = await $fetch<string[]>(`/api/backups?folder=${folder}`)
    backups.value = data.slice(0, 6)
  } catch (error) {
    console.error("Erreur récupération backups:", error)
    backups.value = []
  } finally {
    loading.value = false
  }
})
</script>
