<template>
  <v-card flat border="sm black" :loading="loading" class="px-0" :ripple="false">
    <v-toolbar class="px-5">
      <template #prepend>
        <span class="text-subtitle-1 font-weight-black">{{ tableTitle }}</span>
      </template>
      <template #append>
        <v-btn color="primary" variant="flat" size="large" density="comfortable" :text="buttonLabel"
          class="text-capitalize" />
      </template>
    </v-toolbar>
    <v-card-text class="pa-0 bg-red">
      <v-data-table :headers="headers" :items="items" :item-value="itemValue" :items-per-page="itemsPerPage"
        fixed-header hide-default-footer hide-default-header @click:row="$emit('row-click', $event)"
        style="max-height: calc(100vh - (200px))">
        <template v-for="(_, slotName) in $slots" #[slotName]="slotProps">
          <slot :name="slotName" v-bind="slotProps" />
        </template>
      </v-data-table>
    </v-card-text>
  </v-card>
</template>

<script setup lang="ts">
const selected = defineModel({
  type: Array as PropType<Array<string>>,
  default: () => [],
});
const page = defineModel("page", { type: Number, default: 0 });

const props = defineProps({
  headers: {
    type: Array as PropType<Array<Record<string, string | number>>>,
    required: true,
    default: () => [],
  },
  items: {
    type: Array as PropType<Array<Record<string, any>>>,
    required: true,
    default: () => [],
  },

  itemValue: {
    type: String,
    default: "_id",
  },
    itemsPerPage: {
    type: Number,
    default: 20,
  },
  loading: {
    type: Boolean,
    required: true,
    default: true,
  },
  tableTitle: {
    type: String,
    default: "",
    required: false
  },
  buttonLabel: {
    type: String,
    default: "Add",
    required: false
  }
});

const emit = defineEmits(["refresh", "update:pagination", "row-click"]);

function increment() {
  page.value++;
  emit("update:pagination", page.value);
}

function decrement() {
  page.value--;
  emit("update:pagination", page.value);
}

function tableRowClickHandler(_: any, row: any) {
  const item = props.items[row.index];
  emit("row-click", item);
}

const selectAll = ref(false);

watch(selectAll, (curr) => {
  selected.value.splice(0, selected.value.length);
  if (curr) {
    const ids = props.items.map((i) => i._id as string);
    selected.value.push(...ids);
  }
});
</script>
