<!--
Tableau interactif conçu pour l'affichage d'une collection d'entités

@see https://vuetifyjs.com/en/components/data-tables/
-->

<template>
  <v-col cols="12" sm="12">
    <v-data-table
      :headers="headersWithItem"
      :items="collection.items"
      :server-items-length="collection.pagination.totalItems"
      :loading="$fetchState.pending"
      class="elevation-1"
    >
      <template v-for="header in headersWithItem" #[header.item]="props">
        <slot :name="header.item" v-bind="props">
          {{ props.item[header.value] }}
        </slot>
      </template>

      <template #item.actions="{ item }">
        <v-icon small class="mr-2" @click="editItem(item)"> mdi-pencil </v-icon>
        <v-icon small @click="deleteItem(item)"> mdi-delete </v-icon>
      </template>
    </v-data-table>
  </v-col>
</template>

<script setup lang="ts">
import { ref, toRefs } from 'vue'
import type { Ref } from 'vue'
import { useEntityFetch } from '~/composables/data/useEntityFetch'
import ApiResource from '~/models/ApiResource'
import type { AnyJson } from '~/types/data'

const props = defineProps({
  parent: {
    type: Object,
    required: true,
  },
  model: {
    type: Object,
    required: true,
  },
  headers: {
    type: Array,
    required: true,
  },
})

const { parent, model, headers } = toRefs(props)

const headersWithItem = computed(() => {
  return headers.value.map((header: any) => {
    header.item = 'item.' + header.value
    return header
  })
})

const totalEntries: Ref<number> = ref(0)
const entries: Ref<Array<AnyJson>> = ref(Array<AnyJson>())

const { fetchCollection } = useEntityFetch()

const { data: collection, pending } = await fetchCollection(
  model.value as typeof ApiResource,
  parent.value as ApiResource,
)

const itemId: Ref<number> = ref(0)

const editItem = (item: AnyJson) => {
  itemId.value = item.id
}
</script>
