<script setup lang="ts">
import {computed, watch} from "vue";

const emit = defineEmits([
    'update:search',
    'update:selected',
    'updateTable',
    'deleteItems',
    'editItem',
    'cancelItem'
])

const props = defineProps({
  headers: Array,
  listData: Object,
  items: Array,
  selected: Array,
  loading: Boolean,
  search: String,
  itemValue: String,
  showSelect: Boolean,
  actions: Boolean,
})

const searchValue = computed({
  get() {
    return props.search
  },
  set(value) {
    console.log(value)
    emit('update:search', value)
  }
})

const selectedValues = computed({
  get() {
    return props.selected
  },
  set(values) {
    console.log(props.selected, values)
    emit('update:selected', values)
  }
})

// const selected = ref([])
// const search = ref('')
//
// watch(search, (newValue, oldValue) => {
//   $emit('updateSearch', newValue)
// })
//
// watch(selected, (newValue, oldValue) => {
//   $emit('updateSelected', newValue)
// })

const update = (page_info) => {
  console.log(page_info)
  emit('updateTable', page_info)
}
</script>

<template>
  <div>
    <v-data-table-server
        :headers="headers"
        v-model="selectedValues"
        v-model:items-per-page="listData.itemsPerPage"
        :items="items"
        :items-length="listData.total_items"
        loading-text="Loading..."
        :loading="loading"
        @update:options="update"
        :item-value="itemValue"
        disable-sort
        return-object
        :show-select="showSelect"
    >
      <template v-slot:top>
        <v-toolbar flat>
          <v-text-field
              v-model="searchValue"
              class="ma-2 search"
              density="compact"
              placeholder="Cerca"
              hide-details
          ></v-text-field>
          <v-divider />
          <slot name="header-buttons"></slot>
          <v-btn color="primary">
            <v-icon
                class="me-2"
                size="small"
                :disabled="selectedValues.length === 0"
                @click="$emit('deleteItem', selected)"
            >
              mdi-delete
            </v-icon>
          </v-btn>
        </v-toolbar>
        <slot name="dialog"></slot>
      </template>

      <template v-slot:item.artwork="{ item }">
        <div v-if="item.artwork != ''" v-html="`<img src='/${item.artwork}.jpg' />`"></div>
      </template>

      <template v-if="actions" v-slot:item.actions="{ item }">
        <v-icon
            class="me-2"
            size="small"
            @click="$emit('editItem', item)"
        >
          mdi-pencil
        </v-icon>
        <v-icon
            size="small"
            @click="$emit('deleteItem', item)"
        >
          mdi-delete
        </v-icon>
      </template>
    </v-data-table-server>
  </div>
</template>

<style scoped>
.search {
  min-width:250px;
}
</style>