<template>
  <TableListSecondary
    :headers="headers"
    :items="items"
    :pages="pages"
    :page-range="pageRange"
    :loading="loading"
    :height="height"
    :page="page"
    v-model="selected"
    @update:pagination="_getItems"
    @click:row="onRowClick"
    :length="pages"
    :clickable-rows="clickableRows"
    @update:page="onPageChange"
  >
    <template #title>
      <slot name="title" />
    </template>

    <template #action-button>
      <slot name="action-button" />
    </template>

    <template
      v-for="header in headers"
      :key="header.value"
      #[header.value]="slotProps"
    >
      <slot :name="header.value" v-bind="slotProps" />
    </template>

    <template #action-table="{ item }">
      <slot name="action-table" :item="item" />
    </template>
  </TableListSecondary>
</template>

<script lang="ts" setup>
import { getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";

const emit = defineEmits(["click:create", "update:pagination", "row-click"]);
const page = defineModel("page", { type: Number, default: 1 });

const props = defineProps({
  headers: Array as PropType<any[]>,
  items: Array as PropType<any[]>,
  pages: Number,
  pageRange: String,
  page: Number,
  loading: Boolean,
  height: {
    type: String,
    default: "calc(100vh - 175px)",
  },
  viewPage: Object as PropType<{ name: string }>,
  org: String,
  site: String,
  id: String,
  getItems: Function as PropType<() => Promise<void>>,
  deleteItem: Function as PropType<(id: string) => Promise<void>>,
  clickableRows: {
    type: Boolean,
    default: false,
  },
});

const selected = ref<string[]>([]);

async function _getItems() {
  if (props.getItems) {
    await props.getItems();
    emit("update:pagination");
  }
}

function onPageChange(newPage: number) {
  page.value = newPage;
  _getItems();
  emit("update:pagination", newPage);
}

function onRowClick(item: any) {
  emit("row-click", item);
}
</script>
