<script setup lang="ts">
import type { TableColumn } from "@nuxt/ui";

const UButton = resolveComponent("UButton");

defineProps<{
  data: FileEntry[];
  status: "pending" | "idle" | "success" | "error";
}>();

const emit = defineEmits<{
  rename: [file: FileEntry];
  delete: [file: FileEntry];
}>();

const formatSize = (bytes: number): string => {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
};

const formatDate = (iso: string): string =>
  new Date(iso).toLocaleDateString(undefined, { dateStyle: "medium" });

const columns: TableColumn<FileEntry>[] = [
  { accessorKey: "name", header: "Name" },
  {
    accessorKey: "size",
    header: "Size",
    cell: ({ row }) => formatSize(row.original.size),
  },
  {
    accessorKey: "modifiedAt",
    header: "Modified",
    cell: ({ row }) => formatDate(row.original.modifiedAt),
  },
  {
    id: "actions",
    cell: ({ row }) =>
      h("div", { class: "flex justify-end gap-1" }, [
        h(UButton, {
          icon: "i-lucide-pencil",
          variant: "ghost",
          size: "sm",
          onClick: () => emit("rename", row.original),
        }),
        h(UButton, {
          icon: "i-lucide-trash-2",
          variant: "ghost",
          size: "sm",
          color: "error",
          onClick: () => emit("delete", row.original),
        }),
      ]),
  },
];
</script>

<template>
  <UTable
    :data="data"
    :columns="columns"
    :loading="status === 'pending' || status === 'idle'"
  >
    <template #empty>
      {{ status === "pending" || status === "idle" ? "Loading..." : "No files" }}
    </template>
  </UTable>
</template>
